LoginSignup
2
1

More than 5 years have passed since last update.

AMIの更新通知をトリガーにlambdaからBatchをキックする(Serverless Frameworkも使うぜよ)

Last updated at Posted at 2018-07-13

AWSはAMIが更新された場合の連絡チャネルを準備してくれているようです
更新連絡をトリガーとして、lambdaからBatchをキックして、先回のAMIのコンピューティング環境自動更新を動かす試みです。

設定にあたり、Serverless Frameworkなるものを初めて使用したのですが素敵でした。
以下が、使用したserverless.ymlです。

serverless.yml
service: latest-ami-replace
provider:
  name: aws
  stage: ${opt:stage, self:custom.defaultStage}
  region: ${opt:region, self:custom.defaultRegion}
  runtime: python2.7
  iamRoleStatements:
      - Effect: Allow
        Action:
          - batch:SubmitJob
          - logs:CreateLogStream
          - logs:CreateLogGroup
          - logs:PutLogEvents
        Resource: "*"
custom:
  defaultStage: dev
  defaultRegion: ap-northeast-1
  environment:
    dev:
      JOB_DEFINITION: 'ami-replace:1'
      JOB_NAME:  'ami-replace'
      JOB_QUEUE: 'arn:aws:batch:ap-northeast-1:999999999999:job-queue/ami-replace'

functions:
  handler:
    handler: ami-replace.lambda_handler
    environment: ${self:custom.environment.${self:provider.stage}}
    timeout: 60

resources:
  Resources:

    SNSSubscription:
      Type: AWS::SNS::Subscription
      Properties:
          Endpoint: arn:aws:lambda:ap-northeast-1:999999999999:function:asd_latest_ami_replace
          Protocol: lambda
          TopicArn: arn:aws:sns:ap-northeast-1:177427601217:ecs-optimized-amazon-ami-update

lambda関数は以下です。Batchをcallしているだけの内容です。
上記ではami-replaceとしていますが、環境変数として任意に設定してください。

ami-replace.py
import boto3,os

def lambda_handler(event, context):
    client = boto3.client('batch')

    JOB_NAME = os.getenv("JOB_NAME")
    JOB_QUEUE = os.getenv("JOB_QUEUE")
    JOB_DEFINITION = os.getenv("JOB_DEFINITION")

    response = client.submit_job(
        jobName = JOB_NAME,
        jobQueue = JOB_QUEUE,
        jobDefinition = JOB_DEFINITION
        )

    print(response)
    return 0

上記のServerless Frameworkで登録した環境を削除すると、CloudFormationが以下のエラーを放ちます。
自分のリソースではないものは削除できない模様ですが、AWSが自ら公開しているリソースなのでなんとかして頂きたいところです。

Stack:arn:aws:cloudformation:ap-northeast-1:999999999999:stack/latest-ami-replace-dev/acc286e0-8406-11e8-9519-50a6866998ae is in DELETE_FAILED state and can not be updated.

今回のトピックのキモは、Serverless(CloudFormation)による操作では 外部topic登録できれど削除はできずというところくらいですね。ありがとうございました。

2
1
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
2
1