Use EventBridge rule to run SSM Automation runbook periodically

TOC

Use EventBridge rule to run SSM Automation runbook periodically

On the following pages, we have shown you how to run the SSM Automation runbook.

あわせて読みたい
Create AMI using SSM Automation (one-time/scheduled) 【Create AMI using SSM Automation (one-time/scheduled)】 There are several ways to create an AMI. For example, the following page shows how to create one fro...

The above pages covered how to use the maintenance window to periodically run the runbook.

In this case, we will use the EventBridge rule to run the runbook periodically.

The content to be executed in the runbook is the same as in the page above, but we will create an AMI for an EC2 instance.

Environment

Diagram of Use EventBridge rule to run SSM Automation runbook periodically.

Create two EC2 instances in one private subnet.
The instances will be the latest Amazon Linux 2.
The instances will be tagged and subject to the runbook described below.

Create SSM Automation runbook.
The content of the runbook is to execute the runbook AWS-CreateImage, which is owned by AWS.
The target of the runbook is an instance that has been assigned a specific tag.

Create an EventBridge rule.
Set the runbook to run periodically (once every 10 minutes).

CloudFormation template files

The above configuration is built with CloudFormation.
The CloudFormation templates are placed at the following URL

https://github.com/awstut-an-r/awstut-fa/tree/main/122

Explanation of key points of template files

(Reference) EC2 instance

Resources:
  Instance:
    Type: AWS::EC2::Instance
    Properties:
      IamInstanceProfile: !Ref InstanceProfile
      ImageId: !Ref ImageId
      InstanceType: !Ref InstanceType
      NetworkInterfaces:
        - DeviceIndex: 0
          SubnetId: !Ref PrivateSubnet
          GroupSet:
            - !Ref InstanceSecurityGroup
      Tags:
        - Key: !Ref TagKey
          Value: !Ref TagValue
Code language: YAML (yaml)

The tag settings are key.
The tag information is used to specify the target of the SSM Automation runbook execution.

This time, set the tags as follows

  • Tag Name: CreateImage
  • Tag Value: Group1

SSM Automation Runbook

Resources:
  CreateImageRunbook:
    Type: AWS::SSM::Document
    Properties:
      Content:
        assumeRole: "{{AutomationAssumeRole}}"
        description: Create an AMI for an EC2 instance with a specific tag.
        schemaVersion: "0.3"
        parameters:
          AutomationAssumeRole:
            type: String
            description: (Optional) The ARN of the role that allows Automation to perform the actions on your behalf.
            default: !GetAtt CreateImageRole.Arn
          TagKey:
            type: String
            description: (Required) The tag key of Instance.
            default: !Ref TagKey
          TagValue:
            type: String
            description: (Required) The tag value of Instance.
            default: !Ref TagValue
        mainSteps:
          - name: createImage
            action: aws:executeAutomation
            maxAttempts: 1
            timeoutSeconds: !Ref WaitForSuccessTimeoutSeconds
            onFailure: Abort
            inputs:
              DocumentName: AWS-CreateImage
              TargetParameterName: InstanceId
              Targets:
                - Key: "tag:{{TagKey}}"
                  Values:
                    - "{{TagValue}}"
      DocumentFormat: YAML
      DocumentType: Automation
      Name: !Sub "${Prefix}-CreateImageRunbook"
      TargetType: /AWS::EC2::Instance
Code language: YAML (yaml)

Create an SSM Automation runbook to create an AMI for the instance specified in the tag.

For more information on how to create your own runbook, please see the following pages.

あわせて読みたい
Introduction to Creating SSM Automation Runbooks Using CloudFormation 【Introduction to Creating SSM Automation Runbooks Using CloudFormation】 Many SSM Automation runbooks are currently provided by default. https://docs.aws.am...

The point is the setting regarding steps.

You can execute another runbook from within a runbook by setting the actions property to “aws:executeAutomation”.
In this case, AMI is created by specifying “AWS-CreateImage” for the DocumentName property within inputs.

By specifying the aforementioned tag information in the Tragets property and “InstanceId” in the TargetParameterName, AWS-CreateImage is executed for the instance to which the tag is assigned.

IAM Roles for Runbook

Resources:
  CreateImageRole:
    Type: AWS::IAM::Role
    DeletionPolicy: Delete
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service:
                - ssm.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AmazonSSMAutomationRole
      Policies:
        - PolicyName: CreateImagePolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - tag:GetResources
                Resource:
                  - "*"
Code language: YAML (yaml)

In addition to the AWS management policy AmazonSSMAutomationRole, set an inline policy to allow tag:GetResources.

EventBridge Rules

Resources:
  EventsRule:
    Type: AWS::Events::Rule
    Properties:
      Name: !Sub "${Prefix}-EventsRule"
      ScheduleExpression: rate(10 minutes)
      State: ENABLED
      Targets:
        - Arn: !Sub "arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:automation-definition/${Runbook}:$DEFAULT"
          Id: !Ref Runbook
          RoleArn: !GetAtt EventsRuleRole.Arn
Code language: YAML (yaml)

Create an EventBridge rule to run the runbook periodically.

By specifying “rate(10 minutes)” in the ScheduleExpression property, the runbook can be executed every 10 minutes.

Specify the aforementioned runbook ARN, etc. in the Targets property.

IAM Role for EventBridge Rules

Resources:
  EventsRuleRole:
    Type: AWS::IAM::Role
    DeletionPolicy: Delete
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service: events.amazonaws.com
      Policies:
        - PolicyName: !Sub "${Prefix}-StartAutomationExecutionPolicy"
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action: ssm:StartAutomationExecution
                Resource: !Sub "arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:automation-definition/${Runbook}:$DEFAULT"
              - Effect: Allow
                Action: iam:PassRole
                Resource: !Ref RunbookRoleArn
Code language: YAML (yaml)

Allow two actions in the inline policy.

The first is ssm:StartAutomationExecution.
Literally, this is what allows the runbook to be executed.

The second is iam:PassRole.
This is to pass the IAM role for the SSM Automation runbook that we just checked.

Architecting

Use CloudFormation to build this environment and check its actual behavior.

Create CloudFormation stacks and check the resources in the stacks

Create CloudFormation stacks.
For information on how to create stacks and check each stack, please refer to the following pages.

あわせて読みたい
CloudFormation’s nested stack 【How to build an environment with a nested CloudFormation stack】 Examine nested stacks in CloudFormation. CloudFormation allows you to nest stacks. Nested ...

After reviewing the resources in each stack, information on the main resources created in this case is as follows

  • EC2 instance: i-06de272d94a13fcef
  • SSM Automation runbook: fa-122-CreateImageRunbook
  • EventBridgeRule: fa-122-EventsRule

Check the SSM Automation runbook from the AWS Management Console.

Detail of SSM 1.
Detail of SSM 2.
Detail of SSM 3.

The runbook has been successfully created.
You can see that three parameters must be specified to run this runbook, all of which have default values.

Check the EventBridge rules.

Detail of EventBridge 1.
Detail of EventBridge 2.

You can see that it is scheduled every 10 minutes.
You can also see that the aforementioned runbook is specified as the target.

Operation Check

First AMI creation

Now that we are ready, let’s see how the SSM Automation runbook works.

Detail of SSM 4.

Execution of the runbook has started according to the EventBridge rules.
Three Automations are being executed at one time.

Check the details of the Automation run at the bottom of the first page.

Detail of SSM 5.

You can see that the runbook created this time has been executed.
Also, if you look at the steps executed, you will see that aws:executeAutomation is executed.

Find out more about this step.

Detail of SSM 6.

Looking at the Input parameters, we can see that AWS-CreateImage is to be executed on instances that have been given the given tag.

This execution of Automation indicates that the middle Automation execution of the three Automation executions has been started.

The next step is to check the details of Automation in this middle section.

Detail of SSM 7.

We can see that AWS-CreateImage was executed.
Also, looking at the steps executed, we can see that the first of the three Automation executions was initiated.

Find out more about this Automation.

Detail of SSM 8.

The Outputs shows that an AMI was created as a result of the Automation run.

Check the created AMI and the snapshot associated with it.

Detail of AMI 1.
Detail of AMI 2.

You can see that an AMI and snapshot of the target instance have indeed been created.

Thus, the EventBridge rule allows the SSM Automation runbook to automatically run and create an AMI for the instance specified as targeted by the tag.

Second AMI creation

Ensure that AMIs are created periodically by EventBridge rules.

Wait for a while after the first execution.

Detail of SSM 9.

Ten minutes after the first time, a second Automation run was initiated.

Detail of SSM 10.

Automation has been executed and an AMI has been created.

Confirm the created AMI.

Detail of AMI 3.
Detail of AMI 4.

Indeed, an AMI and snapshot were created.

Indeed, the EventBridge rule allowed the SSM Automation runbook to automatically run periodically to create AMIs for the instances specified as targeted by the tag.

Summary

We have identified a way to get AMIs by using EventBridge rules to periodically run the SSM Automation runbook.

TOC