Run a Command automatically when new EC2 Instances created Using Eventbridge and System Manager

Eventbrige, SSM, SSMAutomation, Automation, AWS

Run command

Architecture Overview #

  1. The authorized AWS User creating the EC2 instance.
  2. The AWS API call (event) registered in CloudTrail.
  3. By default the AWS Cloud Trail sent a event to the EventBridge default bus. The event will be evaluated based on the rule and it passed.
  4. If the event pattern is matched by the rule. It will be triggering the targets. The target can be anything like Lambda,SSM automation doc etc. In our case the target is SSM Automation doc. The rule will pass the AssumeRole and InstanceID matched to the SSM Doc.
  5. In the SSM doc we have the step to call the RunCommand on top of the EC2 instance.
  6. The RunCommand call will be passed to EC2 instance and the required script will be executed.

Introduction #

I am writing this post to explain you about how to run a set of (Powershell / ShellScript) commend on top of EC2 instance whenever it’s getting create with name prefix with aws SSM Automation and EventBridge

What is EventBridge? #

EventBridge is a serverless service that uses events to connect application components together, making it easier for you to construct scalable event-driven apps. Building loosely linked software systems that communicate with one another by emitting and reacting to events is known as event-driven architecture. You may increase your agility and create dependable, scalable apps by using event-driven architecture.

Use EventBridge to route events from sources such as home-grown applications, AWS services, and third-party software to consumer applications across your organization. EventBridge provides simple and consistent ways to ingest, filter, transform, and deliver events so you can build applications quickly.

pre-requisites #

  • AWS Account
  • IAM permission to create a IAM Role & Policies,EventBridge Rule,SSM Document and EC2 Instance
  • IAM Permission to View CloudTrail logs

Step 1 - Create a IAM polices and roles #

In this step we are going to create custom polices and three different IAM Roles. One is to associate with Eventbridge and another one is SSM automation assume role which will allow SSM Automation to trigger a document to perform the RunCommand on EC2 instance. Another one is to attached to EC2 instance which allow SSM Agent to communicate to SSM Service.

Create IAM Policy to attach to Eventbridge Role #

Use the following policy to create a IAM customer managed policy which will allow the eventbridge to trigger the SSM Document. We will be attaching this policy to IAM role in upcoming step. Remember the name of the policy which you have created. We need it while attaching it to eventbridge IAM role.

{
 "Version": "2012-10-17",
 "Statement": [
  {
   "Sid": "ALLOWEventBridgeTOTriggerDocument",
   "Effect": "Allow",
   "Action": "ssm:StartAutomationExecution",
   "Resource": "arn:aws:ssm:*:<ACCOUNT-NUMBER>:automation-definition/<DOCUMENT-NAME>:$DEFAULT"
  }
 ]
}

Note : Change the ACCOUNT-NUMBER and DOCUMENT-NAME

Create Passrole IAM policy to attach to Eventbridge role #

Use the following policy to create a IAM customer Manager policy. This Policy is using to allow eventbrige role to pass the assume role while triggering the SSM Document. This assume role used on behalf of SSM. Remember the name of the policy which you have created. We need it while attaching it to passrole.

{
 "Version": "2012-10-17",
 "Statement": [
  {
   "Sid": "AllowEventBridgeRoleToPassRole",
   "Effect": "Allow",
   "Action": "iam:PassRole",
   "Resource": "arn:aws:iam::<ACCOUNT-NUMBER>:role/<EventBridgeRoleName>"
  }
 ]
}

Note : Change the ACCOUNT-NUMBER and EventBridgeRoleName

Create a Eventbridge IAM Role #

Once the policies created, start creating the eventbrige IAM role. Kindly find the trust policy below. this will be automatically created when your creating the role on behalf of the eventbrige. I am sharing here for the reference.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "events.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

AWS-Role-Trusted-entity-Service-Selection-Eventbridge

AWS-EventBridge-Role-Reference

Create IAM Policy to attach to SSM Role #

Use the following policy to create a IAM customer managed policy which will allow the ssm to run a command on top of the ec2 instances. We will be attaching this policy to IAM role in upcoming step. Remember the name of the policy which you have created. We need it while attaching it to SSM IAM role.

{
	"Version": "2012-10-17",
	"Statement": [
		{
			"Sid": "AllowSSMToUseDocument",
			"Effect": "Allow",
			"Action": "ssm:SendCommand",
			"Resource": [
				"arn:aws:ssm:*:<ACCOUNT_NUMBER>:document/AWS-RunShellScript"
			]
		},
		{
			"Sid": "AllowSSMToRunCommandOnInstance",
			"Effect": "Allow",
			"Action": "ssm:SendCommand",
			"Resource": [
				"arn:aws:ec2:*:ACCOUNT_NUMBER:instance/*"
			]
		},
		{
			"Sid": "AllowSSMToListOperation",
			"Effect": "Allow",
			"Action": [
				"ssm:ListCommands",
				"ssm:DescribeInstanceInformation",
				"ssm:ListCommandInvocations"
			],
			"Resource": "*"
		}
	]
}

Note : Change the ACCOUNT-NUMBER

Create a SSM IAM Role to Assume the Permission #

Once the policies created, start creating the eventbrige IAM role. Kindly find the trust policy below. this will be automatically created when your creating the role on behalf of the eventbrige.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "events.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

Note: Kindly refer the below video if you have any queries.

That’s all about the permission side. Now we are going to the next step to create the SSM Document and Eventbridge rule.

Step 2 - Create a SSM Document #

In this step we are going to create the SSM Document. The document has two different steps.

  1. Sleep – This sleep time is to allow ec2 instance to register under the SSM fleet Manager. (PT10M) It will wait 10 mins

  2. RunCommandOnInstance - This will be reading the input send by the eventbridge. Also it as the script which need to be run on the EC2 instances.

Script Used for this blog

### Installing IIS with Management Tools

Install-WindowsFeature Web-Server -IncludeManagementTools

Kindly refer the below video for creating the SSM document. Just for blog I have use very basic script. you can run any complex script using ssm automation document to your ec2 instance.

Step 3 - Create the eventbrige Rule #

In This step we are going to create the eventbridge rule which will trigger the SSM document based on the pattern and send the information to the SSM Document like EC2 instance ID and AssumeRole name.

Event pattern to match with event. In this event I am trying to match the EC2 instance name and the instance platform. Here I am matching with Name ssm-automation-ec2-ANYTHING and the platform is Windows

{
  "detail": {
    "eventName": ["RunInstances"],
    "eventSource": ["ec2.amazonaws.com"],
    "responseElements": {
      "instancesSet": {
        "items": {
          "platform": ["windows"],
          "tagSet": {
            "items": {
              "key": ["Name"],
              "value": [{
                "wildcard": "ssm-automation-ec2-*"
              }]
          }
       }
    }
  }
}
},

"source": ["aws.ec2"]
}

Kindly find the Input transformer below

Input Path

{
  "InstanceId": "$.detail.responseElements.instancesSet.items[0].instanceId"
}

Input template

{"InstanceID": [<InstanceId>],"AssumeRole":["arn:aws:iam::<AcountNumber>:role/ssm-automation-demo-assume-role"]}

Kindly refer the below video to refer how to create the eventbridge rule.

Now your have the Eventbridge Rule ready!!

That’s about it. Now if you create any window EC2 instance with name of ssm-automation-ec2-ANYNAME, The SSM document will be runcommand on top of the created EC2 instance. Make sure you attaching the SSM agent role to the ec2 instance to have communication with SSM.

Hope this blog helped you to automate your work. Happy Automation 🤗