Automate EC2 AMI Using SSM Document Automation and EventBridge

We will automate the creation of Amazon Machine Image (AMI) from the EC2 instance through custom System Manager (SSM) document automation and also will integrate the EventBridge rule so it can schedule the events and run the execution of the document.

Table of Contents

AWS Systems Manager Documents

SSM documents define the actions that the Systems Manager performs on your managed instances. Documents are in JSON or YAML format and they include steps and parameters to execute the runbooks or scripts.

There are more than 100 pre-configured documents provided by AWS and also you can create your own custom documents. Here we will create our own custom document script for creating AMI in certain steps.

Creating SSM Document Automation Runboook

(1) In Systems Manger select Documents and then go to Automation while creating a document

(2) Here we will create runbooks by placing the custom scripts in the editor option, not through the builder. Now we will look at the script step by step understanding every block of the script.

description: Creates a Linux Managed Instance
schemaVersion: '0.3'
assumeRole: "{{ AutomationAssumeRole }}"
  • Here the assumeRole will use the IAM role that allows Automation to perform the actions in the runbook on your behalf
parameters:
  SourceAmiId:
    type: String
    description: (Required) AMI id to use for launching the instance.
  IamInstanceProfileName:
    type: String
    description: (Required) Role Name to create.
  SecurityGroupIds:
    type: StringList
    description: The IDs of the security groups for the instance.
  InstanceType:
    type: String
    description: (Required) Type of instance to launch. Default is t2.medium.
    default: t2.micro
  KeyName:
    type: String
    description: (Required) Key pair to use when creating instance.
  UserData:
    type: String
    description: (Required) A script provided as a string literal value.
  TargetAmiName:
    type: String
    description: "(Optional) The name of the new AMI that will be created. Default
      is a system-generated string including the source AMI id, and the creation time
      and date."  
  AutomationAssumeRole:
    type: String
    description: '(Optional) The ARN of the role that allows Automation to perform the actions on your behalf. '
    default: ''
  • After we will define the different parameters such as instance creation and AMI ID which will be required to launch an instance.
mainSteps:
  - name: launchInstance
    action: aws:runInstances
    maxAttempts: 3
    timeoutSeconds: 1200
    onFailure: Abort
    inputs:
      ImageId: "{{SourceAmiId}}"
      IamInstanceProfileName: "{{ IamInstanceProfileName }}"
      InstanceType: "{{ InstanceType }}"
      KeyName: "{{ KeyName }}"
      SecurityGroupIds: "{{ SecurityGroupIds }}"
      UserData: "{{ UserData }}"
  • Then comes the mainSteps of the runbook.
  • The first step outputs the current state of the target instance specified in the ImageId, IamInstanceProfileName, Instancetype, KeyName, SecurityGroupIds, and UserData input parameters using the aws:runInstance action.
  - name: createImage
    action: aws:createImage
    onFailure: Abort
    inputs:
      InstanceId: "{{launchInstance.InstanceIds}}"
      ImageName: "{{TargetAmiName}}"
  • The second step is used to create an AMI from an instance which is either running, stopping, or stopped.
  • Here the InstanceId will be used by referencing launchInstance by creating AMI from the instance and using the input parameter as aws:createImage action.
 - name: TerminateInstances
    action: 'aws:changeInstanceState'
    inputs:
      InstanceIds:
        - "{{launchInstance.InstanceIds}}"
      DesiredState: terminated
outputs:
- createImage.ImageId
  • The third and final step will be to stop or terminate the EC2 instance after the creation of AMI.
  • Here again, the InstanceIds will be referencing to launchInstance to stop or terminate the EC2 instances with action as aws:changeInstanceState.

(3) After placing the entire runbook script in the editor click on Execute Automation

Below is the Document Description and steps that it will perform during the execution of automation

(4) You need to provide an input parameter that is not taken as default in the script and then execute automation

  • Here we are providing SourceAMI as the AMI ID of the OS that we want to launch in a specific region. Currently, we will be launching EC2 Linux in the ap-south-1 region.
  • IAMInstanceProfileName is the role to attach to an EC2 instance.
  • SecurityGroupsIds as the security group to attach to an EC2 instance.
  • UserData as the script we will be passing in base64 encoded (Above user, data will install the apache server)

(5) Now execution will start and first it will create an EC2 instance with an Apache server installed in it.

(6) Then in the second step, it will create AMI from the instance.

(7) After in third step EC2 instance will be terminated after the completion of AMI image creation.

(8) Below you can see the status of Executed Steps that were run during the time of execution.

EventBridge SSM Document Automation

Now create an EventBridge rule which will run SSM Document on the estimated schedule at every 12:00 P.M but you can customize the schedule rate as per your requirements.

(1) Go to EventBridge Service, then create a rule in that select schedule as the rule type

(2) Now define the cron expression in the schedule pattern as (30 6 ? 12 * 2022) which will run the SSM document on schedule every day at 06:30.

(3) In select targets choose AWS service as target System Manager Automations and choose the Document name

(4) Remaining will be the input parameter to update, which will be the same as we already did while executing SSM Document Execution.

(5) After that leave everything default and create the rule so that will rule will automatically get triggered every day at 12:00 PM to create the SSM Automation Document of creating AMI from the EC2 instance.

Conclusion

This way we can create AMI image from EC2 instances in an automated way by using the SSM Document Automation runbook.

Also with Eventbridge configured more automation can be achieved by scheduling the SSM document execution to run at certain time intervals.

About the Author ✍🏻

Varshil Desai is a DevOps Engineer at QloudX with 5 AWS certifications & 1 Azure certification.

His main work is in DevOps technology where he builds automated & quick solutions for clients.

With only 1 year of industry experience, Varshil has already made his mark with amazing solutions in the cloud using DevOps automation tools. At the same time, he also likes to explore AI/ML technology.

Leave a Reply

Your email address will not be published. Required fields are marked *