0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWS初心者の勉強メモ:CloudFormationを使って最小構成のバッチ環境を作ってみた

0
Posted at

はじめに

AWS の勉強の一環で、CloudFormationを利用し、サーバレスのバッチ環境を構築したのでメモ。

構成図

EventBridge
↓
Lambda
↓
S3

処理の流れはシンプルです。

  1. EventBridgeが1時間ごとに実行
  2. Lambdaが起動
  3. 実行結果をS3へ保存

目的

今回の目的は、CloudFormationの学習です。

コンソールで手動作成するのではなく、CloudFormationを利用することで、yamlファイルから容易に環境構築することが可能です。

使用したサービスは以下です。

  • CloudFormation
  • Lambda
  • EventBridge
  • IAM
  • S3

CloudFormationテンプレート

今回使用したテンプレートです。

AWSTemplateFormatVersion: "2010-09-09"

Resources:

  LogBucket:
    Type: AWS::S3::Bucket

  LambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole

      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

      Policies:
        - PolicyName: S3Write
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - s3:PutObject
                Resource:
                  - !Sub "${LogBucket.Arn}/*"

  BatchLambda:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: python3.12
      Handler: index.lambda_handler
      Role: !GetAtt LambdaRole.Arn

      Environment:
        Variables:
          BUCKET_NAME: !Ref LogBucket

      Code:
        ZipFile: |
          import boto3
          import os
          from datetime import datetime

          s3 = boto3.client('s3')

          def lambda_handler(event, context):

              filename = "batchLog_" + datetime.now().strftime("%Y%m%d%H%M%S") + ".txt"

              s3.put_object(
                  Bucket=os.environ['BUCKET_NAME'],
                  Key=filename,
                  Body="Batch Execute"
              )

              return {"statusCode": 200}

  BatchRule:
    Type: AWS::Events::Rule
    Properties:
      ScheduleExpression: cron(0 * * * ? *)

      Targets:
        - Arn: !GetAtt BatchLambda.Arn
          Id: LambdaTarget

  LambdaPermission:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName: !Ref BatchLambda
      Principal: events.amazonaws.com
      SourceArn: !GetAtt BatchRule.Arn

テンプレートについて

S3バケット

  LogBucket:
    Type: AWS::S3::Bucket

ログ保存先となるS3バケットの設定です。

IAMロール

  LambdaRole:
    Type: AWS::IAM::Role

Lambda実行用のIAMロールの設定です。

Lambda

  BatchLambda:
    Type: AWS::Lambda::Function

EventBridgeから定期実行されるLambdaの設定とコードです。

EventBridge

  BatchRule:
    Type: AWS::Events::Rule
    Properties:
      ScheduleExpression: cron(0 * * * ? *)

      Targets:
        - Arn: !GetAtt BatchLambda.Arn
          Id: LambdaTarget

EventBridgeの設定です。
毎時Lambdaを実行します。
起動タイミングはcron式で指定しています。

Lambda Permission

  LambdaPermission:
    Type: AWS::Lambda::Permission

EventBridgeからLambdaを実行できるようにするための権限設定です。

デプロイ

CloudFormationの「スタックの作成」からテンプレートをアップロードしてデプロイします。
デプロイ成功後、上記リソースが自動で作成されます。
image.png

動作確認

1時間に1回Lambdaが起動し、以下バケットにログ出力されることを確認できました。

image.png

まとめ

CloudFormationは複数のAWSリソースをまとめて管理できるため、環境構築が非常に楽になります。
作成されたリソースはスタック自体を削除すれば、まとめて削除されるとのことです。
チームでの開発では特に積極的に利用したい機能だと思いました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?