1
votes

I have a cloudformation stack which has update policy as rolling update (AutoScalingRollingUpdate). This stack takes the latest ami from our org. repo and do a rolling update. This runs fine, but involves manual invention. Someone needs to manually go to Cloudformation console and run an update in every few days. I'm trying to automate this and here's my thought: Set up a schedule based rule using Cloudwatch (cron expression) and trigger a lambda function. Once triggered, the lambda should invoke the existing stack. My question is 1) does this seem doable? 2) has anyone written any lambda function(preferably in python) for this?

Attaching a high level architectureenter image description here

1

1 Answers

1
votes

Totally doable. The CloudFormation template would look something like that:

Resources:
  AmiUpdateLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code: ami_updater.py
      Handler: ami_updater.lambda_handler
      Runtime: python3.6
      Timeout: 300
      MemorySize: 128

  AmiUpdateLambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      ManagedPolicyArns:
      - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole 
      # Add policy for updating the Cloudformation stack

  AmiUpdateTriggerEvent:
    Type: AWS::Events::Rule
    Properties:
      ScheduleExpression: "rate(15 day)"
      State: ENABLED
      Targets:
        - Arn: !GetAtt AmiUpdateLambdaFunction.Arn
          Id: AmiUpdateTriggerEvent

  AmiUpdateLambdaPermission:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName: !Ref AmiUpdateLambdaFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt AmiUpdateTriggerEvent.Arn

As for the Python code it's gonna depend on how your AMIs can be found but it shouldn't be rocket science. Then using boto3 use the update_stack method (documentation) and input the new AMI in there.