Step 2

Step 2 - Launch an instance using aws:ExecuteScript

In Step 1, we used the automation action aws:runInstances to launch an EC2 instance. In place of this action, we will be using the action aws:executeScript in order to execute a Python script that launches an EC2 instance and waits for the instance status to change to ok.

Tip: If you copy and paste values from this walkthrough into Document Builder, such as parameter names and handler names, make sure to delete any leading or trailing spaces added to the text value you enter.

Update the Custom Automation Document

  • Open the AWS Systems Manager console at https://console.aws.amazon.com/systems-manager/.

  • In the navigation pane, choose Documents.

  • On the Documents page, select the Owned by me tab and then choose the document you created in Step 1 - Launch an EC2 Instance using aws:runInstances, such as LaunchEC2Instance.

  • Select Actions and then Create new version.

  • For Document description, replace the content with the following.

## Title: LaunchInstanceAndCheckState
-----
**Purpose**: This Automation document first launches an Amazon EC2 instance using the AMI ID provided in the parameter ```imageId```. The second step of this document continuously checks the instance status check value for the launched instance until the status ```ok``` is returned.

## Parameters:
-----
Name | Type | Description | Default Value
------------- | ------------- | ------------- | -------------
assumeRole | String | The ARN of the role that allows Automation to perform the actions on your behalf. | -
imageId  | String | (Optional) The AMI ID to use for launching the instance. The default value uses the latest Amazon Linux AMI ID available. | {{ ssm:/aws/service/ami-amazon-linux-latest/amzn-ami-hvm-x86_64-gp2 }}
  • For Assume role, enter {{ assumeRole }}. This allows us to pass in the Automation service role using the parameter assumeRole which will be created in subsequent steps.

  • For Outputs, replace the existing value with the following.

["launchEc2Instance.OutputPayload", "waitForInstanceStatusOk.OutputPayload"]
  • Expand Input parameters and do the following.

    • Important: Do not modify the imageId parameter. This parameter will be used by the Python script below to launch an EC2 instance using the latest available Amazon Linux AMI.
  • Choose Add a parameter to create the second parameter, tagValue, and enter the following.

    • For Parameter name, enter tagValue.
    • For Type, choose String.
    • For Required, choose No.
    • For Default value, enter LaunchedBySsmAutomation. This adds the tag key-pair value Name:LaunchedBySsmAutomation to the instance.
    • For Description, enter the following.
(Optional) The tag value to add to the instance. The default value is LaunchedBySsmAutomation.
  • Choose Add a parameter to create the third parameter, instanceType, and enter the following information.

    • For Parameter name, enter instanceType.
    • For Type, choose String.
    • For Required, choose No.
    • For Default value, enter t2.micro.
    • For Parameter description, enter the following.
(Optional) The instance type to use for the instance. The default value is t2.micro.
  • Choose Add a parameter to create the fourth parameter, instanceIAMrole, and enter the following information.

    • For Parameter name, enter instanceIAMrole.
    • For Type, choose String.
    • For Required, choose No.
    • For Default value, enter the name of an IAM Instance Profile role that grants permissions to Systems Manager. If you used Quick Setup, the name to use is AmazonSSMRoleForInstancesQuickSetup.
    • For Parameter description, enter the following.
(Optional) The name of the IAM Instance Profile role which grants permissions to Systems Manager. The default value is AmazonSSMRoleForInstancesQuickSetup.
  • Choose Add a parameter to create the fifth parameter, assumeRole, and enter the following information.

    • For Parameter name, enter assumeRole.
    • For Type, choose String.
    • For Required, choose No.
    • For Default value, enter the ARN of the service role to use, in the format arn:aws:iam::111122223333:role/AmazonSSMRoleForAutomationAssumeQuickSetup.
    • For Parameter description, enter the following.
The ARN of the role that allows Automation to perform the actions on your behalf.
  • In the Step 1: launchEc2Instance section, complete the following steps.

    • Modify the Action type and select Run a script (aws:executeScript).
    • For Description, enter a description for the automation step, such as the following.
**About This Step**

This step first launches an EC2 instance using the ```aws:executeScript``` action and the provided python script.
  • For Runtime, choose Python3.6.
  • For Handler, replace the default value with launch_instance. This is the function name declared in the following script.
  • For Script, replace the default contents with the following.
def launch_instance(events, context):
  import boto3
  ec2 = boto3.client('ec2')

  image_id = events['image_id']
  tag_value = events['tag_value']
  instance_type = events['instance_type']
  instance_iam_role = events['instance_iam_role']

  tag_config = {'ResourceType': 'instance', 'Tags': [{'Key':'Name', 'Value':tag_value}]}

  res = ec2.run_instances(ImageId=image_id, IamInstanceProfile={'Name':instance_iam_role}, InstanceType=instance_type, MaxCount=1, MinCount=1, TagSpecifications=[tag_config])

  instance_id = res['Instances'][0]['InstanceId']

  print('[INFO] 1 EC2 instance is successfully launched', instance_id)

  return { 'InstanceId' : instance_id }
  • Expand Additional inputs.
  • For Input name, chose InputPayload. For Input value, enter the following YAML data.
---
image_id: "{{ imageId }}"
tag_value: "{{ tagValue }}"
instance_type: "{{ instanceType }}"
instance_iam_role: "{{ instanceIAMrole }}"
  • Expand Outputs.
  • Enter the following information for the output, Payload.
    • For Name, enter Payload.
    • For Selecter, enter $.Payload.
    • For Type, choose StringMap.
  • Choose Add output and enter the following information for the output, InstanceId.

    • For Name, enter InstanceId.
    • For Selecter, enter $.Payload.InstanceId.
    • For Type, choose String.
  • Choose Add step to add a second step to the Automation document. The second step queries the status of the instance launched in Step 1 and waits until the status returned is ok.

  • In the Step 2 section, do the following.

    • For Step name, enter waitForInstanceStatusOk.
    • For Action type, choose Run a script (aws:executeScript).
    • For Description, enter a description for the automation step, such as the following.
**About This Step**

The python script continuously polls the instance status check value for the instance launched in Step 1 until the ```ok``` status is returned.
  • For Runtime, choose Python3.6.
  • For Handler, replace the default value with poll_instance. This is the function name declared in the following script.
  • For Script, replace the default contents with the following.
def poll_instance(events, context):
  import boto3
  import time

  ec2 = boto3.client('ec2')

  instance_id = events['InstanceId']

  print('[INFO] Waiting for instance status check to report ok', instance_id)

  instance_status = "null"

  while True:
    res = ec2.describe_instance_status(InstanceIds=[instance_id])

    if len(res['InstanceStatuses']) == 0:
      print("Instance status information is not available yet")
      time.sleep(5)
      continue

    instance_status = res['InstanceStatuses'][0]['InstanceStatus']['Status']

    print('[INFO] Polling to get status of the instance', instance_status)

    if instance_status == 'ok':
      break

    time.sleep(10)

  return {'Status': instance_status, 'InstanceId': instance_id}
  • Expand Additional inputs.
  • For Input name, choose InputPayload. For Input value, enter the following.
'{{ launchEc2Instance.Payload }}'
  • Select Set new version as default.

  • Choose Create new version to save the document.