id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
systems-manager-ug-388
systems-manager-ug.pdf
388
You can also drag and drop actions to move them to different places in your runbook's workflow. If your workflow is complex, you might not be able to view all of it in the Automation 1292 AWS Systems Manager User Guide canvas panel. Use the controls at the top of the canvas to zoom in or out. To view different parts of a workflow, you can drag the workflow graph in the canvas. Drag an action from the Actions browser, and drop it into your runbook's workflow graph. A line shows where it will be placed in your workflow. To change the order of an action, you can drag it to a different place in your workflow. The new action has been added to your workflow, and its code is auto-generated. Form After you add an action to your runbook workflow, you can configure it to meet your use case. Choose the action that you want to configure, and you will see its parameters and options in the Form panel. You can also see the YAML or JSON code by choosing the Content toggle. The code associated with the action you have selected is highlighted. Automation 1293 AWS Systems Manager User Guide Keyboard shortcuts The visual design experience supports the keyboard shortcuts shown in the following table. Automation 1294 AWS Systems Manager User Guide Function Keyboard shortcut Undo Ctrl the +Z last operation . Redo Ctrl the +Shif last t operation +Z . Center Alt the +C workflow in the canvas. Backspace Remove all selected states. Remove Delete all selected states. Duplicate Ctrl the +D selected state. Automation 1295 AWS Systems Manager User Guide Using the visual design experience Learn to create, edit and run runbook workflows using the visual design experience. After your workflow is ready, you can save it or export it. You can also use the visual design experience for rapid prototyping. Create a runbook workflow 1. Sign in to the Systems Manager Automation console. 2. Choose Create runbook. 3. In the Name box, enter a name for your runbook, for example, MyNewRunbook. 4. Next to the Design and Code toggle, select the pencil icon and enter a name for your runbook. You can now design a workflow for your new runbook. Design a runbook To design a runbook workflow using the visual design experience, you drag an automation action from the Actions browser into the canvas, placing it where you want it in your runbook's workflow. You can also re-order actions in your workflow by dragging them to a different location. As you drag an action onto the canvas, a line appears wherever you can drop the action in your workflow. After an action is dropped onto the canvas, its code is auto-generated and added inside your runbook's content. If you know the name of the action you want to add, use the search box at the top of the Actions browser to find the action. After you drop an action onto the canvas, configure it using the Form panel on the right. This panel contains the General, Inputs, Outputs, and Configuration tabs for each automation action or API action that you place on the canvas. For example, the General tab consists of the following sections: • The Step name identifies the step. Specify a unique value for the step name. • The Description helps you describe what the action is doing in your runbook's workflow. The Inputs tab contains fields that vary based on the action. For example, the aws:executeScript automation action consists of the following sections: Automation 1296 AWS Systems Manager User Guide • The Runtime is the language to use for running the provided script. • The Handler is the name of your function. You must ensure that the function defined in the handler has two parameters: events and context. The PowerShell runtime doesn't support this parameter. • The Script is an embedded script that you want to run during the workflow. • (Optional) The Attachment is for standalone scripts or .zip files that can be invoked by the action. This parameter is required for JSON runbooks. The Outputs tab helps you specify the values that you want to output from an action. You can reference output values in later actions of your workflow, or generate output from actions for logging purposes. Not all actions will have an Outputs tab because not all actions support outputs. For example, the aws:pause action doesn't support outputs. For actions that do support outputs, the Outputs tab consists of the following sections: • The Name is the name to be used for the output value. You can reference outputs in later actions of your workflow. • The Selector is a JSONPath expression string beginning with "$." that is used to select one or more components within a
systems-manager-ug-389
systems-manager-ug.pdf
389
You can reference output values in later actions of your workflow, or generate output from actions for logging purposes. Not all actions will have an Outputs tab because not all actions support outputs. For example, the aws:pause action doesn't support outputs. For actions that do support outputs, the Outputs tab consists of the following sections: • The Name is the name to be used for the output value. You can reference outputs in later actions of your workflow. • The Selector is a JSONPath expression string beginning with "$." that is used to select one or more components within a JSON element. • The Type is the data type for the output value. For example, a String or Integer data type. The Configuration tab contains properties and options that all automation actions can use. The action consists of the following sections: • The Max attempts property is the number of times an action retries if it fails. • The Timeout seconds property specifies the timeout value for an action. • The Is critical property determines if the action failure stops the entire automation. • The Next step property determines which action the automation goes to next in the runbook. • The On failure property determines which action the automation goes to next in the runbook if the action fails. • The On cancel property determines which action the automation goes to next in the runbook if the action is canceled by a user. To delete an action, you can use backspace, the toolbar above the canvas, or right-click and choose Delete action. Automation 1297 AWS Systems Manager User Guide As your workflow grows, it might not fit in the canvas. To help make the workflow fit in the canvas, try one of the following options: • Use the controls on the side panels to resize or close the panels. • Use the toolbar at the top of the canvas to zoom the workflow graph in or out. Update your runbook You can update an existing runbook workflow by creating a new version of your runbook. Updates to your runbooks can be made by using the visual design experience, or by editing the code directly. To update an existing runbook, use the following procedure: 1. Sign in to the Systems Manager Automation console. 2. Choose the runbook that you want to update. 3. Choose Create new version. 4. The visual design experience has two panes: A code pane and a visual workflow pane. Choose Design in the visual workflow pane to edit your workflow with the visual design experience. When you're done, choose Create new version to save your changes and exit. 5. (Optional) Use the code pane to edit the runbook content in YAML or JSON. Export your runbook To export your runbook's workflow YAML or JSON code, and also a graph of your workflow, use the following procedure: 1. Choose your runbook in the Documents console. 2. Choose Create new version. 3. In the Actions dropdown, choose whether you want to export the graph or runbook, and which format you prefer. Configuring inputs and outputs for your actions Each automation action responds based on input that it receives. In most cases, you then pass output to the subsequent actions. In the visual design experience, you can configure an action's input and output data in the Inputs and Outputs tabs of the Form panel. Automation 1298 AWS Systems Manager User Guide For detailed information about how to define and use output for automation actions, see Using action outputs as inputs. Provide input data for an action Each automation action has one or more inputs that you must provide a value for. The value you provide for an action's input is determined by the data type and format that's accepted by the action. For example, the aws:sleep actions requires an ISO 8601 formatted string value for the Duration input. Generally, you use actions in your runbook's workflow that return output that you want to use in subsequent actions. It's important to make sure your input values are correct to avoid errors in your runbook's workflow. Input values are also important because they determine whether the action returns the expected output. For example, when using the aws:executeAwsApi action, you want to make sure that you're providing the right value for the API operation. Define output data for an action Some automation actions return output after performing their defined operations. Actions that return output either have predefined outputs, or allow you to define the outputs yourself. For example, the aws:createImage action has predefined outputs that return an ImageId and ImageState. Comparatively, with the aws:executeAwsApi action, you can define the outputs you that want from the specified API operation. As a result, you can return one or more values from a single API operation
systems-manager-ug-390
systems-manager-ug.pdf
390
example, when using the aws:executeAwsApi action, you want to make sure that you're providing the right value for the API operation. Define output data for an action Some automation actions return output after performing their defined operations. Actions that return output either have predefined outputs, or allow you to define the outputs yourself. For example, the aws:createImage action has predefined outputs that return an ImageId and ImageState. Comparatively, with the aws:executeAwsApi action, you can define the outputs you that want from the specified API operation. As a result, you can return one or more values from a single API operation to use in subsequent actions. Defining your own outputs for an automation action requires that you specify a name of the output, the data type, and the output value. To continue using the aws:executeAwsApi action as an example, let's say you're calling the DescribeInstances API operation from Amazon EC2. In this example, you want to return, or output, the State of an Amazon EC2 instance and branch your runbook's workflow based on the output. You choose to name the output InstanceState, and use the String data type. The process to define the actual value of the output differs, depending on the action. For example, if you're using the aws:executeScript action, you must use return statements in your functions to provide data to your outputs. With other actions like aws:executeAwsApi, aws:waitForAwsResourceProperty, and aws:assertAwsResourceProperty, a Selector is required. The Selector, or PropertySelector as some actions refer to it, is a JSONPath string that is used to process the JSON response from an API operation. It's important to understand how the JSON response object from an API operation is structured so you can select the correct Automation 1299 AWS Systems Manager User Guide value for your output. Using the DescribeInstances API operation mentioned earlier, see the following example JSON response: { "reservationSet": { "item": { "reservationId": "r-1234567890abcdef0", "ownerId": 123456789012, "groupSet": "", "instancesSet": { "item": { "instanceId": "i-1234567890abcdef0", "imageId": "ami-bff32ccc", "instanceState": { "code": 16, "name": "running" }, "privateDnsName": "ip-192-168-1-88.eu-west-1.compute.internal", "dnsName": "ec2-54-194-252-215.eu-west-1.compute.amazonaws.com", "reason": "", "keyName": "my_keypair", "amiLaunchIndex": 0, "productCodes": "", "instanceType": "t2.micro", "launchTime": "2018-05-08T16:46:19.000Z", "placement": { "availabilityZone": "eu-west-1c", "groupName": "", "tenancy": "default" }, "monitoring": { "state": "disabled" }, "subnetId": "subnet-56f5f000", "vpcId": "vpc-11112222", "privateIpAddress": "192.168.1.88", "ipAddress": "54.194.252.215", "sourceDestCheck": true, "groupSet": { "item": { "groupId": "sg-e4076000", "groupName": "SecurityGroup1" } Automation 1300 User Guide AWS Systems Manager }, "architecture": "x86_64", "rootDeviceType": "ebs", "rootDeviceName": "/dev/xvda", "blockDeviceMapping": { "item": { "deviceName": "/dev/xvda", "ebs": { "volumeId": "vol-1234567890abcdef0", "status": "attached", "attachTime": "2015-12-22T10:44:09.000Z", "deleteOnTermination": true } } }, "virtualizationType": "hvm", "clientToken": "xMcwG14507example", "tagSet": { "item": { "key": "Name", "value": "Server_1" } }, "hypervisor": "xen", "networkInterfaceSet": { "item": { "networkInterfaceId": "eni-551ba000", "subnetId": "subnet-56f5f000", "vpcId": "vpc-11112222", "description": "Primary network interface", "ownerId": 123456789012, "status": "in-use", "macAddress": "02:dd:2c:5e:01:69", "privateIpAddress": "192.168.1.88", "privateDnsName": "ip-192-168-1-88.eu-west-1.compute.internal", "sourceDestCheck": true, "groupSet": { "item": { "groupId": "sg-e4076000", "groupName": "SecurityGroup1" } }, "attachment": { "attachmentId": "eni-attach-39697adc", Automation 1301 AWS Systems Manager User Guide "deviceIndex": 0, "status": "attached", "attachTime": "2018-05-08T16:46:19.000Z", "deleteOnTermination": true }, "association": { "publicIp": "54.194.252.215", "publicDnsName": "ec2-54-194-252-215.eu-west-1.compute.amazonaws.com", "ipOwnerId": "amazon" }, "privateIpAddressesSet": { "item": { "privateIpAddress": "192.168.1.88", "privateDnsName": "ip-192-168-1-88.eu-west-1.compute.internal", "primary": true, "association": { "publicIp": "54.194.252.215", "publicDnsName": "ec2-54-194-252-215.eu- west-1.compute.amazonaws.com", "ipOwnerId": "amazon" } } }, "ipv6AddressesSet": { "item": { "ipv6Address": "2001:db8:1234:1a2b::123" } } } }, "iamInstanceProfile": { "arn": "arn:aws:iam::123456789012:instance-profile/AdminRole", "id": "ABCAJEDNCAA64SSD123AB" }, "ebsOptimized": false, "cpuOptions": { "coreCount": 1, "threadsPerCore": 1 } } } } } Automation 1302 AWS Systems Manager } User Guide In the JSON response object, the instance State is nested in an Instances object, which is nested in the Reservations object. To return the value of the instance State, use the following string for the Selector so the value can be used in our output: $.Reservations[0].Instances[0].State.Name. To reference an output value in subsequent actions of your runbook's workflow, the following format is used: {{ StepName.NameOfOutput }}. For example, {{ GetInstanceState.InstanceState }}. In the visual design experience, you can choose output values to use in subsequent actions using the dropdown for the input. When using outputs in subsequent actions, the data type of the output must match the data type for the input. In this example, the InstanceState output is a String. Therefore, to use the value in a subsequent action's input, the input must accept a String. Error handling with the visual design experience By default, when an action reports an error, Automation stops the runbook's workflow entirely. This is because the default value for the onFailure property on all actions is Abort. You can configure how Automation handles errors in your runbook's workflow. Even if you have configured error handling, some errors might still cause an automation to fail. For more information, see Troubleshooting Systems Manager Automation. In the visual design experience, you configure error handling in the Configuration panel. Automation 1303 AWS Systems Manager User Guide Retry action on error To retry an action in case of an error, specify a value
systems-manager-ug-391
systems-manager-ug.pdf
391
By default, when an action reports an error, Automation stops the runbook's workflow entirely. This is because the default value for the onFailure property on all actions is Abort. You can configure how Automation handles errors in your runbook's workflow. Even if you have configured error handling, some errors might still cause an automation to fail. For more information, see Troubleshooting Systems Manager Automation. In the visual design experience, you configure error handling in the Configuration panel. Automation 1303 AWS Systems Manager User Guide Retry action on error To retry an action in case of an error, specify a value for the Max attempts property. The default value is 1. If you specify a value greater than 1, the action isn't considered to have failed until all of the retry attempts have failed. Timeouts You can configure a timeout for actions to set the maximum number of seconds your action can run before it fails. To configure a timeout, enter the number of seconds that your action should wait before the action fails in the Timeout seconds property. If the timeout is reached and the Automation 1304 AWS Systems Manager User Guide action has a value of Max attempts that is greater than 1, the step isn't considered to have timed out until the retries complete. Failed actions By default, when an action fails, Automation stops the runbook's workflow entirely. You can modify this behavior by specifying an alternative value for the On failure property of the actions in your runbook. If you want the workflow to continue to the next step in the runbook, choose Continue. If you want the workflow to jump to a different subsequent step in the runbook, choose Step and then enter the name of the step. Canceled actions By default, when an action is canceled by a user, Automation stops the runbook's workflow entirely. You can modify this behavior by specifying an alternative value for the On cancel property of the actions in your runbook. If you want the workflow to jump to a different subsequent step in the runbook, choose Step and then enter the name of the step. Critical actions You can designate an action as critical, meaning it determines the overall reporting status of your automation. If a step with this designation fails, Automation reports the final status as Failed regardless of the success of other actions. To configure an action as critical, leave the default value as True for the Is critical property. Ending actions The Is end property stops an automation at the end of the specified action. The default value for this property is false. If you configure this property for an action, the automation stops whether the action succeeds or fails. This property is most often used with aws:branch actions to handle unexpected or undefined input values. The following example shows a runbook that is expecting an instance state of either running, stopping, or stopped. If an instance is in a different state, the automation ends. Automation 1305 AWS Systems Manager User Guide Tutorial: Create a runbook using the visual design experience In this tutorial, you will learn the basics of working with the visual design experience provided by Systems Manager Automation. In the visual design experience, you can create a runbook that uses multiple actions. You use the drag and drop feature to arrange actions on the canvas. You also search for, select, and configure these actions. Then, you can view the auto-generated YAML code for your runbook's workflow, exit the visual design experience, run the runbook, and review the execution details. This tutorial also shows you how to update the runbook and view the new version. At the end of the tutorial, you perform a clean-up step and delete your runbook. After you complete this tutorial, you'll know how to use the visual design experience to create a runbook. You'll also know how to update, run, and delete your runbook. Automation 1306 AWS Systems Manager Note User Guide Before you start this tutorial, make sure to complete Setting up Automation. Topics • Step 1: Navigate to the visual design experience • Step 2: Create a workflow • Step 3: Review the auto-generated code • Step 4: Run your new runbook • Step 5: Clean up Step 1: Navigate to the visual design experience 1. Sign in to the Systems Manager Automation console. 2. Choose Create automation runbook. Step 2: Create a workflow In the visual design experience, a workflow is a graphical representation of your runbook on the canvas. You can use the visual design experience to define, configure, and examine the individual actions of your runbook. To create a workflow 1. Next to the Design and Code toggle, select the pencil icon and enter a name for your runbook. For this tutorial, enter VisualDesignExperienceTutorial.
systems-manager-ug-392
systems-manager-ug.pdf
392
4: Run your new runbook • Step 5: Clean up Step 1: Navigate to the visual design experience 1. Sign in to the Systems Manager Automation console. 2. Choose Create automation runbook. Step 2: Create a workflow In the visual design experience, a workflow is a graphical representation of your runbook on the canvas. You can use the visual design experience to define, configure, and examine the individual actions of your runbook. To create a workflow 1. Next to the Design and Code toggle, select the pencil icon and enter a name for your runbook. For this tutorial, enter VisualDesignExperienceTutorial. 2. In the Document attributes section of the Form panel, expand the Input parameters dropdown, and select Add a parameter. In the Parameter name field, enter InstanceId. In the Type dropdown, choose AWS::EC2::Instance. Select the Required toggle. a. b. c. Automation 1307 AWS Systems Manager User Guide 3. In the AWS APIs browser, enter DescribeInstances in the search bar. 4. Drag an Amazon EC2 – DescribeInstances action to the empty canvas. 5. For Step name, enter a value. For this tutorial, you can use the name GetInstanceState. Automation 1308 AWS Systems Manager User Guide a. Expand the Additional inputs dropdown, and in the Input name field, enter InstanceIds. b. Choose the Inputs tab. c. In the Input value field, choose the InstanceId document input. This references the value of the input parameter that you created at the beginning of the procedure. Since the InstanceIds input for the DescribeInstances action accepts StringList values, you must wrap the InstanceId input in square brackets. The YAML for the Input value should match the following: ['{{ InstanceId }}']. d. e. f. In the Outputs tab, select Add an output and enter InstanceState in the Name field. In the Selector field, enter $.Reservations[0].Instances[0].State.Name. In the Type dropdown, choose String. 6. Drag a Branch action from the Actions browser, and drop it below the GetInstanceState step. 7. For Step name, enter a value. For this tutorial, use the name BranchOnInstanceState. To define the branching logic, do the following: a. Choose the Branch state on the canvas. Then, under Inputs and Choices, select the pencil icon to edit Rule #1. b. Choose Add conditions. c. d. e. In the Conditions for rule #1 dialog box, choose the GetInstanceState.InstanceState step output from the Variable dropdown. For Operator, choose is equal to. For Value, choose String from the dropdown list. Enter stopped. f. Select Save conditions. g. Choose Add new choice rule. h. Choose Add conditions for Rule #2. Automation 1309 AWS Systems Manager User Guide i. j. k. l. In the Conditions for rule #2 dialog box, choose the GetInstanceState.InstanceState step output from the Variable dropdown. For Operator, choose is equal to. For Value, choose String from the dropdown list. Enter stopping. Select Save conditions. m. Choose Add new choice rule. n. o. p. q. r. s. For Rule #3, choose Add conditions. In the Conditions for rule #3 dialog box, choose the GetInstanceState.InstanceState step output from the Variable dropdown. For Operator, choose is equal to. For Value, choose String from the dropdown list. Enter running. Select Save conditions. In the Default rule, choose Go to end for the Default step. 8. Drag a Change an instance state action to the empty Drag action here box under the {{ GetInstanceState.InstanceState }} == "stopped" condition. a. b. For the Step name, enter StartInstance. In the Inputs tab, under Instance IDs, choose the InstanceId document input value from the dropdown. c. For the Desired state, specify running. 9. Drag a Wait on AWS resource action to the empty Drag action here box under the {{ GetInstanceState.InstanceState }} == "stopping" condition. 10. For Step name, enter a value. For this tutorial, use the name WaitForInstanceStop. a. b. c. d. e. For the Service field, choose Amazon EC2. For the API field, choose DescribeInstances. For the Property selector field, enter $.Reservations[0].Instances[0].State.Name. For the Desired values parameter, enter ["stopped"]. In the Configuration tab of the WaitForInstanceStop action, choose StartInstance from the Next step dropdown. 11. Drag a Run command on instances action to the empty Drag action here box under the {{ GetInstanceState.InstanceState }} == "running" condition. Automation 1310 AWS Systems Manager User Guide 12. For the Step name, enter SayHello. a. b. c. In the Inputs tab, enter AWS-RunShellScript for the Document name parameter. For InstanceIds, choose the InstanceId document input value from the dropdown. Expand the Additional inputs dropdown, and in the Input name dropdown, choose Parameters. d. In the Input value field, enter {"commands": "echo 'Hello World'"}. 13. Review the completed runbook in the canvas and select Create runbook to save the tutorial runbook. Step 3: Review the auto-generated code As you drag and drop actions from the Actions browser onto the canvas, the visual design experience automatically composes the
systems-manager-ug-393
systems-manager-ug.pdf
393
Guide 12. For the Step name, enter SayHello. a. b. c. In the Inputs tab, enter AWS-RunShellScript for the Document name parameter. For InstanceIds, choose the InstanceId document input value from the dropdown. Expand the Additional inputs dropdown, and in the Input name dropdown, choose Parameters. d. In the Input value field, enter {"commands": "echo 'Hello World'"}. 13. Review the completed runbook in the canvas and select Create runbook to save the tutorial runbook. Step 3: Review the auto-generated code As you drag and drop actions from the Actions browser onto the canvas, the visual design experience automatically composes the YAML or JSON content of your runbook in real-time. You can view and edit this code. To view the auto-generated code, select Code for the Design and Code toggle. Step 4: Run your new runbook After creating your runbook, you can run the automation. To run your new automation runbook 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. Automation 1311 AWS Systems Manager User Guide 2. 3. In the navigation pane, choose Automation, and then choose Execute automation. In the Automation document list, choose a runbook. Choose one or more options in the Document categories pane to filter SSM documents according to their purpose. To view a runbook that you own, choose the Owned by me tab. To view a runbook that is shared with your account, choose the Shared with me tab. To view all runbooks, choose the All documents tab. Note You can view information about a runbook by choosing the runbook name. 4. In the Document details section, verify that Document version is set to the version that you want to run. The system includes the following version options: • Default version at runtime – Choose this option if the Automation runbook is updated periodically and a new default version is assigned. • Latest version at runtime – Choose this option if the Automation runbook is updated periodically, and you want to run the version that was most recently updated. • 1 (Default) – Choose this option to run the first version of the document, which is the default. 5. Choose Next. 6. 7. In the Execute automation runbook section, choose Simple execution. In the Input parameters section, specify the required inputs. Optionally, you can choose an IAM service role from the AutomationAssumeRole list. 8. (Optional) Choose an Amazon CloudWatch alarm to apply to your automation for monitoring. To attach a CloudWatch alarm to your automation, the IAM principal that starts the automation must have permission for the iam:createServiceLinkedRole action. For more information about CloudWatch alarms, see Using Amazon CloudWatch alarms. If your alarm activates, the automation is stopped. If you use AWS CloudTrail, you will see the API call in your trail. 9. Choose Execute. Automation 1312 AWS Systems Manager Step 5: Clean up To delete your runbook User Guide 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- 2. 3. 4. 5. manager/. In the navigation pane, choose Documents. Select the Owned by me tab. Locate the VisualDesignExperienceTutorial runbook. Select the button on the document card page, and then choose Delete document from the Actions dropdown. Authoring Automation runbooks Each runbook in Automation, a tool in AWS Systems Manager, defines an automation. Automation runbooks define the actions that are performed during an automation. In the runbook content, you define the input parameters, outputs, and actions that Systems Manager performs on your managed instances and AWS resources. Automation includes several pre-defined runbooks that you can use to perform common tasks like restarting one or more Amazon Elastic Compute Cloud (Amazon EC2) instances or creating an Amazon Machine Image (AMI). However, your use cases might extend beyond the capabilities of the pre-defined runbooks. If this is the case, you can create your own runbooks and modify them to your needs. A runbook consists of automation actions, parameters for those actions, and input parameters that you specify. A runbook's content is written in either YAML or JSON. If you're not familiar with either YAML or JSON, we recommend using the visual designer, or learning more about either markup language before attempting to author your own runbook. For more information about the visual designer, see Visual design experience for Automation runbooks. The following sections will help you author your first runbook. Identify your use case The first step in authoring a runbook is identifying your use case. For example, you scheduled the AWS-CreateImage runbook to run daily on all of your production Amazon EC2 instances. At the end of the month, you decide you have more images than are necessary for recovery points. Going Automation 1313 AWS Systems Manager User Guide forward, you want to automatically delete the oldest AMI of an Amazon EC2 instance when a new AMI is created. To accomplish this, you create a
systems-manager-ug-394
systems-manager-ug.pdf
394
experience for Automation runbooks. The following sections will help you author your first runbook. Identify your use case The first step in authoring a runbook is identifying your use case. For example, you scheduled the AWS-CreateImage runbook to run daily on all of your production Amazon EC2 instances. At the end of the month, you decide you have more images than are necessary for recovery points. Going Automation 1313 AWS Systems Manager User Guide forward, you want to automatically delete the oldest AMI of an Amazon EC2 instance when a new AMI is created. To accomplish this, you create a new runbook that does the following: 1. Runs the aws:createImage action and specifies the instance ID in the image description. 2. Runs the aws:waitForAwsResourceProperty action to poll the state of the image until it's available. 3. After the image state is available, the aws:executeScript action runs a custom Python script that gathers the IDs of all images associated with your Amazon EC2 instance. The script does this by filtering, using the instance ID in the image description you specified at creation. Then, the script sorts the list of image IDs based on the creationDate of the image and outputs the ID of the oldest AMI. 4. Lastly, the aws:deleteImage action runs to delete the oldest AMI using the ID from the output of the previous step. In this scenario, you were already using the AWS-CreateImage runbook but found that your use case required greater flexibility. This is a common situation because there can be overlap between runbooks and automation actions. As a result, you might have to adjust which runbooks or actions you use to address your use case. For example, the aws:executeScript and aws:invokeLambdaFunction actions both allow you to run custom scripts as part of your automation. To choose between them, you might prefer aws:invokeLambdaFunction because of the additional supported runtime languages. However, you might prefer aws:executeScript because it allows you to author your script content directly in YAML runbooks and provide script content as attachments for JSON runbooks. You might also consider aws:executeScript to be simpler in terms of AWS Identity and Access Management (IAM) setup. Because it uses the permissions provided in the AutomationAssumeRole, aws:executeScript doesn't require an additional AWS Lambda function execution role. In any given scenario, one action might provide more flexibility, or added functionality, over another. Therefore, we recommend that you review the available input parameters for the runbook or action you want to use to determine which best fits your use case and preferences. Set up your development environment After you've identified your use case and the pre-defined runbooks or automation actions you want to use in your runbook, it's time to set up your development environment for the content of your Automation 1314 AWS Systems Manager User Guide runbook. To develop your runbook content, we recommend using the AWS Toolkit for Visual Studio Code instead of the Systems Manager Documents console. The Toolkit for VS Code is an open-source extension for Visual Studio Code (VS Code) that offers more features than the Systems Manager Documents console. Helpful features include schema validation for both YAML and JSON, snippets for automation action types, and auto-complete support for various options in both YAML and JSON. For more information about installing the Toolkit for VS Code, see Installing the AWS Toolkit for Visual Studio Code. For more information about using the Toolkit for VS Code to develop runbooks, see Working with Systems Manager Automation documents in the AWS Toolkit for Visual Studio Code User Guide. Develop runbook content With your use case identified and environment set up, you're ready to develop the content for your runbook. Your use case and preferences will largely dictate the automation actions or runbooks you use in your runbook content. Some actions support only a subset of input parameters when compared to another action that allows you to accomplish a similar task. Other actions have specific outputs, such as aws:createImage, where some actions allow you to define your own outputs, such as aws:executeAwsApi. If you're unsure how to use a particular action in your runbook, we recommend reviewing the corresponding entry for the action in the Systems Manager Automation actions reference. We also recommend reviewing the content of pre-defined runbooks to see real-world examples of how these actions are used. For more examples of real-world applications of runbooks, see Additional runbook examples. To demonstrate the differences in simplicity and flexibility that runbook content provides, the following tutorials provide an example of how to patch groups of Amazon EC2 instances in stages: • the section called “Example 1: Creating parent-child runbooks” – In this example, two runbooks are used in a parent-child relationship. The parent runbook initiates a rate control automation of the child runbook. • the section called “Example 2: Scripted
systems-manager-ug-395
systems-manager-ug.pdf
395
We also recommend reviewing the content of pre-defined runbooks to see real-world examples of how these actions are used. For more examples of real-world applications of runbooks, see Additional runbook examples. To demonstrate the differences in simplicity and flexibility that runbook content provides, the following tutorials provide an example of how to patch groups of Amazon EC2 instances in stages: • the section called “Example 1: Creating parent-child runbooks” – In this example, two runbooks are used in a parent-child relationship. The parent runbook initiates a rate control automation of the child runbook. • the section called “Example 2: Scripted runbook” – This example demonstrates how you can accomplish the same tasks of Example 1 by condensing the content into a single runbook and using scripts in your runbook. Automation 1315 AWS Systems Manager User Guide Example 1: Creating parent-child runbooks The following example demonstrates how to create two runbooks that patch tagged groups of Amazon Elastic Compute Cloud (Amazon EC2) instances in stages. These runbooks are used in a parent-child relationship with the parent runbook used to initiate a rate control automation of the child runbook. For more information about rate control automations, see Run automated operations at scale. For more information about the automation actions used in this example, see the Systems Manager Automation actions reference. Create the child runbook This example runbook addresses the following scenario. Emily is a Systems Engineer at AnyCompany Consultants, LLC. She needs to configure patching for groups of Amazon Elastic Compute Cloud (Amazon EC2) instances that host primary and secondary databases. Applications access these databases 24 hours a day, so one of the database instances must always be available. She decides that patching the instances in stages is the best approach. The primary group of database instances will be patched first, followed by the secondary group of database instances. Also, to avoid incurring additional costs by leaving instances running that were previously stopped, Emily wants the patched instances to be returned to their original state before the patching occurred. Emily identifies the primary and secondary groups of database instances by the tags associated with the instances. She decides to create a parent runbook that starts a rate control automation of a child runbook. By doing that, she can target the tags associated with the primary and secondary groups of database instances and manage the concurrency of the child automations. After reviewing the available Systems Manager (SSM) documents for patching, she chooses the AWS- RunPatchBaseline document. By using this SSM document, her colleagues can review the associated patch compliance information after the patching operation completes. To start creating her runbook content, Emily reviews the available automation actions and begins authoring the content for the child runbook as follows: 1. First, she provides values for the schema and description of the runbook, and defines the input parameters for the child runbook. By using the AutomationAssumeRole parameter, Emily and her colleagues can use an existing IAM role that allows Automation to perform the actions in the runbook on their behalf. Emily uses the InstanceId parameter to determine the instance that should be patched. Optionally, the Operation, RebootOption, and SnapshotId parameters can be used to provide values Automation 1316 AWS Systems Manager User Guide to document parameters for AWS-RunPatchBaseline. To prevent invalid values from being provided to those document parameters, she defines the allowedValues as needed. YAML schemaVersion: '0.3' description: 'An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.' assumeRole: '{{AutomationAssumeRole}}' parameters: AutomationAssumeRole: type: String description: >- '(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.' default: '' InstanceId: type: String description: >- '(Required) The instance you want to patch.' SnapshotId: type: String description: '(Optional) The snapshot ID to use to retrieve a patch baseline snapshot.' default: '' RebootOption: type: String description: '(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non- compliant until a subsequent reboot and scan.' allowedValues: - NoReboot - RebootIfNeeded default: RebootIfNeeded Operation: type: String description: '(Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.' allowedValues: - Install Automation 1317 AWS Systems Manager User Guide - Scan default: Install JSON { "schemaVersion":"0.3", "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.", "assumeRole":"{{AutomationAssumeRole}}", "parameters":{ "AutomationAssumeRole":{ "type":"String", "description":"(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM
systems-manager-ug-396
systems-manager-ug.pdf
396
The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.' allowedValues: - Install Automation 1317 AWS Systems Manager User Guide - Scan default: Install JSON { "schemaVersion":"0.3", "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.", "assumeRole":"{{AutomationAssumeRole}}", "parameters":{ "AutomationAssumeRole":{ "type":"String", "description":"(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.", "default":"" }, "InstanceId":{ "type":"String", "description":"(Required) The instance you want to patch." }, "SnapshotId":{ "type":"String", "description":"(Optional) The snapshot ID to use to retrieve a patch baseline snapshot.", "default":"" }, "RebootOption":{ "type":"String", "description":"(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non-compliant until a subsequent reboot and scan.", "allowedValues":[ "NoReboot", "RebootIfNeeded" ], "default":"RebootIfNeeded" }, "Operation":{ "type":"String", Automation 1318 AWS Systems Manager User Guide "description":"(Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.", "allowedValues":[ "Install", "Scan" ], "default":"Install" } } }, 2. With the top-level elements defined, Emily proceeds with authoring the actions that make up the mainSteps of the runbook. The first step outputs the current state of the target instance specified in the InstanceId input parameter using the aws:executeAwsApi action. The output of this action is used in later actions. YAML mainSteps: - name: getInstanceState action: 'aws:executeAwsApi' onFailure: Abort inputs: inputs: Service: ec2 Api: DescribeInstances InstanceIds: - '{{InstanceId}}' outputs: - Name: instanceState Selector: '$.Reservations[0].Instances[0].State.Name' Type: String nextStep: branchOnInstanceState JSON "mainSteps":[ { "name":"getInstanceState", "action":"aws:executeAwsApi", "onFailure":"Abort", Automation 1319 AWS Systems Manager User Guide "inputs":{ "inputs":null, "Service":"ec2", "Api":"DescribeInstances", "InstanceIds":[ "{{InstanceId}}" ] }, "outputs":[ { "Name":"instanceState", "Selector":"$.Reservations[0].Instances[0].State.Name", "Type":"String" } ], "nextStep":"branchOnInstanceState" }, 3. Rather than manually starting and keeping track of the original state of every instance that needs to be patched, Emily uses the output from the previous action to branch the automation based on the state of the target instance. This allows the automation to run different steps depending on the conditions defined in the aws:branch action and improves the overall efficiency of the automation without manual intervention. If the instance state is already running, the automation proceeds with patching the instance with the AWS-RunPatchBaseline document using the aws:runCommand action. If the instance state is stopping, the automation polls for the instance to reach the stopped state using the aws:waitForAwsResourceProperty action, starts the instance using the executeAwsApi action, and polls for the instance to reach a running state before patching the instance. If the instance state is stopped, the automation starts the instance and polls for the instance to reach a running state before patching the instance using the same actions. YAML - name: branchOnInstanceState action: 'aws:branch' onFailure: Abort inputs: Choices: Automation 1320 AWS Systems Manager User Guide - NextStep: startInstance Variable: '{{getInstanceState.instanceState}}' StringEquals: stopped - NextStep: verifyInstanceStopped Variable: '{{getInstanceState.instanceState}}' StringEquals: stopping - NextStep: patchInstance Variable: '{{getInstanceState.instanceState}}' StringEquals: running isEnd: true - name: startInstance action: 'aws:executeAwsApi' onFailure: Abort inputs: Service: ec2 Api: StartInstances InstanceIds: - '{{InstanceId}}' nextStep: verifyInstanceRunning - name: verifyInstanceRunning action: 'aws:waitForAwsResourceProperty' timeoutSeconds: 120 inputs: Service: ec2 Api: DescribeInstances InstanceIds: - '{{InstanceId}}' PropertySelector: '$.Reservations[0].Instances[0].State.Name' DesiredValues: - running nextStep: patchInstance - name: verifyInstanceStopped action: 'aws:waitForAwsResourceProperty' timeoutSeconds: 120 inputs: Service: ec2 Api: DescribeInstances InstanceIds: - '{{InstanceId}}' PropertySelector: '$.Reservations[0].Instances[0].State.Name' DesiredValues: - stopped nextStep: startInstance - name: patchInstance Automation 1321 AWS Systems Manager User Guide action: 'aws:runCommand' onFailure: Abort timeoutSeconds: 5400 inputs: DocumentName: 'AWS-RunPatchBaseline' InstanceIds: - '{{InstanceId}}' Parameters: SnapshotId: '{{SnapshotId}}' RebootOption: '{{RebootOption}}' Operation: '{{Operation}}' JSON { "name":"branchOnInstanceState", "action":"aws:branch", "onFailure":"Abort", "inputs":{ "Choices":[ { "NextStep":"startInstance", "Variable":"{{getInstanceState.instanceState}}", "StringEquals":"stopped" }, { "Or":[ { "Variable":"{{getInstanceState.instanceState}}", "StringEquals":"stopping" } ], "NextStep":"verifyInstanceStopped" }, { "NextStep":"patchInstance", "Variable":"{{getInstanceState.instanceState}}", "StringEquals":"running" } ] }, "isEnd":true }, Automation 1322 AWS Systems Manager { User Guide "name":"startInstance", "action":"aws:executeAwsApi", "onFailure":"Abort", "inputs":{ "Service":"ec2", "Api":"StartInstances", "InstanceIds":[ "{{InstanceId}}" ] }, "nextStep":"verifyInstanceRunning" }, { "name":"verifyInstanceRunning", "action":"aws:waitForAwsResourceProperty", "timeoutSeconds":120, "inputs":{ "Service":"ec2", "Api":"DescribeInstances", "InstanceIds":[ "{{InstanceId}}" ], "PropertySelector":"$.Reservations[0].Instances[0].State.Name", "DesiredValues":[ "running" ] }, "nextStep":"patchInstance" }, { "name":"verifyInstanceStopped", "action":"aws:waitForAwsResourceProperty", "timeoutSeconds":120, "inputs":{ "Service":"ec2", "Api":"DescribeInstances", "InstanceIds":[ "{{InstanceId}}" ], "PropertySelector":"$.Reservations[0].Instances[0].State.Name", "DesiredValues":[ "stopped" ], Automation 1323 AWS Systems Manager User Guide "nextStep":"startInstance" } }, { "name":"patchInstance", "action":"aws:runCommand", "onFailure":"Abort", "timeoutSeconds":5400, "inputs":{ "DocumentName":"AWS-RunPatchBaseline", "InstanceIds":[ "{{InstanceId}}" ], "Parameters":{ "SnapshotId":"{{SnapshotId}}", "RebootOption":"{{RebootOption}}", "Operation":"{{Operation}}" } } }, 4. After the patching operation completes, Emily wants the automation to return the target instance to the same state it was in before the automation started. She does this by again using the output from the first action. The automation branches based on the original state of the target instance using the aws:branch action. If the instance was previously in any state other than running, the instance is stopped. Otherwise, if the
systems-manager-ug-397
systems-manager-ug.pdf
397
], Automation 1323 AWS Systems Manager User Guide "nextStep":"startInstance" } }, { "name":"patchInstance", "action":"aws:runCommand", "onFailure":"Abort", "timeoutSeconds":5400, "inputs":{ "DocumentName":"AWS-RunPatchBaseline", "InstanceIds":[ "{{InstanceId}}" ], "Parameters":{ "SnapshotId":"{{SnapshotId}}", "RebootOption":"{{RebootOption}}", "Operation":"{{Operation}}" } } }, 4. After the patching operation completes, Emily wants the automation to return the target instance to the same state it was in before the automation started. She does this by again using the output from the first action. The automation branches based on the original state of the target instance using the aws:branch action. If the instance was previously in any state other than running, the instance is stopped. Otherwise, if the instance state is running, the automation ends. YAML - name: branchOnOriginalInstanceState action: 'aws:branch' onFailure: Abort inputs: Choices: - NextStep: stopInstance Not: Variable: '{{getInstanceState.instanceState}}' StringEquals: running isEnd: true - name: stopInstance action: 'aws:executeAwsApi' onFailure: Abort Automation 1324 AWS Systems Manager User Guide inputs: Service: ec2 Api: StopInstances InstanceIds: - '{{InstanceId}}' JSON { "name":"branchOnOriginalInstanceState", "action":"aws:branch", "onFailure":"Abort", "inputs":{ "Choices":[ { "NextStep":"stopInstance", "Not":{ "Variable":"{{getInstanceState.instanceState}}", "StringEquals":"running" } } ] }, "isEnd":true }, { "name":"stopInstance", "action":"aws:executeAwsApi", "onFailure":"Abort", "inputs":{ "Service":"ec2", "Api":"StopInstances", "InstanceIds":[ "{{InstanceId}}" ] } } ] } 5. Emily reviews the completed child runbook content and creates the runbook in the same AWS account and AWS Region as the target instances. Now she's ready to continue with the creation of the parent runbook's content. The following is the completed child runbook content. Automation 1325 AWS Systems Manager YAML User Guide schemaVersion: '0.3' description: 'An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.' assumeRole: '{{AutomationAssumeRole}}' parameters: AutomationAssumeRole: type: String description: >- '(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.' default: '' InstanceId: type: String description: >- '(Required) The instance you want to patch.' SnapshotId: type: String description: '(Optional) The snapshot ID to use to retrieve a patch baseline snapshot.' default: '' RebootOption: type: String description: '(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non- compliant until a subsequent reboot and scan.' allowedValues: - NoReboot - RebootIfNeeded default: RebootIfNeeded Operation: type: String description: '(Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.' allowedValues: - Install - Scan default: Install Automation 1326 User Guide AWS Systems Manager mainSteps: - name: getInstanceState action: 'aws:executeAwsApi' onFailure: Abort inputs: inputs: Service: ec2 Api: DescribeInstances InstanceIds: - '{{InstanceId}}' outputs: - Name: instanceState Selector: '$.Reservations[0].Instances[0].State.Name' Type: String nextStep: branchOnInstanceState - name: branchOnInstanceState action: 'aws:branch' onFailure: Abort inputs: Choices: - NextStep: startInstance Variable: '{{getInstanceState.instanceState}}' StringEquals: stopped - Or: - Variable: '{{getInstanceState.instanceState}}' StringEquals: stopping NextStep: verifyInstanceStopped - NextStep: patchInstance Variable: '{{getInstanceState.instanceState}}' StringEquals: running isEnd: true - name: startInstance action: 'aws:executeAwsApi' onFailure: Abort inputs: Service: ec2 Api: StartInstances InstanceIds: - '{{InstanceId}}' nextStep: verifyInstanceRunning - name: verifyInstanceRunning action: 'aws:waitForAwsResourceProperty' timeoutSeconds: 120 inputs: Automation 1327 AWS Systems Manager User Guide Service: ec2 Api: DescribeInstances InstanceIds: - '{{InstanceId}}' PropertySelector: '$.Reservations[0].Instances[0].State.Name' DesiredValues: - running nextStep: patchInstance - name: verifyInstanceStopped action: 'aws:waitForAwsResourceProperty' timeoutSeconds: 120 inputs: Service: ec2 Api: DescribeInstances InstanceIds: - '{{InstanceId}}' PropertySelector: '$.Reservations[0].Instances[0].State.Name' DesiredValues: - stopped nextStep: startInstance - name: patchInstance action: 'aws:runCommand' onFailure: Abort timeoutSeconds: 5400 inputs: DocumentName: 'AWS-RunPatchBaseline' InstanceIds: - '{{InstanceId}}' Parameters: SnapshotId: '{{SnapshotId}}' RebootOption: '{{RebootOption}}' Operation: '{{Operation}}' - name: branchOnOriginalInstanceState action: 'aws:branch' onFailure: Abort inputs: Choices: - NextStep: stopInstance Not: Variable: '{{getInstanceState.instanceState}}' StringEquals: running isEnd: true - name: stopInstance action: 'aws:executeAwsApi' Automation 1328 AWS Systems Manager User Guide onFailure: Abort inputs: Service: ec2 Api: StopInstances InstanceIds: - '{{InstanceId}}' JSON { "schemaVersion":"0.3", "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.", "assumeRole":"{{AutomationAssumeRole}}", "parameters":{ "AutomationAssumeRole":{ "type":"String", "description":"'(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.'", "default":"" }, "InstanceId":{ "type":"String", "description":"'(Required) The instance you want to patch.'" }, "SnapshotId":{ "type":"String", "description":"(Optional) The snapshot ID to use to retrieve a patch baseline snapshot.", "default":"" }, "RebootOption":{ "type":"String", "description":"(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non-compliant until a subsequent reboot and scan.", "allowedValues":[ "NoReboot", "RebootIfNeeded" ], "default":"RebootIfNeeded" Automation 1329 AWS Systems Manager }, "Operation":{ "type":"String", User Guide "description":"(Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.", "allowedValues":[ "Install", "Scan" ], "default":"Install" } }, "mainSteps":[ { "name":"getInstanceState", "action":"aws:executeAwsApi", "onFailure":"Abort", "inputs":{ "inputs":null, "Service":"ec2", "Api":"DescribeInstances", "InstanceIds":[ "{{InstanceId}}" ] }, "outputs":[ { "Name":"instanceState",
systems-manager-ug-398
systems-manager-ug.pdf
398
"description":"(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non-compliant until a subsequent reboot and scan.", "allowedValues":[ "NoReboot", "RebootIfNeeded" ], "default":"RebootIfNeeded" Automation 1329 AWS Systems Manager }, "Operation":{ "type":"String", User Guide "description":"(Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.", "allowedValues":[ "Install", "Scan" ], "default":"Install" } }, "mainSteps":[ { "name":"getInstanceState", "action":"aws:executeAwsApi", "onFailure":"Abort", "inputs":{ "inputs":null, "Service":"ec2", "Api":"DescribeInstances", "InstanceIds":[ "{{InstanceId}}" ] }, "outputs":[ { "Name":"instanceState", "Selector":"$.Reservations[0].Instances[0].State.Name", "Type":"String" } ], "nextStep":"branchOnInstanceState" }, { "name":"branchOnInstanceState", "action":"aws:branch", "onFailure":"Abort", "inputs":{ "Choices":[ { "NextStep":"startInstance", Automation 1330 AWS Systems Manager User Guide "Variable":"{{getInstanceState.instanceState}}", "StringEquals":"stopped" }, { "Or":[ { "Variable":"{{getInstanceState.instanceState}}", "StringEquals":"stopping" } ], "NextStep":"verifyInstanceStopped" }, { "NextStep":"patchInstance", "Variable":"{{getInstanceState.instanceState}}", "StringEquals":"running" } ] }, "isEnd":true }, { "name":"startInstance", "action":"aws:executeAwsApi", "onFailure":"Abort", "inputs":{ "Service":"ec2", "Api":"StartInstances", "InstanceIds":[ "{{InstanceId}}" ] }, "nextStep":"verifyInstanceRunning" }, { "name":"verifyInstanceRunning", "action":"aws:waitForAwsResourceProperty", "timeoutSeconds":120, "inputs":{ "Service":"ec2", "Api":"DescribeInstances", "InstanceIds":[ "{{InstanceId}}" ], Automation 1331 AWS Systems Manager User Guide "PropertySelector":"$.Reservations[0].Instances[0].State.Name", "DesiredValues":[ "running" ] }, "nextStep":"patchInstance" }, { "name":"verifyInstanceStopped", "action":"aws:waitForAwsResourceProperty", "timeoutSeconds":120, "inputs":{ "Service":"ec2", "Api":"DescribeInstances", "InstanceIds":[ "{{InstanceId}}" ], "PropertySelector":"$.Reservations[0].Instances[0].State.Name", "DesiredValues":[ "stopped" ], "nextStep":"startInstance" } }, { "name":"patchInstance", "action":"aws:runCommand", "onFailure":"Abort", "timeoutSeconds":5400, "inputs":{ "DocumentName":"AWS-RunPatchBaseline", "InstanceIds":[ "{{InstanceId}}" ], "Parameters":{ "SnapshotId":"{{SnapshotId}}", "RebootOption":"{{RebootOption}}", "Operation":"{{Operation}}" } } }, { "name":"branchOnOriginalInstanceState", "action":"aws:branch", Automation 1332 AWS Systems Manager User Guide "onFailure":"Abort", "inputs":{ "Choices":[ { "NextStep":"stopInstance", "Not":{ "Variable":"{{getInstanceState.instanceState}}", "StringEquals":"running" } } ] }, "isEnd":true }, { "name":"stopInstance", "action":"aws:executeAwsApi", "onFailure":"Abort", "inputs":{ "Service":"ec2", "Api":"StopInstances", "InstanceIds":[ "{{InstanceId}}" ] } } ] } For more information about the automation actions used in this example, see the Systems Manager Automation actions reference. Create the parent runbook This example runbook continues the scenario described in the previous section. Now that Emily has created the child runbook, she begins authoring the content for the parent runbook as follows: 1. First, she provides values for the schema and description of the runbook, and defines the input parameters for the parent runbook. By using the AutomationAssumeRole parameter, Emily and her colleagues can use an existing IAM role that allows Automation to perform the actions in the runbook on their behalf. Emily Automation 1333 AWS Systems Manager User Guide uses the PatchGroupPrimaryKey and PatchGroupPrimaryValue parameters to specify the tag associated with the primary group of database instances that will be patched. She uses the PatchGroupSecondaryKey and PatchGroupSecondaryValue parameters to specify the tag associated with the secondary group of database instances that will be patched. YAML description: 'An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.' schemaVersion: '0.3' assumeRole: '{{AutomationAssumeRole}}' parameters: AutomationAssumeRole: type: String description: '(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.' default: '' PatchGroupPrimaryKey: type: String description: '(Required) The key of the tag for the primary group of instances you want to patch.'' PatchGroupPrimaryValue: type: String description: '(Required) The value of the tag for the primary group of instances you want to patch.' PatchGroupSecondaryKey: type: String description: '(Required) The key of the tag for the secondary group of instances you want to patch.' PatchGroupSecondaryValue: type: String description: '(Required) The value of the tag for the secondary group of instances you want to patch.' JSON { "schemaVersion": "0.3", "description": "An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.", "assumeRole": "{{AutomationAssumeRole}}", "parameters": { Automation 1334 AWS Systems Manager User Guide "AutomationAssumeRole": { "type": "String", "description": "(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.", "default": "" }, "PatchGroupPrimaryKey": { "type": "String", "description": "(Required) The key of the tag for the primary group of instances you want to patch." }, "PatchGroupPrimaryValue": { "type": "String", "description": "(Required) The value of the tag for the primary group of instances you want to patch." }, "PatchGroupSecondaryKey": { "type": "String", "description": "(Required) The key of the tag for the secondary group of instances you want to patch." }, "PatchGroupSecondaryValue": { "type": "String", "description": "(Required) The value of the tag for the secondary group of instances you want to patch." } } }, 2. With the top-level elements defined, Emily proceeds with authoring the actions that make up the mainSteps of the runbook. The first action starts a rate control automation using the child runbook she just created that targets instances associated with the tag specified in the PatchGroupPrimaryKey and PatchGroupPrimaryValue input parameters. She uses the values provided to the input parameters to specify the key and value of the tag associated with the primary group of database instances she wants to patch. After the first automation completes,
systems-manager-ug-399
systems-manager-ug.pdf
399
the tag for the secondary group of instances you want to patch." } } }, 2. With the top-level elements defined, Emily proceeds with authoring the actions that make up the mainSteps of the runbook. The first action starts a rate control automation using the child runbook she just created that targets instances associated with the tag specified in the PatchGroupPrimaryKey and PatchGroupPrimaryValue input parameters. She uses the values provided to the input parameters to specify the key and value of the tag associated with the primary group of database instances she wants to patch. After the first automation completes, the second action starts another rate control automation using the child runbook that targets instances associated with the tag specified in the Automation 1335 AWS Systems Manager User Guide PatchGroupSecondaryKey and PatchGroupSecondaryValue input parameters. She uses the values provided to the input parameters to specify the key and value of the tag associated with the secondary group of database instances she wants to patch. YAML mainSteps: - name: patchPrimaryTargets action: 'aws:executeAutomation' onFailure: Abort timeoutSeconds: 7200 inputs: DocumentName: RunbookTutorialChildAutomation Targets: - Key: 'tag:{{PatchGroupPrimaryKey}}' Values: - '{{PatchGroupPrimaryValue}}' TargetParameterName: 'InstanceId' - name: patchSecondaryTargets action: 'aws:executeAutomation' onFailure: Abort timeoutSeconds: 7200 inputs: DocumentName: RunbookTutorialChildAutomation Targets: - Key: 'tag:{{PatchGroupSecondaryKey}}' Values: - '{{PatchGroupSecondaryValue}}' TargetParameterName: 'InstanceId' JSON "mainSteps":[ { "name":"patchPrimaryTargets", "action":"aws:executeAutomation", "onFailure":"Abort", "timeoutSeconds":7200, "inputs":{ "DocumentName":"RunbookTutorialChildAutomation", "Targets":[ { "Key":"tag:{{PatchGroupPrimaryKey}}", Automation 1336 AWS Systems Manager User Guide "Values":[ "{{PatchGroupPrimaryValue}}" ] } ], "TargetParameterName":"InstanceId" } }, { "name":"patchSecondaryTargets", "action":"aws:executeAutomation", "onFailure":"Abort", "timeoutSeconds":7200, "inputs":{ "DocumentName":"RunbookTutorialChildAutomation", "Targets":[ { "Key":"tag:{{PatchGroupSecondaryKey}}", "Values":[ "{{PatchGroupSecondaryValue}}" ] } ], "TargetParameterName":"InstanceId" } } ] } 3. Emily reviews the completed parent runbook content and creates the runbook in the same AWS account and AWS Region as the target instances. Now, she is ready to test her runbooks to make sure the automation operates as desired before implementing them into her production environment. The following is the completed parent runbook content. YAML description: An example of an Automation runbook that patches groups of Amazon EC2 instances in stages. schemaVersion: '0.3' assumeRole: '{{AutomationAssumeRole}}' parameters: AutomationAssumeRole: type: String Automation 1337 AWS Systems Manager User Guide description: '(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.' default: '' PatchGroupPrimaryKey: type: String description: (Required) The key of the tag for the primary group of instances you want to patch. PatchGroupPrimaryValue: type: String description: '(Required) The value of the tag for the primary group of instances you want to patch. ' PatchGroupSecondaryKey: type: String description: (Required) The key of the tag for the secondary group of instances you want to patch. PatchGroupSecondaryValue: type: String description: '(Required) The value of the tag for the secondary group of instances you want to patch. ' mainSteps: - name: patchPrimaryTargets action: 'aws:executeAutomation' onFailure: Abort timeoutSeconds: 7200 inputs: DocumentName: RunbookTutorialChildAutomation Targets: - Key: 'tag:{{PatchGroupPrimaryKey}}' Values: - '{{PatchGroupPrimaryValue}}' TargetParameterName: 'InstanceId' - name: patchSecondaryTargets action: 'aws:executeAutomation' onFailure: Abort timeoutSeconds: 7200 inputs: DocumentName: RunbookTutorialChildAutomation Targets: - Key: 'tag:{{PatchGroupSecondaryKey}}' Values: - '{{PatchGroupSecondaryValue}}' TargetParameterName: 'InstanceId' Automation 1338 AWS Systems Manager JSON { User Guide "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.", "schemaVersion":"0.3", "assumeRole":"{{AutomationAssumeRole}}", "parameters":{ "AutomationAssumeRole":{ "type":"String", "description":"(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.", "default":"" }, "PatchGroupPrimaryKey":{ "type":"String", "description":"(Required) The key of the tag for the primary group of instances you want to patch." }, "PatchGroupPrimaryValue":{ "type":"String", "description":"(Required) The value of the tag for the primary group of instances you want to patch. " }, "PatchGroupSecondaryKey":{ "type":"String", "description":"(Required) The key of the tag for the secondary group of instances you want to patch." }, "PatchGroupSecondaryValue":{ "type":"String", "description":"(Required) The value of the tag for the secondary group of instances you want to patch. " } }, "mainSteps":[ { "name":"patchPrimaryTargets", "action":"aws:executeAutomation", "onFailure":"Abort", "timeoutSeconds":7200, Automation 1339 AWS Systems Manager "inputs":{ User Guide "DocumentName":"RunbookTutorialChildAutomation", "Targets":[ { "Key":"tag:{{PatchGroupPrimaryKey}}", "Values":[ "{{PatchGroupPrimaryValue}}" ] } ], "TargetParameterName":"InstanceId" } }, { "name":"patchSecondaryTargets", "action":"aws:executeAutomation", "onFailure":"Abort", "timeoutSeconds":7200, "inputs":{ "DocumentName":"RunbookTutorialChildAutomation", "Targets":[ { "Key":"tag:{{PatchGroupSecondaryKey}}", "Values":[ "{{PatchGroupSecondaryValue}}" ] } ], "TargetParameterName":"InstanceId" } } ] } For more information about the automation actions used in this example, see the Systems Manager Automation actions reference. Example 2: Scripted runbook This example runbook addresses the following scenario. Emily is a Systems Engineer at AnyCompany Consultants, LLC. She previously created two runbooks that are used in a parent-child relationship to patch groups of Amazon Elastic Compute Cloud (Amazon EC2) instances that host Automation 1340 AWS Systems Manager User Guide primary and secondary databases. Applications access these databases 24 hours a day, so one of the database instances must always be available. Based on this requirement, she built a solution that patches
systems-manager-ug-400
systems-manager-ug.pdf
400
information about the automation actions used in this example, see the Systems Manager Automation actions reference. Example 2: Scripted runbook This example runbook addresses the following scenario. Emily is a Systems Engineer at AnyCompany Consultants, LLC. She previously created two runbooks that are used in a parent-child relationship to patch groups of Amazon Elastic Compute Cloud (Amazon EC2) instances that host Automation 1340 AWS Systems Manager User Guide primary and secondary databases. Applications access these databases 24 hours a day, so one of the database instances must always be available. Based on this requirement, she built a solution that patches the instances in stages using the AWS-RunPatchBaseline Systems Manager (SSM) document. By using this SSM document, her colleagues can review the associated patch compliance information after the patching operation completes. The primary group of database instances are patched first, followed by the secondary group of database instances. Also, to avoid incurring additional costs by leaving instances running that were previously stopped, Emily made sure that the automation returned the patched instances to their original state before the patching occurred. Emily used tags that are associated with the primary and secondary groups of database instances to identify which instances should be patched in her desired order. Her existing automated solution works, but she wants to improve her solution if possible. To help with the maintenance of the runbook content and to ease troubleshooting efforts, she would like to condense the automation into a single runbook and simplify the number of input parameters. Also, she would like to avoid creating multiple child automations. After Emily reviews the available automation actions, she determines that she can improve her solution by using the aws:executeScript action to run her custom Python scripts. She now begins authoring the content for the runbook as follows: 1. First, she provides values for the schema and description of the runbook, and defines the input parameters for the parent runbook. By using the AutomationAssumeRole parameter, Emily and her colleagues can use an existing IAM role that allows Automation to perform the actions in the runbook on their behalf. Unlike Example 1, the AutomationAssumeRole parameter is now required rather than optional. Because this runbook includes aws:executeScript actions, an AWS Identity and Access Management (IAM) service role (or assume role) is always required. This requirement is necessary because some of the Python scripts specified for the actions call AWS API operations. Emily uses the PrimaryPatchGroupTag and SecondaryPatchGroupTag parameters to specify the tags associated with the primary and secondary group of database instances that will be patched. To simplify the required input parameters, she decides to use StringMap parameters rather than using multiple String parameters as she used in the Example 1 runbook. Optionally, the Operation, RebootOption, and SnapshotId parameters Automation 1341 AWS Systems Manager User Guide can be used to provide values to document parameters for AWS-RunPatchBaseline. To prevent invalid values from being provided to those document parameters, she defines the allowedValues as needed. YAML description: 'An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.' schemaVersion: '0.3' assumeRole: '{{AutomationAssumeRole}}' parameters: AutomationAssumeRole: type: String description: '(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.' PrimaryPatchGroupTag: type: StringMap description: '(Required) The tag for the primary group of instances you want to patch. Specify a key-value pair. Example: {"key" : "value"}' SecondaryPatchGroupTag: type: StringMap description: '(Required) The tag for the secondary group of instances you want to patch. Specify a key-value pair. Example: {"key" : "value"}' SnapshotId: type: String description: '(Optional) The snapshot ID to use to retrieve a patch baseline snapshot.' default: '' RebootOption: type: String description: '(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non- compliant until a subsequent reboot and scan.' allowedValues: - NoReboot - RebootIfNeeded default: RebootIfNeeded Operation: type: String description: '(Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.' Automation 1342 AWS Systems Manager User Guide allowedValues: - Install - Scan default: Install JSON { "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.", "schemaVersion":"0.3", "assumeRole":"{{AutomationAssumeRole}}", "parameters":{ "AutomationAssumeRole":{ "type":"String", "description":"(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook." }, "PrimaryPatchGroupTag":{ "type":"StringMap", "description":"(Required) The tag for the primary group of instances you want to patch. Specify a key-value pair. Example: {\"key\" : \"value\"}" }, "SecondaryPatchGroupTag":{ "type":"StringMap", "description":"(Required)
systems-manager-ug-401
systems-manager-ug.pdf
401
Automation 1342 AWS Systems Manager User Guide allowedValues: - Install - Scan default: Install JSON { "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.", "schemaVersion":"0.3", "assumeRole":"{{AutomationAssumeRole}}", "parameters":{ "AutomationAssumeRole":{ "type":"String", "description":"(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook." }, "PrimaryPatchGroupTag":{ "type":"StringMap", "description":"(Required) The tag for the primary group of instances you want to patch. Specify a key-value pair. Example: {\"key\" : \"value\"}" }, "SecondaryPatchGroupTag":{ "type":"StringMap", "description":"(Required) The tag for the secondary group of instances you want to patch. Specify a key-value pair. Example: {\"key\" : \"value\"}" }, "SnapshotId":{ "type":"String", "description":"(Optional) The snapshot ID to use to retrieve a patch baseline snapshot.", "default":"" }, "RebootOption":{ "type":"String", "description":"(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non-compliant until a subsequent reboot and scan.", "allowedValues":[ "NoReboot", Automation 1343 AWS Systems Manager User Guide "RebootIfNeeded" ], "default":"RebootIfNeeded" }, "Operation":{ "type":"String", "description":"(Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.", "allowedValues":[ "Install", "Scan" ], "default":"Install" } } }, 2. With the top-level elements defined, Emily proceeds with authoring the actions that make up the mainSteps of the runbook. The first step gathers the IDs of all instances associated with the tag specified in the PrimaryPatchGroupTag parameter and outputs a StringMap parameter containing the instance ID and the current state of the instance. The output of this action is used in later actions. Note that the script input parameter isn't supported for JSON runbooks. JSON runbooks must provide script content using the attachment input parameter. YAML mainSteps: - name: getPrimaryInstanceState action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort inputs: Runtime: python3.7 Handler: getInstanceStates InputPayload: primaryTag: '{{PrimaryPatchGroupTag}}' Script: |- def getInstanceStates(events,context): import boto3 Automation 1344 AWS Systems Manager User Guide #Initialize client ec2 = boto3.client('ec2') tag = events['primaryTag'] tagKey, tagValue = list(tag.items())[0] instanceQuery = ec2.describe_instances( Filters=[ { "Name": "tag:" + tagKey, "Values": [tagValue] }] ) if not instanceQuery['Reservations']: noInstancesForTagString = "No instances found for specified tag." return({ 'noInstancesFound' : noInstancesForTagString }) else: queryResponse = instanceQuery['Reservations'] originalInstanceStates = {} for results in queryResponse: instanceSet = results['Instances'] for instance in instanceSet: instanceId = instance['InstanceId'] originalInstanceStates[instanceId] = instance['State'] ['Name'] return originalInstanceStates outputs: - Name: originalInstanceStates Selector: $.Payload Type: StringMap nextStep: verifyPrimaryInstancesRunning JSON "mainSteps":[ { "name":"getPrimaryInstanceState", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"getInstanceStates", "InputPayload":{ Automation 1345 AWS Systems Manager User Guide "primaryTag":"{{PrimaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"originalInstanceStates", "Selector":"$.Payload", "Type":"StringMap" } ], "nextStep":"verifyPrimaryInstancesRunning" }, 3. Emily uses the output from the previous action in another aws:executeScript action to verify all instances associated with the tag specified in the PrimaryPatchGroupTag parameter are in a running state. If the instance state is already running or shutting-down, the script continues to loop through the remaining instances. If the instance state is stopping, the script polls for the instance to reach the stopped state and starts the instance. If the instance state is stopped, the script starts the instance. YAML - name: verifyPrimaryInstancesRunning action: 'aws:executeScript' timeoutSeconds: 600 onFailure: Abort inputs: Runtime: python3.7 Handler: verifyInstancesRunning InputPayload: targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}' Script: |- def verifyInstancesRunning(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') Automation 1346 AWS Systems Manager User Guide instanceDict = events['targetInstances'] for instance in instanceDict: if instanceDict[instance] == 'stopped': print("The target instance " + instance + " is stopped. The instance will now be started.") ec2.start_instances( InstanceIds=[instance] ) elif instanceDict[instance] == 'stopping': print("The target instance " + instance + " is stopping. Polling for instance to reach stopped state.") while instanceDict[instance] != 'stopped': poll = ec2.get_waiter('instance_stopped') poll.wait( InstanceIds=[instance] ) ec2.start_instances( InstanceIds=[instance] ) else: pass nextStep: waitForPrimaryRunningInstances JSON { "name":"verifyPrimaryInstancesRunning", "action":"aws:executeScript", "timeoutSeconds":600, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"verifyInstancesRunning", "InputPayload":{ "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}" }, "Script":"..." }, "nextStep":"waitForPrimaryRunningInstances" }, Automation 1347 AWS Systems Manager User Guide 4. Emily verifies that all instances associated with the tag specified in the PrimaryPatchGroupTag parameter were started or already in a running state. Then she uses another script to verify that all instances, including those that were started in the previous action, have reached the running state. YAML - name: waitForPrimaryRunningInstances action: 'aws:executeScript' timeoutSeconds: 300 onFailure: Abort inputs: Runtime: python3.7 Handler: waitForRunningInstances InputPayload: targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}' Script: |- def waitForRunningInstances(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: poll = ec2.get_waiter('instance_running') poll.wait( InstanceIds=[instance] ) nextStep: returnPrimaryTagKey JSON { "name":"waitForPrimaryRunningInstances", "action":"aws:executeScript", "timeoutSeconds":300, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"waitForRunningInstances", "InputPayload":{ "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}" Automation 1348 AWS Systems Manager User Guide }, "Script":"..." }, "nextStep":"returnPrimaryTagKey" }, 5. Emily uses two more scripts to return individual String values of the key and value of the tag specified in the PrimaryPatchGroupTag parameter. The values returned
systems-manager-ug-402
systems-manager-ug.pdf
402
action, have reached the running state. YAML - name: waitForPrimaryRunningInstances action: 'aws:executeScript' timeoutSeconds: 300 onFailure: Abort inputs: Runtime: python3.7 Handler: waitForRunningInstances InputPayload: targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}' Script: |- def waitForRunningInstances(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: poll = ec2.get_waiter('instance_running') poll.wait( InstanceIds=[instance] ) nextStep: returnPrimaryTagKey JSON { "name":"waitForPrimaryRunningInstances", "action":"aws:executeScript", "timeoutSeconds":300, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"waitForRunningInstances", "InputPayload":{ "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}" Automation 1348 AWS Systems Manager User Guide }, "Script":"..." }, "nextStep":"returnPrimaryTagKey" }, 5. Emily uses two more scripts to return individual String values of the key and value of the tag specified in the PrimaryPatchGroupTag parameter. The values returned by these actions allows her to provide values directly to the Targets parameter for the AWS- RunPatchBaseline document. The automation then proceeds with patching the instance with the AWS-RunPatchBaseline document using the aws:runCommand action. YAML - name: returnPrimaryTagKey action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort inputs: Runtime: python3.7 Handler: returnTagValues InputPayload: primaryTag: '{{PrimaryPatchGroupTag}}' Script: |- def returnTagValues(events,context): tag = events['primaryTag'] tagKey = list(tag)[0] stringKey = "tag:" + tagKey return {'tagKey' : stringKey} outputs: - Name: Payload Selector: $.Payload Type: StringMap - Name: primaryPatchGroupKey Selector: $.Payload.tagKey Type: String nextStep: returnPrimaryTagValue - name: returnPrimaryTagValue action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort inputs: Runtime: python3.7 Automation 1349 AWS Systems Manager User Guide Handler: returnTagValues InputPayload: primaryTag: '{{PrimaryPatchGroupTag}}' Script: |- def returnTagValues(events,context): tag = events['primaryTag'] tagKey = list(tag)[0] tagValue = tag[tagKey] return {'tagValue' : tagValue} outputs: - Name: Payload Selector: $.Payload Type: StringMap - Name: primaryPatchGroupValue Selector: $.Payload.tagValue Type: String nextStep: patchPrimaryInstances - name: patchPrimaryInstances action: 'aws:runCommand' onFailure: Abort timeoutSeconds: 7200 inputs: DocumentName: AWS-RunPatchBaseline Parameters: SnapshotId: '{{SnapshotId}}' RebootOption: '{{RebootOption}}' Operation: '{{Operation}}' Targets: - Key: '{{returnPrimaryTagKey.primaryPatchGroupKey}}' Values: - '{{returnPrimaryTagValue.primaryPatchGroupValue}}' MaxConcurrency: 10% MaxErrors: 10% nextStep: returnPrimaryToOriginalState JSON { "name":"returnPrimaryTagKey", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ Automation 1350 AWS Systems Manager User Guide "Runtime":"python3.7", "Handler":"returnTagValues", "InputPayload":{ "primaryTag":"{{PrimaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"Payload", "Selector":"$.Payload", "Type":"StringMap" }, { "Name":"primaryPatchGroupKey", "Selector":"$.Payload.tagKey", "Type":"String" } ], "nextStep":"returnPrimaryTagValue" }, { "name":"returnPrimaryTagValue", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnTagValues", "InputPayload":{ "primaryTag":"{{PrimaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"Payload", "Selector":"$.Payload", "Type":"StringMap" }, { "Name":"primaryPatchGroupValue", "Selector":"$.Payload.tagValue", "Type":"String" Automation 1351 AWS Systems Manager } User Guide ], "nextStep":"patchPrimaryInstances" }, { "name":"patchPrimaryInstances", "action":"aws:runCommand", "onFailure":"Abort", "timeoutSeconds":7200, "inputs":{ "DocumentName":"AWS-RunPatchBaseline", "Parameters":{ "SnapshotId":"{{SnapshotId}}", "RebootOption":"{{RebootOption}}", "Operation":"{{Operation}}" }, "Targets":[ { "Key":"{{returnPrimaryTagKey.primaryPatchGroupKey}}", "Values":[ "{{returnPrimaryTagValue.primaryPatchGroupValue}}" ] } ], "MaxConcurrency":"10%", "MaxErrors":"10%" }, "nextStep":"returnPrimaryToOriginalState" }, 6. After the patching operation completes, Emily wants the automation to return the target instances associated with the tag specified in the PrimaryPatchGroupTag parameter to the same state they were before the automation started. She does this by again using the output from the first action in a script. Based on the original state of the target instance, if the instance was previously in any state other than running, the instance is stopped. Otherwise, if the instance state is running, the script continues to loop through the remaining instances. YAML - name: returnPrimaryToOriginalState action: 'aws:executeScript' timeoutSeconds: 600 onFailure: Abort Automation 1352 AWS Systems Manager inputs: Runtime: python3.7 Handler: returnToOriginalState InputPayload: User Guide targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}' Script: |- def returnToOriginalState(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: if instanceDict[instance] == 'stopped' or instanceDict[instance] == 'stopping': ec2.stop_instances( InstanceIds=[instance] ) else: pass nextStep: getSecondaryInstanceState JSON { "name":"returnPrimaryToOriginalState", "action":"aws:executeScript", "timeoutSeconds":600, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnToOriginalState", "InputPayload":{ "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}" }, "Script":"..." }, "nextStep":"getSecondaryInstanceState" }, 7. The patching operation is completed for the instances associated with the tag specified in the PrimaryPatchGroupTag parameter. Now Emily duplicates all of the previous actions Automation 1353 AWS Systems Manager User Guide in her runbook content to target the instances associated with the tag specified in the SecondaryPatchGroupTag parameter. YAML - name: getSecondaryInstanceState action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort inputs: Runtime: python3.7 Handler: getInstanceStates InputPayload: secondaryTag: '{{SecondaryPatchGroupTag}}' Script: |- def getInstanceStates(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') tag = events['secondaryTag'] tagKey, tagValue = list(tag.items())[0] instanceQuery = ec2.describe_instances( Filters=[ { "Name": "tag:" + tagKey, "Values": [tagValue] }] ) if not instanceQuery['Reservations']: noInstancesForTagString = "No instances found for specified tag." return({ 'noInstancesFound' : noInstancesForTagString }) else: queryResponse = instanceQuery['Reservations'] originalInstanceStates = {} for results in queryResponse: instanceSet = results['Instances'] for instance in instanceSet: instanceId = instance['InstanceId'] originalInstanceStates[instanceId] = instance['State'] ['Name'] return originalInstanceStates outputs: - Name: originalInstanceStates Automation 1354 AWS Systems Manager User Guide Selector: $.Payload Type: StringMap nextStep: verifySecondaryInstancesRunning - name: verifySecondaryInstancesRunning action: 'aws:executeScript' timeoutSeconds: 600 onFailure: Abort inputs: Runtime: python3.7 Handler: verifyInstancesRunning InputPayload: targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}' Script: |- def verifyInstancesRunning(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: if instanceDict[instance] == 'stopped': print("The target instance " + instance + " is stopped. The instance will now be started.") ec2.start_instances( InstanceIds=[instance] ) elif instanceDict[instance] == 'stopping': print("The target instance " + instance + " is stopping. Polling for instance to reach stopped state.") while instanceDict[instance] != 'stopped': poll = ec2.get_waiter('instance_stopped') poll.wait( InstanceIds=[instance] ) ec2.start_instances( InstanceIds=[instance] ) else: pass nextStep: waitForSecondaryRunningInstances - name: waitForSecondaryRunningInstances action: 'aws:executeScript' timeoutSeconds: 300 onFailure: Abort Automation
systems-manager-ug-403
systems-manager-ug.pdf
403
600 onFailure: Abort inputs: Runtime: python3.7 Handler: verifyInstancesRunning InputPayload: targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}' Script: |- def verifyInstancesRunning(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: if instanceDict[instance] == 'stopped': print("The target instance " + instance + " is stopped. The instance will now be started.") ec2.start_instances( InstanceIds=[instance] ) elif instanceDict[instance] == 'stopping': print("The target instance " + instance + " is stopping. Polling for instance to reach stopped state.") while instanceDict[instance] != 'stopped': poll = ec2.get_waiter('instance_stopped') poll.wait( InstanceIds=[instance] ) ec2.start_instances( InstanceIds=[instance] ) else: pass nextStep: waitForSecondaryRunningInstances - name: waitForSecondaryRunningInstances action: 'aws:executeScript' timeoutSeconds: 300 onFailure: Abort Automation 1355 AWS Systems Manager inputs: Runtime: python3.7 Handler: waitForRunningInstances InputPayload: User Guide targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}' Script: |- def waitForRunningInstances(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: poll = ec2.get_waiter('instance_running') poll.wait( InstanceIds=[instance] ) nextStep: returnSecondaryTagKey - name: returnSecondaryTagKey action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort inputs: Runtime: python3.7 Handler: returnTagValues InputPayload: secondaryTag: '{{SecondaryPatchGroupTag}}' Script: |- def returnTagValues(events,context): tag = events['secondaryTag'] tagKey = list(tag)[0] stringKey = "tag:" + tagKey return {'tagKey' : stringKey} outputs: - Name: Payload Selector: $.Payload Type: StringMap - Name: secondaryPatchGroupKey Selector: $.Payload.tagKey Type: String nextStep: returnSecondaryTagValue - name: returnSecondaryTagValue action: 'aws:executeScript' timeoutSeconds: 120 Automation 1356 AWS Systems Manager User Guide onFailure: Abort inputs: Runtime: python3.7 Handler: returnTagValues InputPayload: secondaryTag: '{{SecondaryPatchGroupTag}}' Script: |- def returnTagValues(events,context): tag = events['secondaryTag'] tagKey = list(tag)[0] tagValue = tag[tagKey] return {'tagValue' : tagValue} outputs: - Name: Payload Selector: $.Payload Type: StringMap - Name: secondaryPatchGroupValue Selector: $.Payload.tagValue Type: String nextStep: patchSecondaryInstances - name: patchSecondaryInstances action: 'aws:runCommand' onFailure: Abort timeoutSeconds: 7200 inputs: DocumentName: AWS-RunPatchBaseline Parameters: SnapshotId: '{{SnapshotId}}' RebootOption: '{{RebootOption}}' Operation: '{{Operation}}' Targets: - Key: '{{returnSecondaryTagKey.secondaryPatchGroupKey}}' Values: - '{{returnSecondaryTagValue.secondaryPatchGroupValue}}' MaxConcurrency: 10% MaxErrors: 10% nextStep: returnSecondaryToOriginalState - name: returnSecondaryToOriginalState action: 'aws:executeScript' timeoutSeconds: 600 onFailure: Abort inputs: Runtime: python3.7 Handler: returnToOriginalState Automation 1357 AWS Systems Manager InputPayload: User Guide targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}' Script: |- def returnToOriginalState(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: if instanceDict[instance] == 'stopped' or instanceDict[instance] == 'stopping': ec2.stop_instances( InstanceIds=[instance] ) else: pass JSON { "name":"getSecondaryInstanceState", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"getInstanceStates", "InputPayload":{ "secondaryTag":"{{SecondaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"originalInstanceStates", "Selector":"$.Payload", "Type":"StringMap" } ], "nextStep":"verifySecondaryInstancesRunning" }, { Automation 1358 AWS Systems Manager User Guide "name":"verifySecondaryInstancesRunning", "action":"aws:executeScript", "timeoutSeconds":600, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"verifyInstancesRunning", "InputPayload":{ "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}" }, "Script":"..." }, "nextStep":"waitForSecondaryRunningInstances" }, { "name":"waitForSecondaryRunningInstances", "action":"aws:executeScript", "timeoutSeconds":300, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"waitForRunningInstances", "InputPayload":{ "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}" }, "Script":"..." }, "nextStep":"returnSecondaryTagKey" }, { "name":"returnSecondaryTagKey", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnTagValues", "InputPayload":{ "secondaryTag":"{{SecondaryPatchGroupTag}}" }, "Script":"..." }, Automation 1359 AWS Systems Manager User Guide "outputs":[ { "Name":"Payload", "Selector":"$.Payload", "Type":"StringMap" }, { "Name":"secondaryPatchGroupKey", "Selector":"$.Payload.tagKey", "Type":"String" } ], "nextStep":"returnSecondaryTagValue" }, { "name":"returnSecondaryTagValue", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnTagValues", "InputPayload":{ "secondaryTag":"{{SecondaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"Payload", "Selector":"$.Payload", "Type":"StringMap" }, { "Name":"secondaryPatchGroupValue", "Selector":"$.Payload.tagValue", "Type":"String" } ], "nextStep":"patchSecondaryInstances" }, { "name":"patchSecondaryInstances", "action":"aws:runCommand", Automation 1360 AWS Systems Manager User Guide "onFailure":"Abort", "timeoutSeconds":7200, "inputs":{ "DocumentName":"AWS-RunPatchBaseline", "Parameters":{ "SnapshotId":"{{SnapshotId}}", "RebootOption":"{{RebootOption}}", "Operation":"{{Operation}}" }, "Targets":[ { "Key":"{{returnSecondaryTagKey.secondaryPatchGroupKey}}", "Values":[ "{{returnSecondaryTagValue.secondaryPatchGroupValue}}" ] } ], "MaxConcurrency":"10%", "MaxErrors":"10%" }, "nextStep":"returnSecondaryToOriginalState" }, { "name":"returnSecondaryToOriginalState", "action":"aws:executeScript", "timeoutSeconds":600, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnToOriginalState", "InputPayload":{ "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}" }, "Script":"..." } } ] } 8. Emily reviews the completed scripted runbook content and creates the runbook in the same AWS account and AWS Region as the target instances. Now she's ready to test her runbook Automation 1361 AWS Systems Manager User Guide to make sure the automation operates as desired before implementing it into her production environment. The following is the completed scripted runbook content. YAML description: An example of an Automation runbook that patches groups of Amazon EC2 instances in stages. schemaVersion: '0.3' assumeRole: '{{AutomationAssumeRole}}' parameters: AutomationAssumeRole: type: String description: '(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.' PrimaryPatchGroupTag: type: StringMap description: '(Required) The tag for the primary group of instances you want to patch. Specify a key-value pair. Example: {"key" : "value"}' SecondaryPatchGroupTag: type: StringMap description: '(Required) The tag for the secondary group of instances you want to patch. Specify a key-value pair. Example: {"key" : "value"}' SnapshotId: type: String description: '(Optional) The snapshot ID to use to retrieve a patch baseline snapshot.' default: '' RebootOption: type: String description: '(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non- compliant until a subsequent reboot and scan.' allowedValues: - NoReboot - RebootIfNeeded default: RebootIfNeeded Operation: type: String description: '(Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.' allowedValues: Automation 1362 AWS Systems Manager User Guide - Install - Scan default: Install mainSteps: - name: getPrimaryInstanceState action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort
systems-manager-ug-404
systems-manager-ug.pdf
404
String description: '(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non- compliant until a subsequent reboot and scan.' allowedValues: - NoReboot - RebootIfNeeded default: RebootIfNeeded Operation: type: String description: '(Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.' allowedValues: Automation 1362 AWS Systems Manager User Guide - Install - Scan default: Install mainSteps: - name: getPrimaryInstanceState action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort inputs: Runtime: python3.7 Handler: getInstanceStates InputPayload: primaryTag: '{{PrimaryPatchGroupTag}}' Script: |- def getInstanceStates(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') tag = events['primaryTag'] tagKey, tagValue = list(tag.items())[0] instanceQuery = ec2.describe_instances( Filters=[ { "Name": "tag:" + tagKey, "Values": [tagValue] }] ) if not instanceQuery['Reservations']: noInstancesForTagString = "No instances found for specified tag." return({ 'noInstancesFound' : noInstancesForTagString }) else: queryResponse = instanceQuery['Reservations'] originalInstanceStates = {} for results in queryResponse: instanceSet = results['Instances'] for instance in instanceSet: instanceId = instance['InstanceId'] originalInstanceStates[instanceId] = instance['State'] ['Name'] return originalInstanceStates outputs: - Name: originalInstanceStates Selector: $.Payload Automation 1363 AWS Systems Manager User Guide Type: StringMap nextStep: verifyPrimaryInstancesRunning - name: verifyPrimaryInstancesRunning action: 'aws:executeScript' timeoutSeconds: 600 onFailure: Abort inputs: Runtime: python3.7 Handler: verifyInstancesRunning InputPayload: targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}' Script: |- def verifyInstancesRunning(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: if instanceDict[instance] == 'stopped': print("The target instance " + instance + " is stopped. The instance will now be started.") ec2.start_instances( InstanceIds=[instance] ) elif instanceDict[instance] == 'stopping': print("The target instance " + instance + " is stopping. Polling for instance to reach stopped state.") while instanceDict[instance] != 'stopped': poll = ec2.get_waiter('instance_stopped') poll.wait( InstanceIds=[instance] ) ec2.start_instances( InstanceIds=[instance] ) else: pass nextStep: waitForPrimaryRunningInstances - name: waitForPrimaryRunningInstances action: 'aws:executeScript' timeoutSeconds: 300 onFailure: Abort inputs: Automation 1364 AWS Systems Manager User Guide Runtime: python3.7 Handler: waitForRunningInstances InputPayload: targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}' Script: |- def waitForRunningInstances(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: poll = ec2.get_waiter('instance_running') poll.wait( InstanceIds=[instance] ) nextStep: returnPrimaryTagKey - name: returnPrimaryTagKey action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort inputs: Runtime: python3.7 Handler: returnTagValues InputPayload: primaryTag: '{{PrimaryPatchGroupTag}}' Script: |- def returnTagValues(events,context): tag = events['primaryTag'] tagKey = list(tag)[0] stringKey = "tag:" + tagKey return {'tagKey' : stringKey} outputs: - Name: Payload Selector: $.Payload Type: StringMap - Name: primaryPatchGroupKey Selector: $.Payload.tagKey Type: String nextStep: returnPrimaryTagValue - name: returnPrimaryTagValue action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort Automation 1365 AWS Systems Manager User Guide inputs: Runtime: python3.7 Handler: returnTagValues InputPayload: primaryTag: '{{PrimaryPatchGroupTag}}' Script: |- def returnTagValues(events,context): tag = events['primaryTag'] tagKey = list(tag)[0] tagValue = tag[tagKey] return {'tagValue' : tagValue} outputs: - Name: Payload Selector: $.Payload Type: StringMap - Name: primaryPatchGroupValue Selector: $.Payload.tagValue Type: String nextStep: patchPrimaryInstances - name: patchPrimaryInstances action: 'aws:runCommand' onFailure: Abort timeoutSeconds: 7200 inputs: DocumentName: AWS-RunPatchBaseline Parameters: SnapshotId: '{{SnapshotId}}' RebootOption: '{{RebootOption}}' Operation: '{{Operation}}' Targets: - Key: '{{returnPrimaryTagKey.primaryPatchGroupKey}}' Values: - '{{returnPrimaryTagValue.primaryPatchGroupValue}}' MaxConcurrency: 10% MaxErrors: 10% nextStep: returnPrimaryToOriginalState - name: returnPrimaryToOriginalState action: 'aws:executeScript' timeoutSeconds: 600 onFailure: Abort inputs: Runtime: python3.7 Handler: returnToOriginalState InputPayload: Automation 1366 AWS Systems Manager User Guide targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}' Script: |- def returnToOriginalState(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: if instanceDict[instance] == 'stopped' or instanceDict[instance] == 'stopping': ec2.stop_instances( InstanceIds=[instance] ) else: pass nextStep: getSecondaryInstanceState - name: getSecondaryInstanceState action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort inputs: Runtime: python3.7 Handler: getInstanceStates InputPayload: secondaryTag: '{{SecondaryPatchGroupTag}}' Script: |- def getInstanceStates(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') tag = events['secondaryTag'] tagKey, tagValue = list(tag.items())[0] instanceQuery = ec2.describe_instances( Filters=[ { "Name": "tag:" + tagKey, "Values": [tagValue] }] ) if not instanceQuery['Reservations']: noInstancesForTagString = "No instances found for specified tag." return({ 'noInstancesFound' : noInstancesForTagString }) Automation 1367 AWS Systems Manager else: User Guide queryResponse = instanceQuery['Reservations'] originalInstanceStates = {} for results in queryResponse: instanceSet = results['Instances'] for instance in instanceSet: instanceId = instance['InstanceId'] originalInstanceStates[instanceId] = instance['State'] ['Name'] return originalInstanceStates outputs: - Name: originalInstanceStates Selector: $.Payload Type: StringMap nextStep: verifySecondaryInstancesRunning - name: verifySecondaryInstancesRunning action: 'aws:executeScript' timeoutSeconds: 600 onFailure: Abort inputs: Runtime: python3.7 Handler: verifyInstancesRunning InputPayload: targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}' Script: |- def verifyInstancesRunning(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: if instanceDict[instance] == 'stopped': print("The target instance " + instance + " is stopped. The instance will now be started.") ec2.start_instances( InstanceIds=[instance] ) elif instanceDict[instance] == 'stopping': print("The target instance " + instance + " is stopping. Polling for instance to reach stopped state.") while instanceDict[instance] != 'stopped': poll = ec2.get_waiter('instance_stopped') poll.wait( Automation 1368 AWS Systems Manager User Guide InstanceIds=[instance] ) ec2.start_instances( InstanceIds=[instance] ) else: pass nextStep: waitForSecondaryRunningInstances - name: waitForSecondaryRunningInstances action: 'aws:executeScript' timeoutSeconds: 300 onFailure: Abort inputs: Runtime: python3.7 Handler: waitForRunningInstances InputPayload: targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}' Script: |- def waitForRunningInstances(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: poll = ec2.get_waiter('instance_running') poll.wait( InstanceIds=[instance] ) nextStep: returnSecondaryTagKey -
systems-manager-ug-405
systems-manager-ug.pdf
405
is stopped. The instance will now be started.") ec2.start_instances( InstanceIds=[instance] ) elif instanceDict[instance] == 'stopping': print("The target instance " + instance + " is stopping. Polling for instance to reach stopped state.") while instanceDict[instance] != 'stopped': poll = ec2.get_waiter('instance_stopped') poll.wait( Automation 1368 AWS Systems Manager User Guide InstanceIds=[instance] ) ec2.start_instances( InstanceIds=[instance] ) else: pass nextStep: waitForSecondaryRunningInstances - name: waitForSecondaryRunningInstances action: 'aws:executeScript' timeoutSeconds: 300 onFailure: Abort inputs: Runtime: python3.7 Handler: waitForRunningInstances InputPayload: targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}' Script: |- def waitForRunningInstances(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: poll = ec2.get_waiter('instance_running') poll.wait( InstanceIds=[instance] ) nextStep: returnSecondaryTagKey - name: returnSecondaryTagKey action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort inputs: Runtime: python3.7 Handler: returnTagValues InputPayload: secondaryTag: '{{SecondaryPatchGroupTag}}' Script: |- def returnTagValues(events,context): tag = events['secondaryTag'] tagKey = list(tag)[0] stringKey = "tag:" + tagKey Automation 1369 AWS Systems Manager User Guide return {'tagKey' : stringKey} outputs: - Name: Payload Selector: $.Payload Type: StringMap - Name: secondaryPatchGroupKey Selector: $.Payload.tagKey Type: String nextStep: returnSecondaryTagValue - name: returnSecondaryTagValue action: 'aws:executeScript' timeoutSeconds: 120 onFailure: Abort inputs: Runtime: python3.7 Handler: returnTagValues InputPayload: secondaryTag: '{{SecondaryPatchGroupTag}}' Script: |- def returnTagValues(events,context): tag = events['secondaryTag'] tagKey = list(tag)[0] tagValue = tag[tagKey] return {'tagValue' : tagValue} outputs: - Name: Payload Selector: $.Payload Type: StringMap - Name: secondaryPatchGroupValue Selector: $.Payload.tagValue Type: String nextStep: patchSecondaryInstances - name: patchSecondaryInstances action: 'aws:runCommand' onFailure: Abort timeoutSeconds: 7200 inputs: DocumentName: AWS-RunPatchBaseline Parameters: SnapshotId: '{{SnapshotId}}' RebootOption: '{{RebootOption}}' Operation: '{{Operation}}' Targets: - Key: '{{returnSecondaryTagKey.secondaryPatchGroupKey}}' Automation 1370 AWS Systems Manager Values: User Guide - '{{returnSecondaryTagValue.secondaryPatchGroupValue}}' MaxConcurrency: 10% MaxErrors: 10% nextStep: returnSecondaryToOriginalState - name: returnSecondaryToOriginalState action: 'aws:executeScript' timeoutSeconds: 600 onFailure: Abort inputs: Runtime: python3.7 Handler: returnToOriginalState InputPayload: targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}' Script: |- def returnToOriginalState(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceDict = events['targetInstances'] for instance in instanceDict: if instanceDict[instance] == 'stopped' or instanceDict[instance] == 'stopping': ec2.stop_instances( InstanceIds=[instance] ) else: pass JSON { "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.", "schemaVersion":"0.3", "assumeRole":"{{AutomationAssumeRole}}", "parameters":{ "AutomationAssumeRole":{ "type":"String", "description":"(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is Automation 1371 AWS Systems Manager User Guide specified, Systems Manager Automation uses your IAM permissions to operate this runbook." }, "PrimaryPatchGroupTag":{ "type":"StringMap", "description":"(Required) The tag for the primary group of instances you want to patch. Specify a key-value pair. Example: {\"key\" : \"value\"}" }, "SecondaryPatchGroupTag":{ "type":"StringMap", "description":"(Required) The tag for the secondary group of instances you want to patch. Specify a key-value pair. Example: {\"key\" : \"value\"}" }, "SnapshotId":{ "type":"String", "description":"(Optional) The snapshot ID to use to retrieve a patch baseline snapshot.", "default":"" }, "RebootOption":{ "type":"String", "description":"(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non-compliant until a subsequent reboot and scan.", "allowedValues":[ "NoReboot", "RebootIfNeeded" ], "default":"RebootIfNeeded" }, "Operation":{ "type":"String", "description":"(Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.", "allowedValues":[ "Install", "Scan" ], "default":"Install" } }, "mainSteps":[ Automation 1372 AWS Systems Manager { User Guide "name":"getPrimaryInstanceState", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"getInstanceStates", "InputPayload":{ "primaryTag":"{{PrimaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"originalInstanceStates", "Selector":"$.Payload", "Type":"StringMap" } ], "nextStep":"verifyPrimaryInstancesRunning" }, { "name":"verifyPrimaryInstancesRunning", "action":"aws:executeScript", "timeoutSeconds":600, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"verifyInstancesRunning", "InputPayload":{ "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}" }, "Script":"..." }, "nextStep":"waitForPrimaryRunningInstances" }, { "name":"waitForPrimaryRunningInstances", "action":"aws:executeScript", "timeoutSeconds":300, "onFailure":"Abort", "inputs":{ Automation 1373 AWS Systems Manager User Guide "Runtime":"python3.7", "Handler":"waitForRunningInstances", "InputPayload":{ "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}" }, "Script":"..." }, "nextStep":"returnPrimaryTagKey" }, { "name":"returnPrimaryTagKey", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnTagValues", "InputPayload":{ "primaryTag":"{{PrimaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"Payload", "Selector":"$.Payload", "Type":"StringMap" }, { "Name":"primaryPatchGroupKey", "Selector":"$.Payload.tagKey", "Type":"String" } ], "nextStep":"returnPrimaryTagValue" }, { "name":"returnPrimaryTagValue", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", Automation 1374 AWS Systems Manager User Guide "Handler":"returnTagValues", "InputPayload":{ "primaryTag":"{{PrimaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"Payload", "Selector":"$.Payload", "Type":"StringMap" }, { "Name":"primaryPatchGroupValue", "Selector":"$.Payload.tagValue", "Type":"String" } ], "nextStep":"patchPrimaryInstances" }, { "name":"patchPrimaryInstances", "action":"aws:runCommand", "onFailure":"Abort", "timeoutSeconds":7200, "inputs":{ "DocumentName":"AWS-RunPatchBaseline", "Parameters":{ "SnapshotId":"{{SnapshotId}}", "RebootOption":"{{RebootOption}}", "Operation":"{{Operation}}" }, "Targets":[ { "Key":"{{returnPrimaryTagKey.primaryPatchGroupKey}}", "Values":[ "{{returnPrimaryTagValue.primaryPatchGroupValue}}" ] } ], "MaxConcurrency":"10%", "MaxErrors":"10%" }, "nextStep":"returnPrimaryToOriginalState" Automation 1375 AWS Systems Manager }, User Guide { "name":"returnPrimaryToOriginalState", "action":"aws:executeScript", "timeoutSeconds":600, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnToOriginalState", "InputPayload":{ "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}" }, "Script":"..." }, "nextStep":"getSecondaryInstanceState" }, { "name":"getSecondaryInstanceState", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"getInstanceStates", "InputPayload":{ "secondaryTag":"{{SecondaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"originalInstanceStates", "Selector":"$.Payload", "Type":"StringMap" } ], "nextStep":"verifySecondaryInstancesRunning" }, { "name":"verifySecondaryInstancesRunning", "action":"aws:executeScript", "timeoutSeconds":600, "onFailure":"Abort", Automation 1376 AWS Systems Manager "inputs":{ "Runtime":"python3.7", "Handler":"verifyInstancesRunning", "InputPayload":{ User Guide "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}" }, "Script":"..." }, "nextStep":"waitForSecondaryRunningInstances" }, { "name":"waitForSecondaryRunningInstances", "action":"aws:executeScript", "timeoutSeconds":300, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"waitForRunningInstances", "InputPayload":{ "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}" }, "Script":"..." }, "nextStep":"returnSecondaryTagKey" }, { "name":"returnSecondaryTagKey", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnTagValues", "InputPayload":{ "secondaryTag":"{{SecondaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"Payload", "Selector":"$.Payload", Automation 1377 AWS Systems Manager User Guide "Type":"StringMap" }, { "Name":"secondaryPatchGroupKey", "Selector":"$.Payload.tagKey", "Type":"String" } ], "nextStep":"returnSecondaryTagValue" }, { "name":"returnSecondaryTagValue", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnTagValues", "InputPayload":{ "secondaryTag":"{{SecondaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"Payload", "Selector":"$.Payload", "Type":"StringMap" }, { "Name":"secondaryPatchGroupValue", "Selector":"$.Payload.tagValue", "Type":"String" } ], "nextStep":"patchSecondaryInstances"
systems-manager-ug-406
systems-manager-ug.pdf
406
], "nextStep":"verifySecondaryInstancesRunning" }, { "name":"verifySecondaryInstancesRunning", "action":"aws:executeScript", "timeoutSeconds":600, "onFailure":"Abort", Automation 1376 AWS Systems Manager "inputs":{ "Runtime":"python3.7", "Handler":"verifyInstancesRunning", "InputPayload":{ User Guide "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}" }, "Script":"..." }, "nextStep":"waitForSecondaryRunningInstances" }, { "name":"waitForSecondaryRunningInstances", "action":"aws:executeScript", "timeoutSeconds":300, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"waitForRunningInstances", "InputPayload":{ "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}" }, "Script":"..." }, "nextStep":"returnSecondaryTagKey" }, { "name":"returnSecondaryTagKey", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnTagValues", "InputPayload":{ "secondaryTag":"{{SecondaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"Payload", "Selector":"$.Payload", Automation 1377 AWS Systems Manager User Guide "Type":"StringMap" }, { "Name":"secondaryPatchGroupKey", "Selector":"$.Payload.tagKey", "Type":"String" } ], "nextStep":"returnSecondaryTagValue" }, { "name":"returnSecondaryTagValue", "action":"aws:executeScript", "timeoutSeconds":120, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnTagValues", "InputPayload":{ "secondaryTag":"{{SecondaryPatchGroupTag}}" }, "Script":"..." }, "outputs":[ { "Name":"Payload", "Selector":"$.Payload", "Type":"StringMap" }, { "Name":"secondaryPatchGroupValue", "Selector":"$.Payload.tagValue", "Type":"String" } ], "nextStep":"patchSecondaryInstances" }, { "name":"patchSecondaryInstances", "action":"aws:runCommand", "onFailure":"Abort", "timeoutSeconds":7200, "inputs":{ "DocumentName":"AWS-RunPatchBaseline", Automation 1378 AWS Systems Manager User Guide "Parameters":{ "SnapshotId":"{{SnapshotId}}", "RebootOption":"{{RebootOption}}", "Operation":"{{Operation}}" }, "Targets":[ { "Key":"{{returnSecondaryTagKey.secondaryPatchGroupKey}}", "Values":[ "{{returnSecondaryTagValue.secondaryPatchGroupValue}}" ] } ], "MaxConcurrency":"10%", "MaxErrors":"10%" }, "nextStep":"returnSecondaryToOriginalState" }, { "name":"returnSecondaryToOriginalState", "action":"aws:executeScript", "timeoutSeconds":600, "onFailure":"Abort", "inputs":{ "Runtime":"python3.7", "Handler":"returnToOriginalState", "InputPayload":{ "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}" }, "Script":"..." } } ] } For more information about the automation actions used in this example, see the Systems Manager Automation actions reference. Automation 1379 AWS Systems Manager Additional runbook examples User Guide The following example runbook demonstrate how you can use AWS Systems Manager automation actions to automate common deployment, troubleshooting, and maintenance tasks. Note The example runbooks in this section are provided to demonstrate how you can create custom runbooks to support your specific operational needs. These runbooks aren't meant for use in production environments as is. However, you can customize them for your own use. Examples • Deploy VPC architecture and Microsoft Active Directory domain controllers • Restore a root volume from the latest snapshot • Create an AMI and cross-Region copy Deploy VPC architecture and Microsoft Active Directory domain controllers To increase efficiency and standardize common tasks, you might choose to automate deployments. This is useful if you regularly deploy the same architecture across multiple accounts and AWS Regions. Automating architecture deployments can also reduce the potential for human error that can occur when deploying architecture manually. AWS Systems Manager Automation actions can help you accomplish this. Automation is a tool in AWS Systems Manager. The following example AWS Systems Manager runbook performs these actions: • Retrieves the latest Windows Server 2016 Amazon Machine Image (AMI) using Systems Manager Parameter Store to use when launching the EC2 instances that will be configured as domain controllers. Parameter Store is a tool in AWS Systems Manager. • Uses the aws:executeAwsApi automation action to call several AWS API operations to create the VPC architecture. The domain controller instances are launched in private subnets, and connect to the internet using a NAT gateway. This allows the SSM Agent on the instances to access the requisite Systems Manager endpoints. • Uses the aws:waitForAwsResourceProperty automation action to confirm the instances launched by the previous action are Online for AWS Systems Manager. Automation 1380 AWS Systems Manager User Guide • Uses the aws:runCommand automation action to configure the instances launched as Microsoft Active Directory domain controllers. YAML --- description: Custom Automation Deployment Example schemaVersion: '0.3' parameters: AutomationAssumeRole: type: String default: '' description: >- (Optional) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to run this runbook. mainSteps: - name: getLatestWindowsAmi action: aws:executeAwsApi onFailure: Abort inputs: Service: ssm Api: GetParameter Name: >- /aws/service/ami-windows-latest/Windows_Server-2016-English-Full-Base outputs: - Name: amiId Selector: $.Parameter.Value Type: String nextStep: createSSMInstanceRole - name: createSSMInstanceRole action: aws:executeAwsApi onFailure: Abort inputs: Service: iam Api: CreateRole AssumeRolePolicyDocument: >- {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal": {"Service":["ec2.amazonaws.com"]},"Action":["sts:AssumeRole"]}]} RoleName: sampleSSMInstanceRole nextStep: attachManagedSSMPolicy - name: attachManagedSSMPolicy Automation 1381 AWS Systems Manager User Guide action: aws:executeAwsApi onFailure: Abort inputs: Service: iam Api: AttachRolePolicy PolicyArn: 'arn:aws:iam::aws:policy/service-role/ AmazonSSMManagedInstanceCore' RoleName: sampleSSMInstanceRole nextStep: createSSMInstanceProfile - name: createSSMInstanceProfile action: aws:executeAwsApi onFailure: Abort inputs: Service: iam Api: CreateInstanceProfile InstanceProfileName: sampleSSMInstanceRole outputs: - Name: instanceProfileArn Selector: $.InstanceProfile.Arn Type: String nextStep: addSSMInstanceRoleToProfile - name: addSSMInstanceRoleToProfile action: aws:executeAwsApi onFailure: Abort inputs: Service: iam Api: AddRoleToInstanceProfile InstanceProfileName: sampleSSMInstanceRole RoleName: sampleSSMInstanceRole nextStep: createVpc - name: createVpc action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateVpc CidrBlock: 10.0.100.0/22 outputs: - Name: vpcId Selector: $.Vpc.VpcId Type: String nextStep: getMainRtb - name: getMainRtb action: aws:executeAwsApi Automation 1382 AWS Systems Manager User Guide onFailure: Abort inputs: Service: ec2 Api: DescribeRouteTables Filters: - Name: vpc-id Values: - '{{ createVpc.vpcId }}' outputs: - Name: mainRtbId Selector: '$.RouteTables[0].RouteTableId' Type: String nextStep: verifyMainRtb - name: verifyMainRtb action: aws:assertAwsResourceProperty onFailure: Abort inputs: Service: ec2 Api: DescribeRouteTables RouteTableIds: - '{{ getMainRtb.mainRtbId }}' PropertySelector: '$.RouteTables[0].Associations[0].Main' DesiredValues: - 'True' nextStep: createPubSubnet - name: createPubSubnet action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateSubnet CidrBlock: 10.0.103.0/24 AvailabilityZone: us-west-2c VpcId: '{{ createVpc.vpcId }}' outputs: - Name: pubSubnetId Selector: $.Subnet.SubnetId Type: String nextStep: createPubRtb - name: createPubRtb action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Automation 1383 AWS Systems Manager User Guide Api: CreateRouteTable VpcId: '{{ createVpc.vpcId }}' outputs: - Name: pubRtbId Selector: $.RouteTable.RouteTableId Type: String nextStep: createIgw -
systems-manager-ug-407
systems-manager-ug.pdf
407
createVpc.vpcId }}' outputs: - Name: mainRtbId Selector: '$.RouteTables[0].RouteTableId' Type: String nextStep: verifyMainRtb - name: verifyMainRtb action: aws:assertAwsResourceProperty onFailure: Abort inputs: Service: ec2 Api: DescribeRouteTables RouteTableIds: - '{{ getMainRtb.mainRtbId }}' PropertySelector: '$.RouteTables[0].Associations[0].Main' DesiredValues: - 'True' nextStep: createPubSubnet - name: createPubSubnet action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateSubnet CidrBlock: 10.0.103.0/24 AvailabilityZone: us-west-2c VpcId: '{{ createVpc.vpcId }}' outputs: - Name: pubSubnetId Selector: $.Subnet.SubnetId Type: String nextStep: createPubRtb - name: createPubRtb action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Automation 1383 AWS Systems Manager User Guide Api: CreateRouteTable VpcId: '{{ createVpc.vpcId }}' outputs: - Name: pubRtbId Selector: $.RouteTable.RouteTableId Type: String nextStep: createIgw - name: createIgw action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateInternetGateway outputs: - Name: igwId Selector: $.InternetGateway.InternetGatewayId Type: String nextStep: attachIgw - name: attachIgw action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: AttachInternetGateway InternetGatewayId: '{{ createIgw.igwId }}' VpcId: '{{ createVpc.vpcId }}' nextStep: allocateEip - name: allocateEip action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: AllocateAddress Domain: vpc outputs: - Name: eipAllocationId Selector: $.AllocationId Type: String nextStep: createNatGw - name: createNatGw action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Automation 1384 AWS Systems Manager User Guide Api: CreateNatGateway AllocationId: '{{ allocateEip.eipAllocationId }}' SubnetId: '{{ createPubSubnet.pubSubnetId }}' outputs: - Name: natGwId Selector: $.NatGateway.NatGatewayId Type: String nextStep: verifyNatGwAvailable - name: verifyNatGwAvailable action: aws:waitForAwsResourceProperty timeoutSeconds: 150 inputs: Service: ec2 Api: DescribeNatGateways NatGatewayIds: - '{{ createNatGw.natGwId }}' PropertySelector: '$.NatGateways[0].State' DesiredValues: - available nextStep: createNatRoute - name: createNatRoute action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateRoute DestinationCidrBlock: 0.0.0.0/0 NatGatewayId: '{{ createNatGw.natGwId }}' RouteTableId: '{{ getMainRtb.mainRtbId }}' nextStep: createPubRoute - name: createPubRoute action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateRoute DestinationCidrBlock: 0.0.0.0/0 GatewayId: '{{ createIgw.igwId }}' RouteTableId: '{{ createPubRtb.pubRtbId }}' nextStep: setPubSubAssoc - name: setPubSubAssoc action: aws:executeAwsApi onFailure: Abort inputs: Automation 1385 AWS Systems Manager Service: ec2 Api: AssociateRouteTable RouteTableId: '{{ createPubRtb.pubRtbId }}' SubnetId: '{{ createPubSubnet.pubSubnetId }}' User Guide - name: createDhcpOptions action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateDhcpOptions DhcpConfigurations: - Key: domain-name-servers Values: - '10.0.100.50,10.0.101.50' - Key: domain-name Values: - sample.com outputs: - Name: dhcpOptionsId Selector: $.DhcpOptions.DhcpOptionsId Type: String nextStep: createDCSubnet1 - name: createDCSubnet1 action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateSubnet CidrBlock: 10.0.100.0/24 AvailabilityZone: us-west-2a VpcId: '{{ createVpc.vpcId }}' outputs: - Name: firstSubnetId Selector: $.Subnet.SubnetId Type: String nextStep: createDCSubnet2 - name: createDCSubnet2 action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateSubnet CidrBlock: 10.0.101.0/24 AvailabilityZone: us-west-2b Automation 1386 AWS Systems Manager User Guide VpcId: '{{ createVpc.vpcId }}' outputs: - Name: secondSubnetId Selector: $.Subnet.SubnetId Type: String nextStep: createDCSecGroup - name: createDCSecGroup action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateSecurityGroup GroupName: SampleDCSecGroup Description: Security Group for Sample Domain Controllers VpcId: '{{ createVpc.vpcId }}' outputs: - Name: dcSecGroupId Selector: $.GroupId Type: String nextStep: authIngressDCTraffic - name: authIngressDCTraffic action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: AuthorizeSecurityGroupIngress GroupId: '{{ createDCSecGroup.dcSecGroupId }}' IpPermissions: - FromPort: -1 IpProtocol: '-1' IpRanges: - CidrIp: 0.0.0.0/0 Description: Allow all traffic between Domain Controllers nextStep: verifyInstanceProfile - name: verifyInstanceProfile action: aws:waitForAwsResourceProperty maxAttempts: 5 onFailure: Abort inputs: Service: iam Api: ListInstanceProfilesForRole RoleName: sampleSSMInstanceRole PropertySelector: '$.InstanceProfiles[0].Arn' DesiredValues: Automation 1387 AWS Systems Manager User Guide - '{{ createSSMInstanceProfile.instanceProfileArn }}' nextStep: iamEventualConsistency - name: iamEventualConsistency action: aws:sleep inputs: Duration: PT2M nextStep: launchDC1 - name: launchDC1 action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: RunInstances BlockDeviceMappings: - DeviceName: /dev/sda1 Ebs: DeleteOnTermination: true VolumeSize: 50 VolumeType: gp2 - DeviceName: xvdf Ebs: DeleteOnTermination: true VolumeSize: 100 VolumeType: gp2 IamInstanceProfile: Arn: '{{ createSSMInstanceProfile.instanceProfileArn }}' ImageId: '{{ getLatestWindowsAmi.amiId }}' InstanceType: t2.micro MaxCount: 1 MinCount: 1 PrivateIpAddress: 10.0.100.50 SecurityGroupIds: - '{{ createDCSecGroup.dcSecGroupId }}' SubnetId: '{{ createDCSubnet1.firstSubnetId }}' TagSpecifications: - ResourceType: instance Tags: - Key: Name Value: SampleDC1 outputs: - Name: pdcInstanceId Selector: '$.Instances[0].InstanceId' Type: String nextStep: launchDC2 Automation 1388 AWS Systems Manager User Guide - name: launchDC2 action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: RunInstances BlockDeviceMappings: - DeviceName: /dev/sda1 Ebs: DeleteOnTermination: true VolumeSize: 50 VolumeType: gp2 - DeviceName: xvdf Ebs: DeleteOnTermination: true VolumeSize: 100 VolumeType: gp2 IamInstanceProfile: Arn: '{{ createSSMInstanceProfile.instanceProfileArn }}' ImageId: '{{ getLatestWindowsAmi.amiId }}' InstanceType: t2.micro MaxCount: 1 MinCount: 1 PrivateIpAddress: 10.0.101.50 SecurityGroupIds: - '{{ createDCSecGroup.dcSecGroupId }}' SubnetId: '{{ createDCSubnet2.secondSubnetId }}' TagSpecifications: - ResourceType: instance Tags: - Key: Name Value: SampleDC2 outputs: - Name: adcInstanceId Selector: '$.Instances[0].InstanceId' Type: String nextStep: verifyDCInstanceState - name: verifyDCInstanceState action: aws:waitForAwsResourceProperty inputs: Service: ec2 Api: DescribeInstanceStatus IncludeAllInstances: true InstanceIds: Automation 1389 AWS Systems Manager User Guide - '{{ launchDC1.pdcInstanceId }}' - '{{ launchDC2.adcInstanceId }}' PropertySelector: '$.InstanceStatuses..InstanceState.Name' DesiredValues: - running nextStep: verifyInstancesOnlineSSM - name: verifyInstancesOnlineSSM action: aws:waitForAwsResourceProperty timeoutSeconds: 600 inputs: Service: ssm Api: DescribeInstanceInformation InstanceInformationFilterList: - key: InstanceIds valueSet: - '{{ launchDC1.pdcInstanceId }}' - '{{ launchDC2.adcInstanceId }}' PropertySelector: '$.InstanceInformationList..PingStatus' DesiredValues: - Online nextStep: installADRoles - name: installADRoles action: aws:runCommand inputs: DocumentName: AWS-RunPowerShellScript InstanceIds: - '{{ launchDC1.pdcInstanceId }}' - '{{ launchDC2.adcInstanceId }}' Parameters: commands: |- try { Install-WindowsFeature -Name AD-Domain-Services - IncludeManagementTools } catch { Write-Error "Failed to install ADDS Role." } nextStep: setAdminPassword - name: setAdminPassword action: aws:runCommand inputs: DocumentName: AWS-RunPowerShellScript InstanceIds: - '{{ launchDC1.pdcInstanceId
systems-manager-ug-408
systems-manager-ug.pdf
408
User Guide - '{{ launchDC1.pdcInstanceId }}' - '{{ launchDC2.adcInstanceId }}' PropertySelector: '$.InstanceStatuses..InstanceState.Name' DesiredValues: - running nextStep: verifyInstancesOnlineSSM - name: verifyInstancesOnlineSSM action: aws:waitForAwsResourceProperty timeoutSeconds: 600 inputs: Service: ssm Api: DescribeInstanceInformation InstanceInformationFilterList: - key: InstanceIds valueSet: - '{{ launchDC1.pdcInstanceId }}' - '{{ launchDC2.adcInstanceId }}' PropertySelector: '$.InstanceInformationList..PingStatus' DesiredValues: - Online nextStep: installADRoles - name: installADRoles action: aws:runCommand inputs: DocumentName: AWS-RunPowerShellScript InstanceIds: - '{{ launchDC1.pdcInstanceId }}' - '{{ launchDC2.adcInstanceId }}' Parameters: commands: |- try { Install-WindowsFeature -Name AD-Domain-Services - IncludeManagementTools } catch { Write-Error "Failed to install ADDS Role." } nextStep: setAdminPassword - name: setAdminPassword action: aws:runCommand inputs: DocumentName: AWS-RunPowerShellScript InstanceIds: - '{{ launchDC1.pdcInstanceId }}' Automation 1390 AWS Systems Manager Parameters: commands: - net user Administrator "sampleAdminPass123!" User Guide nextStep: createForest - name: createForest action: aws:runCommand inputs: DocumentName: AWS-RunPowerShellScript InstanceIds: - '{{ launchDC1.pdcInstanceId }}' Parameters: commands: |- $dsrmPass = 'sample123!' | ConvertTo-SecureString -asPlainText -Force try { Install-ADDSForest -DomainName "sample.com" -DomainMode 6 -ForestMode 6 -InstallDNS -DatabasePath "D:\NTDS" -SysvolPath "D:\SYSVOL" - SafeModeAdministratorPassword $dsrmPass -Force } catch { Write-Error $_ } try { Add-DnsServerForwarder -IPAddress "10.0.100.2" } catch { Write-Error $_ } nextStep: associateDhcpOptions - name: associateDhcpOptions action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: AssociateDhcpOptions DhcpOptionsId: '{{ createDhcpOptions.dhcpOptionsId }}' VpcId: '{{ createVpc.vpcId }}' nextStep: waitForADServices - name: waitForADServices action: aws:sleep inputs: Duration: PT1M nextStep: promoteADC - name: promoteADC action: aws:runCommand Automation 1391 AWS Systems Manager inputs: DocumentName: AWS-RunPowerShellScript InstanceIds: - '{{ launchDC2.adcInstanceId }}' Parameters: commands: |- ipconfig /renew User Guide $dsrmPass = 'sample123!' | ConvertTo-SecureString -asPlainText -Force $domAdminUser = "sample\Administrator" $domAdminPass = "sampleAdminPass123!" | ConvertTo-SecureString - asPlainText -Force $domAdminCred = New-Object System.Management.Automation.PSCredential($domAdminUser,$domAdminPass) try { Install-ADDSDomainController -DomainName "sample.com" -InstallDNS -DatabasePath "D:\NTDS" -SysvolPath "D:\SYSVOL" -SafeModeAdministratorPassword $dsrmPass -Credential $domAdminCred -Force } catch { Write-Error $_ } JSON { "description": "Custom Automation Deployment Example", "schemaVersion": "0.3", "assumeRole": "{{ AutomationAssumeRole }}", "parameters": { "AutomationAssumeRole": { "type": "String", "description": "(Optional) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to run this runbook.", "default": "" } }, "mainSteps": [ { "name": "getLatestWindowsAmi", "action": "aws:executeAwsApi", Automation 1392 AWS Systems Manager User Guide "onFailure": "Abort", "inputs": { "Service": "ssm", "Api": "GetParameter", "Name": "/aws/service/ami-windows-latest/Windows_Server-2016-English- Full-Base" }, "outputs": [ { "Name": "amiId", "Selector": "$.Parameter.Value", "Type": "String" } ], "nextStep": "createSSMInstanceRole" }, { "name": "createSSMInstanceRole", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "iam", "Api": "CreateRole", "AssumeRolePolicyDocument": "{\"Version\":\"2012-10-17\",\"Statement\": [{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action \":[\"sts:AssumeRole\"]}]}", "RoleName": "sampleSSMInstanceRole" }, "nextStep": "attachManagedSSMPolicy" }, { "name": "attachManagedSSMPolicy", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "iam", "Api": "AttachRolePolicy", "PolicyArn": "arn:aws:iam::aws:policy/service-role/ AmazonSSMManagedInstanceCore", "RoleName": "sampleSSMInstanceRole" }, "nextStep": "createSSMInstanceProfile" }, { Automation 1393 AWS Systems Manager User Guide "name": "createSSMInstanceProfile", "action":"aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "iam", "Api": "CreateInstanceProfile", "InstanceProfileName": "sampleSSMInstanceRole" }, "outputs": [ { "Name": "instanceProfileArn", "Selector": "$.InstanceProfile.Arn", "Type": "String" } ], "nextStep": "addSSMInstanceRoleToProfile" }, { "name": "addSSMInstanceRoleToProfile", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "iam", "Api": "AddRoleToInstanceProfile", "InstanceProfileName": "sampleSSMInstanceRole", "RoleName": "sampleSSMInstanceRole" }, "nextStep": "createVpc" }, { "name": "createVpc", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateVpc", "CidrBlock": "10.0.100.0/22" }, "outputs": [ { "Name": "vpcId", "Selector": "$.Vpc.VpcId", "Type": "String" } Automation 1394 AWS Systems Manager User Guide "nextStep": "getMainRtb" }, { "name": "getMainRtb", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "DescribeRouteTables", "Filters": [ { "Name": "vpc-id", "Values": ["{{ createVpc.vpcId }}"] } ] }, "outputs": [ { "Name": "mainRtbId", "Selector": "$.RouteTables[0].RouteTableId", "Type": "String" } ], "nextStep": "verifyMainRtb" }, { "name": "verifyMainRtb", "action": "aws:assertAwsResourceProperty", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "DescribeRouteTables", "RouteTableIds": ["{{ getMainRtb.mainRtbId }}"], "PropertySelector": "$.RouteTables[0].Associations[0].Main", "DesiredValues": ["True"] }, "nextStep": "createPubSubnet" }, { "name": "createPubSubnet", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { Automation 1395 AWS Systems Manager User Guide "Service": "ec2", "Api": "CreateSubnet", "CidrBlock": "10.0.103.0/24", "AvailabilityZone": "us-west-2c", "VpcId": "{{ createVpc.vpcId }}" }, "outputs":[ { "Name": "pubSubnetId", "Selector": "$.Subnet.SubnetId", "Type": "String" } ], "nextStep": "createPubRtb" }, { "name": "createPubRtb", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateRouteTable", "VpcId": "{{ createVpc.vpcId }}" }, "outputs": [ { "Name": "pubRtbId", "Selector": "$.RouteTable.RouteTableId", "Type": "String" } ], "nextStep": "createIgw" }, { "name": "createIgw", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateInternetGateway" }, "outputs": [ { "Name": "igwId", Automation 1396 AWS Systems Manager User Guide "Selector": "$.InternetGateway.InternetGatewayId", "Type": "String" } ], "nextStep": "attachIgw" }, { "name": "attachIgw", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "AttachInternetGateway", "InternetGatewayId": "{{ createIgw.igwId }}", "VpcId": "{{ createVpc.vpcId }}" }, "nextStep": "allocateEip" }, { "name": "allocateEip", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "AllocateAddress", "Domain": "vpc" }, "outputs": [ { "Name": "eipAllocationId", "Selector": "$.AllocationId", "Type": "String" } ], "nextStep": "createNatGw" }, { "name": "createNatGw", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateNatGateway", "AllocationId": "{{ allocateEip.eipAllocationId }}", Automation 1397 AWS Systems Manager User Guide "SubnetId": "{{ createPubSubnet.pubSubnetId }}" }, "outputs":[ { "Name": "natGwId", "Selector": "$.NatGateway.NatGatewayId", "Type": "String" } ], "nextStep": "verifyNatGwAvailable" }, { "name": "verifyNatGwAvailable", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 150, "inputs": { "Service": "ec2", "Api": "DescribeNatGateways", "NatGatewayIds": [ "{{ createNatGw.natGwId }}" ],
systems-manager-ug-409
systems-manager-ug.pdf
409
}}", "VpcId": "{{ createVpc.vpcId }}" }, "nextStep": "allocateEip" }, { "name": "allocateEip", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "AllocateAddress", "Domain": "vpc" }, "outputs": [ { "Name": "eipAllocationId", "Selector": "$.AllocationId", "Type": "String" } ], "nextStep": "createNatGw" }, { "name": "createNatGw", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateNatGateway", "AllocationId": "{{ allocateEip.eipAllocationId }}", Automation 1397 AWS Systems Manager User Guide "SubnetId": "{{ createPubSubnet.pubSubnetId }}" }, "outputs":[ { "Name": "natGwId", "Selector": "$.NatGateway.NatGatewayId", "Type": "String" } ], "nextStep": "verifyNatGwAvailable" }, { "name": "verifyNatGwAvailable", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 150, "inputs": { "Service": "ec2", "Api": "DescribeNatGateways", "NatGatewayIds": [ "{{ createNatGw.natGwId }}" ], "PropertySelector": "$.NatGateways[0].State", "DesiredValues": [ "available" ] }, "nextStep": "createNatRoute" }, { "name": "createNatRoute", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateRoute", "DestinationCidrBlock": "0.0.0.0/0", "NatGatewayId": "{{ createNatGw.natGwId }}", "RouteTableId": "{{ getMainRtb.mainRtbId }}" }, "nextStep": "createPubRoute" }, { "name": "createPubRoute", "action": "aws:executeAwsApi", Automation 1398 AWS Systems Manager User Guide "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateRoute", "DestinationCidrBlock": "0.0.0.0/0", "GatewayId": "{{ createIgw.igwId }}", "RouteTableId": "{{ createPubRtb.pubRtbId }}" }, "nextStep": "setPubSubAssoc" }, { "name": "setPubSubAssoc", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "AssociateRouteTable", "RouteTableId": "{{ createPubRtb.pubRtbId }}", "SubnetId": "{{ createPubSubnet.pubSubnetId }}" } }, { "name": "createDhcpOptions", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateDhcpOptions", "DhcpConfigurations": [ { "Key": "domain-name-servers", "Values": ["10.0.100.50,10.0.101.50"] }, { "Key": "domain-name", "Values": ["sample.com"] } ] }, "outputs": [ { "Name": "dhcpOptionsId", "Selector": "$.DhcpOptions.DhcpOptionsId", "Type": "String" Automation 1399 AWS Systems Manager } User Guide ], "nextStep": "createDCSubnet1" }, { "name": "createDCSubnet1", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateSubnet", "CidrBlock": "10.0.100.0/24", "AvailabilityZone": "us-west-2a", "VpcId": "{{ createVpc.vpcId }}" }, "outputs": [ { "Name": "firstSubnetId", "Selector": "$.Subnet.SubnetId", "Type": "String" } ], "nextStep": "createDCSubnet2" }, { "name": "createDCSubnet2", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateSubnet", "CidrBlock": "10.0.101.0/24", "AvailabilityZone": "us-west-2b", "VpcId": "{{ createVpc.vpcId }}" }, "outputs": [ { "Name": "secondSubnetId", "Selector": "$.Subnet.SubnetId", "Type": "String" } ], "nextStep": "createDCSecGroup" }, Automation 1400 AWS Systems Manager { "name": "createDCSecGroup", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateSecurityGroup", "GroupName": "SampleDCSecGroup", "Description": "Security Group for Example Domain Controllers", "VpcId": "{{ createVpc.vpcId }}" User Guide }, "outputs": [ { "Name": "dcSecGroupId", "Selector": "$.GroupId", "Type": "String" } ], "nextStep": "authIngressDCTraffic" }, { "name": "authIngressDCTraffic", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "AuthorizeSecurityGroupIngress", "GroupId": "{{ createDCSecGroup.dcSecGroupId }}", "IpPermissions": [ { "FromPort": -1, "IpProtocol": "-1", "IpRanges": [ { "CidrIp": "0.0.0.0/0", "Description": "Allow all traffic between Domain Controllers" } ] } ] }, "nextStep": "verifyInstanceProfile" }, { Automation 1401 AWS Systems Manager User Guide "name": "verifyInstanceProfile", "action": "aws:waitForAwsResourceProperty", "maxAttempts": 5, "onFailure": "Abort", "inputs": { "Service": "iam", "Api": "ListInstanceProfilesForRole", "RoleName": "sampleSSMInstanceRole", "PropertySelector": "$.InstanceProfiles[0].Arn", "DesiredValues": [ "{{ createSSMInstanceProfile.instanceProfileArn }}" ] }, "nextStep": "iamEventualConsistency" }, { "name": "iamEventualConsistency", "action": "aws:sleep", "inputs": { "Duration": "PT2M" }, "nextStep": "launchDC1" }, { "name": "launchDC1", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "RunInstances", "BlockDeviceMappings": [ { "DeviceName": "/dev/sda1", "Ebs": { "DeleteOnTermination": true, "VolumeSize": 50, "VolumeType": "gp2" } }, { "DeviceName": "xvdf", "Ebs": { "DeleteOnTermination": true, "VolumeSize": 100, Automation 1402 AWS Systems Manager User Guide "VolumeType": "gp2" } } ], "IamInstanceProfile": { "Arn": "{{ createSSMInstanceProfile.instanceProfileArn }}" }, "ImageId": "{{ getLatestWindowsAmi.amiId }}", "InstanceType": "t2.micro", "MaxCount": 1, "MinCount": 1, "PrivateIpAddress": "10.0.100.50", "SecurityGroupIds": [ "{{ createDCSecGroup.dcSecGroupId }}" ], "SubnetId": "{{ createDCSubnet1.firstSubnetId }}", "TagSpecifications": [ { "ResourceType": "instance", "Tags": [ { "Key": "Name", "Value": "SampleDC1" } ] } ] }, "outputs": [ { "Name": "pdcInstanceId", "Selector": "$.Instances[0].InstanceId", "Type": "String" } ], "nextStep": "launchDC2" }, { "name": "launchDC2", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "RunInstances", Automation 1403 AWS Systems Manager User Guide "BlockDeviceMappings": [ { "DeviceName": "/dev/sda1", "Ebs": { "DeleteOnTermination": true, "VolumeSize": 50, "VolumeType": "gp2" } }, { "DeviceName": "xvdf", "Ebs": { "DeleteOnTermination": true, "VolumeSize": 100, "VolumeType": "gp2" } } ], "IamInstanceProfile": { "Arn": "{{ createSSMInstanceProfile.instanceProfileArn }}" }, "ImageId": "{{ getLatestWindowsAmi.amiId }}", "InstanceType": "t2.micro", "MaxCount": 1, "MinCount": 1, "PrivateIpAddress": "10.0.101.50", "SecurityGroupIds": [ "{{ createDCSecGroup.dcSecGroupId }}" ], "SubnetId": "{{ createDCSubnet2.secondSubnetId }}", "TagSpecifications": [ { "ResourceType": "instance", "Tags": [ { "Key": "Name", "Value": "SampleDC2" } ] } ] }, "outputs": [ { Automation 1404 AWS Systems Manager User Guide "Name": "adcInstanceId", "Selector": "$.Instances[0].InstanceId", "Type": "String" } ], "nextStep": "verifyDCInstanceState" }, { "name": "verifyDCInstanceState", "action": "aws:waitForAwsResourceProperty", "inputs": { "Service": "ec2", "Api": "DescribeInstanceStatus", "IncludeAllInstances": true, "InstanceIds": [ "{{ launchDC1.pdcInstanceId }}", "{{ launchDC2.adcInstanceId }}" ], "PropertySelector": "$.InstanceStatuses[0].InstanceState.Name", "DesiredValues": [ "running" ] }, "nextStep": "verifyInstancesOnlineSSM" }, { "name": "verifyInstancesOnlineSSM", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 600, "inputs": { "Service": "ssm", "Api": "DescribeInstanceInformation", "InstanceInformationFilterList": [ { "key": "InstanceIds", "valueSet": [ "{{ launchDC1.pdcInstanceId }}", "{{ launchDC2.adcInstanceId }}" ] } ], "PropertySelector": "$.InstanceInformationList[0].PingStatus", "DesiredValues": [ "Online" Automation 1405 AWS Systems Manager ] }, "nextStep": "installADRoles" }, { "name": "installADRoles", "action": "aws:runCommand", "inputs": { User Guide "DocumentName": "AWS-RunPowerShellScript", "InstanceIds": [ "{{ launchDC1.pdcInstanceId }}", "{{ launchDC2.adcInstanceId }}" ], "Parameters": { "commands": [ "try {", " Install-WindowsFeature -Name AD-Domain-Services - IncludeManagementTools", "}", "catch {", " Write-Error \"Failed to install ADDS Role.\"",
systems-manager-ug-410
systems-manager-ug.pdf
410
"{{ launchDC2.adcInstanceId }}" ], "PropertySelector": "$.InstanceStatuses[0].InstanceState.Name", "DesiredValues": [ "running" ] }, "nextStep": "verifyInstancesOnlineSSM" }, { "name": "verifyInstancesOnlineSSM", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 600, "inputs": { "Service": "ssm", "Api": "DescribeInstanceInformation", "InstanceInformationFilterList": [ { "key": "InstanceIds", "valueSet": [ "{{ launchDC1.pdcInstanceId }}", "{{ launchDC2.adcInstanceId }}" ] } ], "PropertySelector": "$.InstanceInformationList[0].PingStatus", "DesiredValues": [ "Online" Automation 1405 AWS Systems Manager ] }, "nextStep": "installADRoles" }, { "name": "installADRoles", "action": "aws:runCommand", "inputs": { User Guide "DocumentName": "AWS-RunPowerShellScript", "InstanceIds": [ "{{ launchDC1.pdcInstanceId }}", "{{ launchDC2.adcInstanceId }}" ], "Parameters": { "commands": [ "try {", " Install-WindowsFeature -Name AD-Domain-Services - IncludeManagementTools", "}", "catch {", " Write-Error \"Failed to install ADDS Role.\"", "}" ] } }, "nextStep": "setAdminPassword" }, { "name": "setAdminPassword", "action": "aws:runCommand", "inputs": { "DocumentName": "AWS-RunPowerShellScript", "InstanceIds": [ "{{ launchDC1.pdcInstanceId }}" ], "Parameters": { "commands": [ "net user Administrator \"sampleAdminPass123!\"" ] } }, "nextStep": "createForest" }, { Automation 1406 AWS Systems Manager User Guide "name": "createForest", "action": "aws:runCommand", "inputs": { "DocumentName": "AWS-RunPowerShellScript", "InstanceIds": [ "{{ launchDC1.pdcInstanceId }}" ], "Parameters": { "commands": [ "$dsrmPass = 'sample123!' | ConvertTo-SecureString -asPlainText - Force", "try {", " Install-ADDSForest -DomainName \"sample.com\" -DomainMode 6 - ForestMode 6 -InstallDNS -DatabasePath \"D:\\NTDS\" -SysvolPath \"D:\\SYSVOL\" - SafeModeAdministratorPassword $dsrmPass -Force", "}", "catch {", " Write-Error $_", "}", "try {", " Add-DnsServerForwarder -IPAddress \"10.0.100.2\"", "}", "catch {", " Write-Error $_", "}" ] } }, "nextStep": "associateDhcpOptions" }, { "name": "associateDhcpOptions", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "AssociateDhcpOptions", "DhcpOptionsId": "{{ createDhcpOptions.dhcpOptionsId }}", "VpcId": "{{ createVpc.vpcId }}" }, "nextStep": "waitForADServices" }, { "name": "waitForADServices", Automation 1407 AWS Systems Manager User Guide "action": "aws:sleep", "inputs": { "Duration": "PT1M" }, "nextStep": "promoteADC" }, { "name": "promoteADC", "action": "aws:runCommand", "inputs": { "DocumentName": "AWS-RunPowerShellScript", "InstanceIds": [ "{{ launchDC2.adcInstanceId }}" ], "Parameters": { "commands": [ "ipconfig /renew", "$dsrmPass = 'sample123!' | ConvertTo-SecureString -asPlainText - Force", "$domAdminUser = \"sample\\Administrator\"", "$domAdminPass = \"sampleAdminPass123!\" | ConvertTo-SecureString - asPlainText -Force", "$domAdminCred = New-Object System.Management.Automation.PSCredential($domAdminUser,$domAdminPass)", "try {", " Install-ADDSDomainController -DomainName \"sample.com \" -InstallDNS -DatabasePath \"D:\\NTDS\" -SysvolPath \"D:\\SYSVOL\" - SafeModeAdministratorPassword $dsrmPass -Credential $domAdminCred -Force", "}", "catch {", " Write-Error $_", "}" ] } } } ] } Automation 1408 AWS Systems Manager User Guide Restore a root volume from the latest snapshot The operating system on a root volume can become corrupted for various reasons. For example, following a patching operation, instances might fail to boot successfully due to a corrupted kernel or registry. Automating common troubleshooting tasks, like restoring a root volume from the latest snapshot taken before the patching operation, can reduce downtime and expedite your troubleshooting efforts. AWS Systems Manager Automation actions can help you accomplish this. Automation is a tool in AWS Systems Manager. The following example AWS Systems Manager runbook performs these actions: • Uses the aws:executeAwsApi automation action to retrieve details from the root volume of the instance. • Uses the aws:executeScript automation action to retrieve the latest snapshot for the root volume. • Uses the aws:branch automation action to continue the automation if a snapshot is found for the root volume. YAML --- description: Custom Automation Troubleshooting Example schemaVersion: '0.3' assumeRole: "{{ AutomationAssumeRole }}" parameters: AutomationAssumeRole: type: String description: "(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to use this runbook." default: '' InstanceId: type: String description: "(Required) The Instance Id whose root EBS volume you want to restore the latest Snapshot." default: '' mainSteps: - name: getInstanceDetails Automation 1409 AWS Systems Manager User Guide action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: DescribeInstances InstanceIds: - "{{ InstanceId }}" outputs: - Name: availabilityZone Selector: "$.Reservations[0].Instances[0].Placement.AvailabilityZone" Type: String - Name: rootDeviceName Selector: "$.Reservations[0].Instances[0].RootDeviceName" Type: String nextStep: getRootVolumeId - name: getRootVolumeId action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: DescribeVolumes Filters: - Name: attachment.device Values: ["{{ getInstanceDetails.rootDeviceName }}"] - Name: attachment.instance-id Values: ["{{ InstanceId }}"] outputs: - Name: rootVolumeId Selector: "$.Volumes[0].VolumeId" Type: String nextStep: getSnapshotsByStartTime - name: getSnapshotsByStartTime action: aws:executeScript timeoutSeconds: 45 onFailure: Abort inputs: Runtime: python3.8 Handler: getSnapshotsByStartTime InputPayload: rootVolumeId : "{{ getRootVolumeId.rootVolumeId }}" Script: |- def getSnapshotsByStartTime(events,context): import boto3 Automation 1410 AWS Systems Manager User Guide #Initialize client ec2 = boto3.client('ec2') rootVolumeId = events['rootVolumeId'] snapshotsQuery = ec2.describe_snapshots( Filters=[ { "Name": "volume-id", "Values": [rootVolumeId] } ] ) if not snapshotsQuery['Snapshots']: noSnapshotFoundString = "NoSnapshotFound" return { 'noSnapshotFound' : noSnapshotFoundString } else: jsonSnapshots = snapshotsQuery['Snapshots'] sortedSnapshots = sorted(jsonSnapshots, key=lambda k: k['StartTime'], reverse=True) latestSortedSnapshotId = sortedSnapshots[0]['SnapshotId'] return { 'latestSnapshotId' : latestSortedSnapshotId } outputs: - Name: Payload Selector: $.Payload Type: StringMap - Name: latestSnapshotId Selector: $.Payload.latestSnapshotId Type: String - Name: noSnapshotFound Selector: $.Payload.noSnapshotFound Type: String nextStep: branchFromResults - name: branchFromResults action: aws:branch onFailure: Abort inputs: Choices: - NextStep: createNewRootVolumeFromSnapshot Not: Variable: "{{ getSnapshotsByStartTime.noSnapshotFound }}" StringEquals: "NoSnapshotFound" isEnd: true - name: createNewRootVolumeFromSnapshot action: aws:executeAwsApi onFailure: Abort Automation 1411 AWS Systems Manager User Guide inputs: Service: ec2 Api: CreateVolume AvailabilityZone: "{{ getInstanceDetails.availabilityZone }}" SnapshotId: "{{ getSnapshotsByStartTime.latestSnapshotId }}" outputs: - Name: newRootVolumeId
systems-manager-ug-411
systems-manager-ug.pdf
411
'noSnapshotFound' : noSnapshotFoundString } else: jsonSnapshots = snapshotsQuery['Snapshots'] sortedSnapshots = sorted(jsonSnapshots, key=lambda k: k['StartTime'], reverse=True) latestSortedSnapshotId = sortedSnapshots[0]['SnapshotId'] return { 'latestSnapshotId' : latestSortedSnapshotId } outputs: - Name: Payload Selector: $.Payload Type: StringMap - Name: latestSnapshotId Selector: $.Payload.latestSnapshotId Type: String - Name: noSnapshotFound Selector: $.Payload.noSnapshotFound Type: String nextStep: branchFromResults - name: branchFromResults action: aws:branch onFailure: Abort inputs: Choices: - NextStep: createNewRootVolumeFromSnapshot Not: Variable: "{{ getSnapshotsByStartTime.noSnapshotFound }}" StringEquals: "NoSnapshotFound" isEnd: true - name: createNewRootVolumeFromSnapshot action: aws:executeAwsApi onFailure: Abort Automation 1411 AWS Systems Manager User Guide inputs: Service: ec2 Api: CreateVolume AvailabilityZone: "{{ getInstanceDetails.availabilityZone }}" SnapshotId: "{{ getSnapshotsByStartTime.latestSnapshotId }}" outputs: - Name: newRootVolumeId Selector: "$.VolumeId" Type: String nextStep: stopInstance - name: stopInstance action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: StopInstances InstanceIds: - "{{ InstanceId }}" nextStep: verifyVolumeAvailability - name: verifyVolumeAvailability action: aws:waitForAwsResourceProperty timeoutSeconds: 120 inputs: Service: ec2 Api: DescribeVolumes VolumeIds: - "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}" PropertySelector: "$.Volumes[0].State" DesiredValues: - "available" nextStep: verifyInstanceStopped - name: verifyInstanceStopped action: aws:waitForAwsResourceProperty timeoutSeconds: 120 inputs: Service: ec2 Api: DescribeInstances InstanceIds: - "{{ InstanceId }}" PropertySelector: "$.Reservations[0].Instances[0].State.Name" DesiredValues: - "stopped" nextStep: detachRootVolume - name: detachRootVolume Automation 1412 AWS Systems Manager User Guide action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: DetachVolume VolumeId: "{{ getRootVolumeId.rootVolumeId }}" nextStep: verifyRootVolumeDetached - name: verifyRootVolumeDetached action: aws:waitForAwsResourceProperty timeoutSeconds: 30 inputs: Service: ec2 Api: DescribeVolumes VolumeIds: - "{{ getRootVolumeId.rootVolumeId }}" PropertySelector: "$.Volumes[0].State" DesiredValues: - "available" nextStep: attachNewRootVolume - name: attachNewRootVolume action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: AttachVolume Device: "{{ getInstanceDetails.rootDeviceName }}" InstanceId: "{{ InstanceId }}" VolumeId: "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}" nextStep: verifyNewRootVolumeAttached - name: verifyNewRootVolumeAttached action: aws:waitForAwsResourceProperty timeoutSeconds: 30 inputs: Service: ec2 Api: DescribeVolumes VolumeIds: - "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}" PropertySelector: "$.Volumes[0].Attachments[0].State" DesiredValues: - "attached" nextStep: startInstance - name: startInstance action: aws:executeAwsApi onFailure: Abort Automation 1413 AWS Systems Manager User Guide inputs: Service: ec2 Api: StartInstances InstanceIds: - "{{ InstanceId }}" JSON { "description": "Custom Automation Troubleshooting Example", "schemaVersion": "0.3", "assumeRole": "{{ AutomationAssumeRole }}", "parameters": { "AutomationAssumeRole": { "type": "String", "description": "(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to run this runbook.", "default": "" }, "InstanceId": { "type": "String", "description": "(Required) The Instance Id whose root EBS volume you want to restore the latest Snapshot.", "default": "" } }, "mainSteps": [ { "name": "getInstanceDetails", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "DescribeInstances", "InstanceIds": [ "{{ InstanceId }}" ] }, "outputs": [ { "Name": "availabilityZone", Automation 1414 AWS Systems Manager User Guide "Selector": "$.Reservations[0].Instances[0].Placement.AvailabilityZone", "Type": "String" }, { "Name": "rootDeviceName", "Selector": "$.Reservations[0].Instances[0].RootDeviceName", "Type": "String" } ], "nextStep": "getRootVolumeId" }, { "name": "getRootVolumeId", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "DescribeVolumes", "Filters": [ { "Name": "attachment.device", "Values": [ "{{ getInstanceDetails.rootDeviceName }}" ] }, { "Name": "attachment.instance-id", "Values": [ "{{ InstanceId }}" ] } ] }, "outputs": [ { "Name": "rootVolumeId", "Selector": "$.Volumes[0].VolumeId", "Type": "String" } ], "nextStep": "getSnapshotsByStartTime" }, { Automation 1415 AWS Systems Manager User Guide "name": "getSnapshotsByStartTime", "action": "aws:executeScript", "timeoutSeconds": 45, "onFailure": "Continue", "inputs": { "Runtime": "python3.8", "Handler": "getSnapshotsByStartTime", "InputPayload": { "rootVolumeId": "{{ getRootVolumeId.rootVolumeId }}" }, "Attachment": "getSnapshotsByStartTime.py" }, "outputs": [ { "Name": "Payload", "Selector": "$.Payload", "Type": "StringMap" }, { "Name": "latestSnapshotId", "Selector": "$.Payload.latestSnapshotId", "Type": "String" }, { "Name": "noSnapshotFound", "Selector": "$.Payload.noSnapshotFound", "Type": "String" } ], "nextStep": "branchFromResults" }, { "name": "branchFromResults", "action": "aws:branch", "onFailure": "Abort", "inputs": { "Choices": [ { "NextStep": "createNewRootVolumeFromSnapshot", "Not": { "Variable": "{{ getSnapshotsByStartTime.noSnapshotFound }}", "StringEquals": "NoSnapshotFound" } Automation 1416 AWS Systems Manager User Guide } ] }, "isEnd": true }, { "name": "createNewRootVolumeFromSnapshot", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateVolume", "AvailabilityZone": "{{ getInstanceDetails.availabilityZone }}", "SnapshotId": "{{ getSnapshotsByStartTime.latestSnapshotId }}" }, "outputs": [ { "Name": "newRootVolumeId", "Selector": "$.VolumeId", "Type": "String" } ], "nextStep": "stopInstance" }, { "name": "stopInstance", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "StopInstances", "InstanceIds": [ "{{ InstanceId }}" ] }, "nextStep": "verifyVolumeAvailability" }, { "name": "verifyVolumeAvailability", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 120, "inputs": { "Service": "ec2", "Api": "DescribeVolumes", Automation 1417 AWS Systems Manager User Guide "VolumeIds": [ "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}" ], "PropertySelector": "$.Volumes[0].State", "DesiredValues": [ "available" ] }, "nextStep": "verifyInstanceStopped" }, { "name": "verifyInstanceStopped", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 120, "inputs": { "Service": "ec2", "Api": "DescribeInstances", "InstanceIds": [ "{{ InstanceId }}" ], "PropertySelector": "$.Reservations[0].Instances[0].State.Name", "DesiredValues": [ "stopped" ] }, "nextStep": "detachRootVolume" }, { "name": "detachRootVolume", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "DetachVolume", "VolumeId": "{{ getRootVolumeId.rootVolumeId }}" }, "nextStep": "verifyRootVolumeDetached" }, { "name": "verifyRootVolumeDetached", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 30, "inputs": { "Service": "ec2", Automation 1418 AWS Systems Manager User Guide "Api": "DescribeVolumes", "VolumeIds": [ "{{ getRootVolumeId.rootVolumeId }}" ], "PropertySelector": "$.Volumes[0].State", "DesiredValues": [ "available" ] }, "nextStep": "attachNewRootVolume" }, { "name": "attachNewRootVolume", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "AttachVolume", "Device": "{{ getInstanceDetails.rootDeviceName }}", "InstanceId": "{{ InstanceId }}", "VolumeId": "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}" }, "nextStep": "verifyNewRootVolumeAttached" }, { "name": "verifyNewRootVolumeAttached", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 30, "inputs": { "Service": "ec2", "Api": "DescribeVolumes", "VolumeIds": [
systems-manager-ug-412
systems-manager-ug.pdf
412
"name": "detachRootVolume", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "DetachVolume", "VolumeId": "{{ getRootVolumeId.rootVolumeId }}" }, "nextStep": "verifyRootVolumeDetached" }, { "name": "verifyRootVolumeDetached", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 30, "inputs": { "Service": "ec2", Automation 1418 AWS Systems Manager User Guide "Api": "DescribeVolumes", "VolumeIds": [ "{{ getRootVolumeId.rootVolumeId }}" ], "PropertySelector": "$.Volumes[0].State", "DesiredValues": [ "available" ] }, "nextStep": "attachNewRootVolume" }, { "name": "attachNewRootVolume", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "AttachVolume", "Device": "{{ getInstanceDetails.rootDeviceName }}", "InstanceId": "{{ InstanceId }}", "VolumeId": "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}" }, "nextStep": "verifyNewRootVolumeAttached" }, { "name": "verifyNewRootVolumeAttached", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 30, "inputs": { "Service": "ec2", "Api": "DescribeVolumes", "VolumeIds": [ "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}" ], "PropertySelector": "$.Volumes[0].Attachments[0].State", "DesiredValues": [ "attached" ] }, "nextStep": "startInstance" }, { "name": "startInstance", "action": "aws:executeAwsApi", Automation 1419 AWS Systems Manager User Guide "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "StartInstances", "InstanceIds": [ "{{ InstanceId }}" ] } } ], "files": { "getSnapshotsByStartTime.py": { "checksums": { "sha256": "sampleETagValue" } } } } Create an AMI and cross-Region copy Creating an Amazon Machine Image (AMI) of an instance is a common process used in backup and recovery. You might also choose to copy an AMI to another AWS Region as part of a disaster recovery architecture. Automating common maintenance tasks can reduce downtime if an issue requires failover. AWS Systems Manager Automation actions can help you accomplish this. Automation is a tool in AWS Systems Manager. The following example AWS Systems Manager runbook performs these actions: • Uses the aws:executeAwsApi automation action to create an AMI. • Uses the aws:waitForAwsResourceProperty automation action to confirm the availability of the AMI. • Uses the aws:executeScript automation action to copy the AMI to the destination Region. YAML --- description: Custom Automation Backup and Recovery Example schemaVersion: '0.3' Automation 1420 AWS Systems Manager User Guide assumeRole: "{{ AutomationAssumeRole }}" parameters: AutomationAssumeRole: type: String description: "(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to use this runbook." default: '' InstanceId: type: String description: "(Required) The ID of the EC2 instance." default: '' mainSteps: - name: createImage action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateImage InstanceId: "{{ InstanceId }}" Name: "Automation Image for {{ InstanceId }}" NoReboot: false outputs: - Name: newImageId Selector: "$.ImageId" Type: String nextStep: verifyImageAvailability - name: verifyImageAvailability action: aws:waitForAwsResourceProperty timeoutSeconds: 600 inputs: Service: ec2 Api: DescribeImages ImageIds: - "{{ createImage.newImageId }}" PropertySelector: "$.Images[0].State" DesiredValues: - available nextStep: copyImage - name: copyImage action: aws:executeScript timeoutSeconds: 45 Automation 1421 AWS Systems Manager User Guide onFailure: Abort inputs: Runtime: python3.8 Handler: crossRegionImageCopy InputPayload: newImageId : "{{ createImage.newImageId }}" Script: |- def crossRegionImageCopy(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2', region_name='us-east-1') newImageId = events['newImageId'] ec2.copy_image( Name='DR Copy for ' + newImageId, SourceImageId=newImageId, SourceRegion='us-west-2' ) JSON { "description": "Custom Automation Backup and Recovery Example", "schemaVersion": "0.3", "assumeRole": "{{ AutomationAssumeRole }}", "parameters": { "AutomationAssumeRole": { "type": "String", "description": "(Required) The ARN of the role that allows Automation to perform\nthe actions on your behalf. If no role is specified, Systems Manager Automation\nuses your IAM permissions to run this runbook.", "default": "" }, "InstanceId": { "type": "String", "description": "(Required) The ID of the EC2 instance.", "default": "" } }, "mainSteps": [ { Automation 1422 AWS Systems Manager User Guide "name": "createImage", "action": "aws:executeAwsApi", "onFailure": "Abort", "inputs": { "Service": "ec2", "Api": "CreateImage", "InstanceId": "{{ InstanceId }}", "Name": "Automation Image for {{ InstanceId }}", "NoReboot": false }, "outputs": [ { "Name": "newImageId", "Selector": "$.ImageId", "Type": "String" } ], "nextStep": "verifyImageAvailability" }, { "name": "verifyImageAvailability", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 600, "inputs": { "Service": "ec2", "Api": "DescribeImages", "ImageIds": [ "{{ createImage.newImageId }}" ], "PropertySelector": "$.Images[0].State", "DesiredValues": [ "available" ] }, "nextStep": "copyImage" }, { "name": "copyImage", "action": "aws:executeScript", "timeoutSeconds": 45, "onFailure": "Abort", "inputs": { "Runtime": "python3.8", "Handler": "crossRegionImageCopy", Automation 1423 AWS Systems Manager User Guide "InputPayload": { "newImageId": "{{ createImage.newImageId }}" }, "Attachment": "crossRegionImageCopy.py" } } ], "files": { "crossRegionImageCopy.py": { "checksums": { "sha256": "sampleETagValue" } } } } Creating input parameters that populate AWS resources Automation, a tool in Systems Manager, populates AWS resources in the AWS Management Console that match the resource type you define for an input parameter. Resources in your AWS account that match the resource type are displayed in a dropdown list for you to choose. You can define input parameter types for Amazon Elastic Compute Cloud (Amazon EC2) instances, Amazon Simple Storage Service (Amazon S3) buckets, and AWS Identity and Access Management (IAM) roles. The supported type definitions and the regular expressions used to locate matching resources are as follows: • AWS::EC2::Instance::Id - ^m?i-([a-z0-9]{8}|[a-z0-9]{17})$ • List<AWS::EC2::Instance::Id> - ^m?i-([a-z0-9]{8}|[a-z0-9]{17})$ • AWS::S3::Bucket::Name - ^[0-9a-z][a-z0-9\\-\\.]{3,63}$ • List<AWS::S3::Bucket::Name> - ^[0-9a-z][a-z0-9\\-\\.]{3,63}$ • AWS::IAM::Role::Arn - ^arn:(aws|aws-cn|aws-us-gov|aws-iso|aws-iso-b):iam:: [0-9]{12}:role/.*$ • List<AWS::IAM::Role::Arn> - ^arn:(aws|aws-cn|aws-us-gov|aws-iso|aws-iso- b):iam::[0-9]{12}:role/.*$ The following is an example of input parameter types defined in runbook content. Automation 1424 AWS Systems Manager YAML User
systems-manager-ug-413
systems-manager-ug.pdf
413
displayed in a dropdown list for you to choose. You can define input parameter types for Amazon Elastic Compute Cloud (Amazon EC2) instances, Amazon Simple Storage Service (Amazon S3) buckets, and AWS Identity and Access Management (IAM) roles. The supported type definitions and the regular expressions used to locate matching resources are as follows: • AWS::EC2::Instance::Id - ^m?i-([a-z0-9]{8}|[a-z0-9]{17})$ • List<AWS::EC2::Instance::Id> - ^m?i-([a-z0-9]{8}|[a-z0-9]{17})$ • AWS::S3::Bucket::Name - ^[0-9a-z][a-z0-9\\-\\.]{3,63}$ • List<AWS::S3::Bucket::Name> - ^[0-9a-z][a-z0-9\\-\\.]{3,63}$ • AWS::IAM::Role::Arn - ^arn:(aws|aws-cn|aws-us-gov|aws-iso|aws-iso-b):iam:: [0-9]{12}:role/.*$ • List<AWS::IAM::Role::Arn> - ^arn:(aws|aws-cn|aws-us-gov|aws-iso|aws-iso- b):iam::[0-9]{12}:role/.*$ The following is an example of input parameter types defined in runbook content. Automation 1424 AWS Systems Manager YAML User Guide description: Enables encryption on an Amazon S3 bucket schemaVersion: '0.3' assumeRole: '{{ AutomationAssumeRole }}' parameters: BucketName: type: 'AWS::S3::Bucket::Name' description: (Required) The name of the Amazon S3 bucket you want to encrypt. SSEAlgorithm: type: String description: (Optional) The server-side encryption algorithm to use for the default encryption. default: AES256 AutomationAssumeRole: type: 'AWS::IAM::Role::Arn' description: (Optional) The Amazon Resource Name (ARN) of the role that allows Automation to perform the actions on your behalf. default: '' mainSteps: - name: enableBucketEncryption action: 'aws:executeAwsApi' inputs: Service: s3 Api: PutBucketEncryption Bucket: '{{BucketName}}' ServerSideEncryptionConfiguration: Rules: - ApplyServerSideEncryptionByDefault: SSEAlgorithm: '{{SSEAlgorithm}}' isEnd: true JSON { "description": "Enables encryption on an Amazon S3 bucket", "schemaVersion": "0.3", "assumeRole": "{{ AutomationAssumeRole }}", "parameters": { "BucketName": { "type": "AWS::S3::Bucket::Name", "description": "(Required) The name of the Amazon S3 bucket you want to encrypt." Automation 1425 AWS Systems Manager }, "SSEAlgorithm": { "type": "String", User Guide "description": "(Optional) The server-side encryption algorithm to use for the default encryption.", "default": "AES256" }, "AutomationAssumeRole": { "type": "AWS::IAM::Role::Arn", "description": "(Optional) The Amazon Resource Name (ARN) of the role that allows Automation to perform the actions on your behalf.", "default": "" } }, "mainSteps": [ { "name": "enableBucketEncryption", "action": "aws:executeAwsApi", "inputs": { "Service": "s3", "Api": "PutBucketEncryption", "Bucket": "{{BucketName}}", "ServerSideEncryptionConfiguration": { "Rules": [ { "ApplyServerSideEncryptionByDefault": { "SSEAlgorithm": "{{SSEAlgorithm}}" } } ] } }, "isEnd": true } ] } Using Document Builder to create runbooks If the AWS Systems Manager public runbooks don't support all the actions you want to perform on your AWS resources, you can create your own runbooks. To create a custom runbook, you can manually create a local YAML or JSON format file with the appropriate automation actions. Automation 1426 AWS Systems Manager User Guide Alternatively, you can use Document Builder in the Systems Manager Automation console to build a custom runbook. Using Document Builder, you can add automation actions to your custom runbook and provide the required parameters without having to use JSON or YAML syntax. After you add steps and create the runbook, the system converts the actions you've added into the YAML format that Systems Manager can use to run automation. Runbooks support the use of Markdown, a markup language, which allows you to add wiki-style descriptions to runbooks and individual steps within the runbook. For more information about using Markdown, see Using Markdown in AWS. Create a runbook using Document Builder Before you begin We recommend that you read about the different actions that you can use within a runbook. For more information, see Systems Manager Automation actions reference. To create a runbook using Document Builder 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Documents. 3. Choose Create automation. 4. 5. For Name, enter a descriptive name for the runbook. For Document description, provide the markdown style description for the runbook. You can provide instructions for using the runbook, numbered steps, or any other type of information to describe the runbook. Refer to the default text for information about formatting your content. Tip Toggle between Hide preview and Show preview to see what your description content looks like as you compose. 6. (Optional) For Assume role, enter the name or ARN of a service role to perform actions on your behalf. If you don't specify a role, Automation uses the access permissions of the user who runs the automation. Automation 1427 AWS Systems Manager User Guide Important For runbooks not owned by Amazon that use the aws:executeScript action, a role must be specified. For information, see Permissions for using runbooks. 7. (Optional) For Outputs, enter any outputs for the automation of this runbook to make available for other processes. For example, if your runbook creates a new AMI, you might specify ["CreateImage.ImageId"], and then use this output to create new instances in a subsequent automation. 8. (Optional) Expand the Input parameters section and do the following. 1. For Parameter name, enter a descriptive name for the runbook parameter you're creating. 2. For Type, choose a type for the parameter, such as String or MapList. 3. For Required, do one of the following: • Choose Yes if a value for this runbook parameter must be supplied at runtime. • Choose No if the parameter isn't
systems-manager-ug-414
systems-manager-ug.pdf
414
make available for other processes. For example, if your runbook creates a new AMI, you might specify ["CreateImage.ImageId"], and then use this output to create new instances in a subsequent automation. 8. (Optional) Expand the Input parameters section and do the following. 1. For Parameter name, enter a descriptive name for the runbook parameter you're creating. 2. For Type, choose a type for the parameter, such as String or MapList. 3. For Required, do one of the following: • Choose Yes if a value for this runbook parameter must be supplied at runtime. • Choose No if the parameter isn't required, and (optional) enter a default parameter value in Default value. 4. For Description, enter a description for the runbook parameter. Note To add more runbook parameters, choose Add a parameter. To remove a runbook parameter, choose the X (Remove) button. 9. (Optional) Expand the Target type section and choose a target type to define the kinds of resources the automation can run on. For example, to use a runbook on EC2 instances, choose /AWS::EC2::Instance. Note If you specify a value of '/', the runbook can run on all types of resources. For a list of valid resource types, see AWS Resource Types Reference in the AWS CloudFormation User Guide. Automation 1428 AWS Systems Manager User Guide 10. (Optional) Expand the Document tags section and enter one or more tag key-value pairs to apply to the runbook. Tags make it easier to identify, organize, and search for resources. 11. In the Step 1 section, provide the following information. • For Step name, enter a descriptive name for the first step of the automation. • For Action type, select the action type to use for this step. For a list and information about the available action types, see Systems Manager Automation actions reference. • For Description, enter a description for the automation step. You can use Markdown to format your text. • Depending on the Action type selected, enter the required inputs for the action type in the Step inputs section. For example, if you selected the action aws:approve, you must specify a value for the Approvers property. For information about the step input fields, see the entry in Systems Manager Automation actions reference for the action type you selected. For example: aws:executeStateMachine – Run an AWS Step Functions state machine. • (Optional) For Additional inputs, provide any additional input values needed for your runbook. The available input types depend on the action type you selected for the step. (Note that some action types require input values.) Note To add more inputs, choose Add optional input. To remove an input, choose the X (Remove) button. • (Optional) For Outputs, enter any outputs for this step to make available for other processes. Note Outputs isn't available for all action types. • (Optional) Expand the Common properties section and specify properties for the actions that are common to all automation actions. For example, for Timeout seconds, you can provide a value in seconds to specify how long the step can run before it's stopped. Automation 1429 AWS Systems Manager User Guide For more information, see Properties shared by all actions. Note To add more steps, select Add step and repeat the procedure for creating a step. To remove a step, choose Remove step. 12. Choose Create automation to save the runbook. Create a runbook that runs scripts The following procedure shows how to use Document Builder in the AWS Systems Manager Automation console to create a custom runbook that runs a script. The first step of the runbook you create runs a script to launch an Amazon Elastic Compute Cloud (Amazon EC2) instance. The second step runs another script to monitor for the instance status check to change to ok. Then, an overall status of Success is reported for the automation. Before you begin Make sure you have completed the following steps: • Verify that you have administrator privileges, or that you have been granted the appropriate permissions to access Systems Manager in AWS Identity and Access Management (IAM). For information, see Verifying user access for runbooks. • Verify that you have an IAM service role for Automation (also known as an assume role) in your AWS account. The role is required because this walkthrough uses the aws:executeScript action. For information about creating this role, see Configuring a service role (assume role) access for automations. For information about the IAM service role requirement for running aws:executeScript, see Permissions for using runbooks. • Verify that you have permission to launch EC2 instances. For information, see IAM and Amazon EC2 in the Amazon EC2 User Guide. Automation 1430 AWS Systems Manager User Guide To create a custom runbook that runs scripts using Document Builder 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2.
systems-manager-ug-415
systems-manager-ug.pdf
415
role) in your AWS account. The role is required because this walkthrough uses the aws:executeScript action. For information about creating this role, see Configuring a service role (assume role) access for automations. For information about the IAM service role requirement for running aws:executeScript, see Permissions for using runbooks. • Verify that you have permission to launch EC2 instances. For information, see IAM and Amazon EC2 in the Amazon EC2 User Guide. Automation 1430 AWS Systems Manager User Guide To create a custom runbook that runs scripts using Document Builder 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Documents. 3. Choose Create automation. 4. 5. For Name, type this descriptive name for the runbook: LaunchInstanceAndCheckStatus. (Optional) For Document description, replace the default text with a description for this runbook, using Markdown. The following is an example. ##Title: LaunchInstanceAndCheckState ----- **Purpose**: This runbook first launches an EC2 instance using the AMI ID provided in the parameter ```imageId```. The second step of this runbook 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 | (Optional) 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 }} 6. For Assume role, enter the ARN of the IAM service role for Automation (Assume role) for the automation, in the format arn:aws:iam::111122223333:role/ AutomationServiceRole. Substitute your AWS account ID for 111122223333. The role you specify is used to provide the permissions needed to start the automation. Important For runbooks not owned by Amazon that use the aws:executeScript action, a role must be specified. For information, see Permissions for using runbooks. 7. Expand Input parameters and do the following. Automation 1431 AWS Systems Manager User Guide 1. For Parameter name, enter imageId. 2. For Type, choose String. 3. For Required, choose No. 4. For Default value, enter the following. {{ ssm:/aws/service/ami-amazon-linux-latest/amzn-ami-hvm-x86_64-gp2 }} Note This value launches an Amazon EC2 instance using the latest Amazon Linux 1 Amazon Machine Image (AMI) ID. If you want to use a different AMI, replace the value with your AMI ID. 5. For Description, enter the following. (Optional) The AMI ID to use for launching the instance. The default value uses the latest released Amazon Linux AMI ID. 8. Choose Add a parameter to create the second parameter, tagValue, and enter the following. 1. For Parameter name, enter tagValue. 2. For Type, choose String. 3. For Required, choose No. 4. For Default value, enter LaunchedBySsmAutomation. This adds the tag key-pair value Name:LaunchedBySsmAutomation to the instance. 5. For Description, enter the following. (Optional) The tag value to add to the instance. The default value is LaunchedBySsmAutomation. 9. Choose Add a parameter to create the third parameter, instanceType, and enter the following information. 1. For Parameter name, enter instanceType. 2. For Type, choose String. 3. For Required, choose No. Automation 1432 AWS Systems Manager User Guide 4. For Default value, enter t2.micro. 5. For Parameter description, enter the following. (Optional) The instance type to use for the instance. The default value is t2.micro. 10. Expand Target type and choose "/". 11. (Optional) Expand Document tags to apply resource tags to your runbook. For Tag key, enter Purpose, and for Tag value, enter LaunchInstanceAndCheckState. 12. In the Step 1 section, complete the following steps. 1. For Step name, enter this descriptive step name for the first step of the automation: LaunchEc2Instance. 2. For Action type, choose Run a script (aws:executeScript). 3. 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 script. 4. Expand Inputs. 5. For Runtime, choose the runtime language to use to run the provided script. 6. For Handler, enter launch_instance. This is the function name declared in the following script. Note This is not required for PowerShell. 7. For Script, replace the default contents with the following. Be sure to match the script with the corresponding runtime value. Python def launch_instance(events, context): import boto3 ec2 = boto3.client('ec2') Automation 1433 AWS Systems Manager User Guide image_id = events['image_id'] tag_value = events['tag_value'] instance_type = events['instance_type'] tag_config = {'ResourceType': 'instance', 'Tags': [{'Key':'Name', 'Value':tag_value}]} res = ec2.run_instances(ImageId=image_id, 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 } PowerShell Install-Module AWS.Tools.EC2 -Force Import-Module AWS.Tools.EC2 $payload = $env:InputPayload | ConvertFrom-Json $imageid = $payload.image_id $tagvalue = $payload.tag_value $instanceType = $payload.instance_type $type = New-Object Amazon.EC2.InstanceType -ArgumentList $instanceType
systems-manager-ug-416
systems-manager-ug.pdf
416
replace the default contents with the following. Be sure to match the script with the corresponding runtime value. Python def launch_instance(events, context): import boto3 ec2 = boto3.client('ec2') Automation 1433 AWS Systems Manager User Guide image_id = events['image_id'] tag_value = events['tag_value'] instance_type = events['instance_type'] tag_config = {'ResourceType': 'instance', 'Tags': [{'Key':'Name', 'Value':tag_value}]} res = ec2.run_instances(ImageId=image_id, 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 } PowerShell Install-Module AWS.Tools.EC2 -Force Import-Module AWS.Tools.EC2 $payload = $env:InputPayload | ConvertFrom-Json $imageid = $payload.image_id $tagvalue = $payload.tag_value $instanceType = $payload.instance_type $type = New-Object Amazon.EC2.InstanceType -ArgumentList $instanceType $resource = New-Object Amazon.EC2.ResourceType -ArgumentList 'instance' $tag = @{Key='Name';Value=$tagValue} $tagSpecs = New-Object Amazon.EC2.Model.TagSpecification $tagSpecs.ResourceType = $resource $tagSpecs.Tags.Add($tag) $res = New-EC2Instance -ImageId $imageId -MinCount 1 -MaxCount 1 - InstanceType $type -TagSpecification $tagSpecs Automation 1434 AWS Systems Manager User Guide return @{'InstanceId'=$res.Instances.InstanceId} 8. Expand Additional inputs. 9. For Input name, choose InputPayload. For Input value, enter the following YAML data. image_id: "{{ imageId }}" tag_value: "{{ tagValue }}" instance_type: "{{ instanceType }}" 13. Expand Outputs and do the following: • For Name, enter payload. • For Selector, enter $.Payload. • For Type, choose StringMap. 14. Choose Add step to add a second step to the runbook. The second step queries the status of the instance launched in Step 1 and waits until the status returned is ok. 15. In the Step 2 section, do the following. 1. For Step name, enter this descriptive name for the second step of the automation: WaitForInstanceStatusOk. 2. For Action type, choose Run a script (aws:executeScript). 3. For Description, enter a description for the automation step, such as the following. **About This Step** The script continuously polls the instance status check value for the instance launched in Step 1 until the ```ok``` status is returned. 4. For Runtime, choose the runtime language to be used for executing the provided script. 5. For Handler, enter poll_instance. This is the function name declared in the following script. Note This is not required for PowerShell. Automation 1435 AWS Systems Manager User Guide 6. For Script, replace the default contents with the following. Be sure to match the script with the corresponding runtime value. Python 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} PowerShell Install-Module AWS.Tools.EC2 -Force Automation 1436 AWS Systems Manager User Guide $inputPayload = $env:InputPayload | ConvertFrom-Json $instanceId = $inputPayload.payload.InstanceId $status = Get-EC2InstanceStatus -InstanceId $instanceId while ($status.Status.Status -ne 'ok'){ Write-Host 'Polling get status of the instance', $instanceId Start-Sleep -Seconds 5 $status = Get-EC2InstanceStatus -InstanceId $instanceId } return @{Status = $status.Status.Status; InstanceId = $instanceId} 7. Expand Additional inputs. 8. For Input name, choose InputPayload. For Input value, enter the following: {{ LaunchEc2Instance.payload }} 16. Choose Create automation to save the runbook. Using scripts in runbooks Automation runbooks support running scripts as part of the automation. Automation is a tool in AWS Systems Manager. By using runbooks, you can run scripts directly in AWS without creating a separate compute environment to run your scripts. Because runbooks can run script steps along with other automation step types, such as approvals, you can manually intervene in critical or ambiguous situations. You can send the output from aws:executeScript actions in your runbooks to Amazon CloudWatch Logs. For more information, see Logging Automation action output with CloudWatch Logs. Permissions for using runbooks To use a runbook, Systems Manager must use the permissions of an AWS Identity and Access Management (IAM) role. The method that Automation uses to determine which role's permissions to use depends on a few factors, and whether a step uses the aws:executeScript action. For runbooks that don't use aws:executeScript, Automation uses one of two sources of permissions: Automation 1437 AWS Systems Manager User Guide • The permissions of an IAM service role, or Assume role, that is specified in the runbook or passed in as a parameter. • If no IAM service role is specified, the permissions of the user who started the automation. When a step in a runbook includes the aws:executeScript action, however, an IAM service role (Assume role) is always required if the Python or PowerShell script specified for the action is calling any AWS API operations. Automation checks for this role in the following order: • The permissions of an IAM service role, or Assume role, that is specified in the runbook or passed in as a parameter. • If no role is found, Automation attempts to run the Python or PowerShell script specified for aws:executeScript without any
systems-manager-ug-417
systems-manager-ug.pdf
417
role is specified, the permissions of the user who started the automation. When a step in a runbook includes the aws:executeScript action, however, an IAM service role (Assume role) is always required if the Python or PowerShell script specified for the action is calling any AWS API operations. Automation checks for this role in the following order: • The permissions of an IAM service role, or Assume role, that is specified in the runbook or passed in as a parameter. • If no role is found, Automation attempts to run the Python or PowerShell script specified for aws:executeScript without any permissions. If the script is calling an AWS API operation (for example the Amazon EC2 CreateImage operation), or attempting to act on an AWS resource (such as an EC2 instance), the step containing the script fails, and Systems Manager returns an error message reporting the failure. Adding scripts to runbooks You can add scripts to your runbooks by including the script inline as part of a step in the runbook. You can also attach scripts to the runbook by uploading the scripts from your local machine or by specifying an Amazon Simple Storage Service (Amazon S3) bucket where the scripts are located. After a step that runs a script is complete, the output of the script is available as a JSON object, which you can then use as input for subsequent steps in your runbook. For more information about the aws:executeScript action and how to use attachments for scripts, see aws:executeScript – Run a script. Script constraints for runbooks Runbooks enforce a limit of five file attachments. Scripts can either be in the form of a Python script (.py), a PowerShell Core script (.ps1), or attached as contents within a .zip file. Using conditional statements in runbooks By default, the steps that you define in the mainSteps section of a runbook run in sequential order. After one action is completed, the next action specified in the mainSteps section begins. Furthermore, if an action fails to run, the entire automation fails (by default). You can use the aws:branch automation action and the runbook options described in this section to create automations that perform conditional branching. This means that you can create automations that Automation 1438 AWS Systems Manager User Guide jump to a different step after evaluating different choices or that dynamically respond to changes when a step is complete. Here is a list of options that you can use to create dynamic automations: • aws:branch: This automation action allows you to create a dynamic automation that evaluates multiple choices in a single step and then jumps to a different step in the runbook based on the results of that evaluation. • nextStep: This option specifies which step in an automation to process next after successfully completing a step. • isEnd: This option stops an automation at the end of a specific step. The default value for this option is false. • isCritical: This option designates a step as critical for the successful completion of the automation. If a step with this designation fails, then Automation reports the final status of the automation as Failed. The default value for this option is true. • onFailure: This option indicates whether the automation should stop, continue, or go to a different step on failure. The default value for this option is abort. The following section describes the aws:branch automation action. For more information about the nextStep, isEnd, isCritical, and onFailure options, see Example aws:branch runbooks. Working with the aws:branch action The aws:branch action offers the most dynamic conditional branching options for automations. As noted earlier, this action allows your automation to evaluate multiple conditions in a single step and then jump to a new step based on the results of that evaluation. The aws:branch action functions like an IF-ELIF-ELSE statement in programming. Here is a YAML example of an aws:branch step. - name: ChooseOSforCommands action: aws:branch inputs: Choices: - NextStep: runPowerShellCommand Variable: "{{GetInstance.platform}}" StringEquals: Windows - NextStep: runShellCommand Variable: "{{GetInstance.platform}}" Automation 1439 AWS Systems Manager StringEquals: Linux Default: PostProcessing User Guide When you specify the aws:branch action for a step, you specify Choices that the automation must evaluate. The automation can evaluate Choices based on the value of a parameter that you specified in the Parameters section of the runbook. The automation can also evaluate Choices based on output from a previous step. The automation evaluates each choice by using a Boolean expression. If the evaluation determines that the first choice is true, then the automation jumps to the step designated for that choice. If the evaluation determines that the first choice is false, then the automation evaluates the next choice. If your step includes three or more Choices, then the automation evaluates each choice in sequential order until it evaluates a choice
systems-manager-ug-418
systems-manager-ug.pdf
418
based on the value of a parameter that you specified in the Parameters section of the runbook. The automation can also evaluate Choices based on output from a previous step. The automation evaluates each choice by using a Boolean expression. If the evaluation determines that the first choice is true, then the automation jumps to the step designated for that choice. If the evaluation determines that the first choice is false, then the automation evaluates the next choice. If your step includes three or more Choices, then the automation evaluates each choice in sequential order until it evaluates a choice that is true. The automation then jumps to the designated step for the true choice. If none of the Choices are true, the automation checks to see if the step contains a Default value. A Default value defines a step that the automation should jump to if none of the choices are true. If no Default value is specified for the step, then the automation processes the next step in the runbook. Here is an aws:branch step in YAML named chooseOSfromParameter. The step includes two Choices: (NextStep: runWindowsCommand) and (NextStep: runLinuxCommand). The automation evaluates these Choices to determine which command to run for the appropriate operating system. The Variable for each choice uses {{OSName}}, which is a parameter that the runbook author defined in the Parameters section of the runbook. mainSteps: - name: chooseOSfromParameter action: aws:branch inputs: Choices: - NextStep: runWindowsCommand Variable: "{{OSName}}" StringEquals: Windows - NextStep: runLinuxCommand Variable: "{{OSName}}" StringEquals: Linux Automation 1440 AWS Systems Manager User Guide Here is an aws:branch step in YAML named chooseOSfromOutput. The step includes two Choices: (NextStep: runPowerShellCommand) and (NextStep: runShellCommand). The automation evaluates these Choices to determine which command to run for the appropriate operating system. The Variable for each choice uses {{GetInstance.platform}}, which is the output from an earlier step in the runbook. This example also includes an option called Default. If the automation evaluates both Choices, and neither choice is true, then the automation jumps to a step called PostProcessing. mainSteps: - name: chooseOSfromOutput action: aws:branch inputs: Choices: - NextStep: runPowerShellCommand Variable: "{{GetInstance.platform}}" StringEquals: Windows - NextStep: runShellCommand Variable: "{{GetInstance.platform}}" StringEquals: Linux Default: PostProcessing Creating an aws:branch step in a runbook When you create an aws:branch step in a runbook, you define the Choices the automation should evaluate to determine which step the automation should jump to next. As noted earlier, Choices are evaluated by using a Boolean expression. Each choice must define the following options: • NextStep: The next step in the runbook to process if the designated choice is true. • Variable: Specify either the name of a parameter that is defined in the Parameters section of the runbook, a variable defined in the Variables section, or specify an output object from a previous step. Specify variable values by using the following form. Variable: "{{variable name}}" Specify parameter values by using the following form. Automation 1441 AWS Systems Manager User Guide Variable: "{{parameter name}}" Specify output object variables by using the following form. Variable: "{{previousStepName.outputName}}" Note Creating the output variable is described in more detail in the next section, About creating the output variable. • Operation: The criteria used to evaluate the choice, such as StringEquals: Linux. The aws:branch action supports the following operations: String operations • StringEquals • EqualsIgnoreCase • StartsWith • EndsWith • Contains Numeric operations • NumericEquals • NumericGreater • NumericLesser • NumericGreaterOrEquals • NumericLesser • NumericLesserOrEquals Boolean operation • BooleanEquals Automation 1442 AWS Systems Manager Important User Guide When you create a runbook, the system validates each operation in the runbook. If an operation isn't supported, the system returns an error when you try to create the runbook. • Default: Specify a fallback step that the automation should jump to if none of the Choices are true. Note If you don't want to specify a Default value, then you can specify the isEnd option. If none of the Choices are true and no Default value is specified, then the automation stops at the end of the step. Use the following templates to help you construct the aws:branch step in your runbook. Replace each example resource placeholder with your own information. YAML mainSteps: - name: step name action: aws:branch inputs: Choices: - NextStep: step to jump to if evaluation for this choice is true Variable: "{{parameter name or output from previous step}}" Operation type: Operation value - NextStep: step to jump to if evaluation for this choice is true Variable: "{{parameter name or output from previous step}}" Operation type: Operation value Default: step to jump to if all choices are false JSON { "mainSteps":[ Automation 1443 AWS Systems Manager { "name":"a name for the step", "action":"aws:branch", "inputs":{ "Choices":[ { User Guide "NextStep":"step to jump to if evaluation for this choice is true", "Variable":"{{parameter name or
systems-manager-ug-419
systems-manager-ug.pdf
419
step name action: aws:branch inputs: Choices: - NextStep: step to jump to if evaluation for this choice is true Variable: "{{parameter name or output from previous step}}" Operation type: Operation value - NextStep: step to jump to if evaluation for this choice is true Variable: "{{parameter name or output from previous step}}" Operation type: Operation value Default: step to jump to if all choices are false JSON { "mainSteps":[ Automation 1443 AWS Systems Manager { "name":"a name for the step", "action":"aws:branch", "inputs":{ "Choices":[ { User Guide "NextStep":"step to jump to if evaluation for this choice is true", "Variable":"{{parameter name or output from previous step}}", "Operation type":"Operation value" }, { "NextStep":"step to jump to if evaluation for this choice is true", "Variable":"{{parameter name or output from previous step}}", "Operation type":"Operation value" } ], "Default":"step to jump to if all choices are false" } } ] } About creating the output variable To create an aws:branch choice that references the output from a previous step, you need to identify the name of the previous step and the name of the output field. You then combine the names of the step and the field by using the following format. Variable: "{{previousStepName.outputName}}" For example, the first step in the following example is named GetInstance. And then, under outputs, there is a field called platform. In the second step (ChooseOSforCommands), the author wants to reference the output from the platform field as a variable. To create the variable, simply combine the step name (GetInstance) and the output field name (platform) to create Variable: "{{GetInstance.platform}}". mainSteps: - Name: GetInstance action: aws:executeAwsApi inputs: Automation 1444 User Guide AWS Systems Manager Service: ssm Api: DescribeInstanceInformation Filters: - Key: InstanceIds Values: ["{{ InstanceId }}"] outputs: - Name: myInstance Selector: "$.InstanceInformationList[0].InstanceId" Type: String - Name: platform Selector: "$.InstanceInformationList[0].PlatformType" Type: String - name: ChooseOSforCommands action: aws:branch inputs: Choices: - NextStep: runPowerShellCommand Variable: "{{GetInstance.platform}}" StringEquals: Windows - NextStep: runShellCommand Variable: "{{GetInstance.platform}}" StringEquals: Linux Default: Sleep Here is an example that shows how "Variable": "{{ describeInstance.Platform }}" is created from the previous step and the output. - name: describeInstance action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: DescribeInstances InstanceIds: - "{{ InstanceId }}" outputs: - Name: Platform Selector: "$.Reservations[0].Instances[0].Platform" Type: String nextStep: branchOnInstancePlatform - name: branchOnInstancePlatform action: aws:branch Automation 1445 User Guide AWS Systems Manager inputs: Choices: - NextStep: runEC2RescueForWindows Variable: "{{ describeInstance.Platform }}" StringEquals: windows Default: runEC2RescueForLinux Example aws:branch runbooks Here are some example runbooks that use aws:branch. Example 1: Using aws:branch with an output variable to run commands based on the operating system type In the first step of this example (GetInstance), the runbook author uses the aws:executeAwsApi action to call the ssm DescribeInstanceInformation API operation. The author uses this action to determine the type of operating system being used by an instance. The aws:executeAwsApi action outputs the instance ID and the platform type. In the second step (ChooseOSforCommands), the author uses the aws:branch action with two Choices (NextStep: runPowerShellCommand) and (NextStep: runShellCommand). The automation evaluates the operating system of the instance by using the output from the previous step (Variable: "{{GetInstance.platform}}"). The automation jumps to a step for the designated operating system. --- schemaVersion: '0.3' assumeRole: "{{AutomationAssumeRole}}" parameters: AutomationAssumeRole: default: "" type: String mainSteps: - name: GetInstance action: aws:executeAwsApi inputs: Service: ssm Api: DescribeInstanceInformation outputs: - Name: myInstance Selector: "$.InstanceInformationList[0].InstanceId" Automation 1446 AWS Systems Manager Type: String - Name: platform Selector: "$.InstanceInformationList[0].PlatformType" User Guide Type: String - name: ChooseOSforCommands action: aws:branch inputs: Choices: - NextStep: runPowerShellCommand Variable: "{{GetInstance.platform}}" StringEquals: Windows - NextStep: runShellCommand Variable: "{{GetInstance.platform}}" StringEquals: Linux Default: Sleep - name: runShellCommand action: aws:runCommand inputs: DocumentName: AWS-RunShellScript InstanceIds: - "{{GetInstance.myInstance}}" Parameters: commands: - ls isEnd: true - name: runPowerShellCommand action: aws:runCommand inputs: DocumentName: AWS-RunPowerShellScript InstanceIds: - "{{GetInstance.myInstance}}" Parameters: commands: - ls isEnd: true - name: Sleep action: aws:sleep inputs: Duration: PT3S Example 2: Using aws:branch with a parameter variable to run commands based on the operating system type Automation 1447 AWS Systems Manager User Guide The runbook author defines several parameter options at the beginning of the runbook in the parameters section. One parameter is named OperatingSystemName. In the first step (ChooseOS), the author uses the aws:branch action with two Choices (NextStep: runWindowsCommand) and (NextStep: runLinuxCommand). The variable for these Choices references the parameter option specified in the parameters section (Variable: "{{OperatingSystemName}}"). When the user runs this runbook, they specify a value at runtime for OperatingSystemName. The automation uses the runtime parameter during the Choices evaluation. The automation jumps to a step for the designated operating system based on the runtime parameter specified for OperatingSystemName. --- schemaVersion: '0.3' assumeRole: "{{AutomationAssumeRole}}" parameters: AutomationAssumeRole: default: "" type: String OperatingSystemName: type: String LinuxInstanceId: type: String WindowsInstanceId: type: String mainSteps: - name: ChooseOS action: aws:branch inputs: Choices: - NextStep: runWindowsCommand Variable: "{{OperatingSystemName}}" StringEquals: windows - NextStep: runLinuxCommand Variable: "{{OperatingSystemName}}" StringEquals: linux Default: Sleep -
systems-manager-ug-420
systems-manager-ug.pdf
420
Choices references the parameter option specified in the parameters section (Variable: "{{OperatingSystemName}}"). When the user runs this runbook, they specify a value at runtime for OperatingSystemName. The automation uses the runtime parameter during the Choices evaluation. The automation jumps to a step for the designated operating system based on the runtime parameter specified for OperatingSystemName. --- schemaVersion: '0.3' assumeRole: "{{AutomationAssumeRole}}" parameters: AutomationAssumeRole: default: "" type: String OperatingSystemName: type: String LinuxInstanceId: type: String WindowsInstanceId: type: String mainSteps: - name: ChooseOS action: aws:branch inputs: Choices: - NextStep: runWindowsCommand Variable: "{{OperatingSystemName}}" StringEquals: windows - NextStep: runLinuxCommand Variable: "{{OperatingSystemName}}" StringEquals: linux Default: Sleep - name: runLinuxCommand action: aws:runCommand inputs: DocumentName: "AWS-RunShellScript" InstanceIds: - "{{LinuxInstanceId}}" Automation 1448 User Guide AWS Systems Manager Parameters: commands: - ls isEnd: true - name: runWindowsCommand action: aws:runCommand inputs: DocumentName: "AWS-RunPowerShellScript" InstanceIds: - "{{WindowsInstanceId}}" Parameters: commands: - date isEnd: true - name: Sleep action: aws:sleep inputs: Duration: PT3S Creating complex branching automations with operators You can create complex branching automations by using the And, Or, and Not operators in your aws:branch steps. The 'And' operator Use the And operator when you want multiple variables to be true for a choice. In the following example, the first choice evaluates if an instance is running and uses the Windows operating system. If the evaluation of both of these variables is true, then the automation jumps to the runPowerShellCommand step. If one or more of the variables is false, then the automation evaluates the variables for the second choice. mainSteps: - name: switch2 action: aws:branch inputs: Choices: - And: - Variable: "{{GetInstance.pingStatus}}" StringEquals: running - Variable: "{{GetInstance.platform}}" StringEquals: Windows Automation 1449 AWS Systems Manager User Guide NextStep: runPowerShellCommand - And: - Variable: "{{GetInstance.pingStatus}}" StringEquals: running - Variable: "{{GetInstance.platform}}" StringEquals: Linux NextStep: runShellCommand Default: sleep3 The 'Or' operator Use the Or operator when you want any of multiple variables to be true for a choice. In the following example, the first choice evaluates if a parameter string is Windows and if the output from an AWS Lambda step is true. If the evaluation determines that either of these variables is true, then the automation jumps to the RunPowerShellCommand step. If both variables are false, then the automation evaluates the variables for the second choice. - Or: - Variable: "{{parameter1}}" StringEquals: Windows - Variable: "{{BooleanParam1}}" BooleanEquals: true NextStep: RunPowershellCommand - Or: - Variable: "{{parameter2}}" StringEquals: Linux - Variable: "{{BooleanParam2}}" BooleanEquals: true NextStep: RunShellScript The 'Not' operator Use the Not operator when you want to jump to a step defined when a variable is not true. In the following example, the first choice evaluates if a parameter string is Not Linux. If the evaluation determines that the variable isn't Linux, then the automation jumps to the sleep2 step. If the evaluation of the first choice determines that it is Linux, then the automation evaluates the next choice. mainSteps: Automation 1450 User Guide AWS Systems Manager - name: switch action: aws:branch inputs: Choices: - NextStep: sleep2 Not: Variable: "{{testParam}}" StringEquals: Linux - NextStep: sleep1 Variable: "{{testParam}}" StringEquals: Windows Default: sleep3 Examples of how to use conditional options This section includes different examples of how to use dynamic options in a runbook. Each example in this section extends the following runbook. This runbook has two actions. The first action is named InstallMsiPackage. It uses the aws:runCommand action to install an application on a Windows Server instance. The second action is named TestInstall. It uses the aws:invokeLambdaFunction action to perform a test of the installed application if the application installed successfully. Step one specifies onFailure: Abort. This means that if the application didn't install successfully, the automation stops before step two. Example 1: Runbook with two linear actions --- schemaVersion: '0.3' description: Install MSI package and run validation. assumeRole: "{{automationAssumeRole}}" parameters: automationAssumeRole: type: String description: "(Required) Assume role." packageName: type: String description: "(Required) MSI package to be installed." instanceIds: type: String description: "(Required) Comma separated list of instances." mainSteps: - name: InstallMsiPackage Automation 1451 User Guide AWS Systems Manager action: aws:runCommand maxAttempts: 2 onFailure: Abort inputs: InstanceIds: - "{{instanceIds}}" DocumentName: AWS-RunPowerShellScript Parameters: commands: - msiexec /i {{packageName}} - name: TestInstall action: aws:invokeLambdaFunction maxAttempts: 1 timeoutSeconds: 500 inputs: FunctionName: TestLambdaFunction ... Creating a dynamic automation that jumps to different steps by using the onFailure option The following example uses the onFailure: step:step name, nextStep, and isEnd options to create a dynamic automation. With this example, if the InstallMsiPackage action fails, then the automation jumps to an action called PostFailure (onFailure: step:PostFailure) to run an AWS Lambda function to perform some action in the event the install failed. If the install succeeds, then the automation jumps to the TestInstall action (nextStep: TestInstall). Both the TestInstall and the PostFailure steps use the isEnd option (isEnd: true) so that the automation finishes when either of those steps is completed. Note Using the isEnd
systems-manager-ug-421
systems-manager-ug.pdf
421
by using the onFailure option The following example uses the onFailure: step:step name, nextStep, and isEnd options to create a dynamic automation. With this example, if the InstallMsiPackage action fails, then the automation jumps to an action called PostFailure (onFailure: step:PostFailure) to run an AWS Lambda function to perform some action in the event the install failed. If the install succeeds, then the automation jumps to the TestInstall action (nextStep: TestInstall). Both the TestInstall and the PostFailure steps use the isEnd option (isEnd: true) so that the automation finishes when either of those steps is completed. Note Using the isEnd option in the last step of the mainSteps section is optional. If the last step doesn't jump to other steps, then the automation stops after running the action in the last step. Example 2: A dynamic automation that jumps to different steps mainSteps - name: InstallMsiPackage action: aws:runCommand onFailure: step:PostFailure Automation 1452 User Guide AWS Systems Manager maxAttempts: 2 inputs: InstanceIds: - "{{instanceIds}}" DocumentName: AWS-RunPowerShellScript Parameters: commands: - msiexec /i {{packageName}} nextStep: TestInstall - name: TestInstall action: aws:invokeLambdaFunction maxAttempts: 1 timeoutSeconds: 500 inputs: FunctionName: TestLambdaFunction isEnd: true - name: PostFailure action: aws:invokeLambdaFunction maxAttempts: 1 timeoutSeconds: 500 inputs: FunctionName: PostFailureRecoveryLambdaFunction isEnd: true ... Note Before processing a runbook, the system verifies that the runbook doesn't create an infinite loop. If an infinite loop is detected, Automation returns an error and a circle trace showing which steps create the loop. Creating a dynamic automation that defines critical steps You can specify that a step is critical for the overall success of the automation. If a critical step fails, then Automation reports the status of the automation as Failed, even if one or more steps ran successfully. In the following example, the user identifies the VerifyDependencies step if the InstallMsiPackage step fails (onFailure: step:VerifyDependencies). The user specifies that the InstallMsiPackage step isn't critical (isCritical: false). In this example, if the application failed to install, Automation processes the VerifyDependencies step to determine if one or more dependencies is missing, which therefore caused the application install to fail. Automation 1453 AWS Systems Manager User Guide Example 3: Defining critical steps for the automation --- name: InstallMsiPackage action: aws:runCommand onFailure: step:VerifyDependencies isCritical: false maxAttempts: 2 inputs: InstanceIds: - "{{instanceIds}}" DocumentName: AWS-RunPowerShellScript Parameters: commands: - msiexec /i {{packageName}} nextStep: TestPackage ... Using action outputs as inputs Several automation actions return pre-defined outputs. You can pass these outputs as inputs to later steps in your runbook using the format {{stepName.outputName}}. You can also define custom outputs for automation actions in your runbooks. This allows you to run scripts, or invoke API operations for other AWS services once so you can reuse the values as inputs in later actions. Parameter types in runbooks are static. This means the parameter type can't be changed after it's defined. To define a step output provide the following fields: • Name: (Required) The output name which is used to reference the output value in later steps. • Selector: (Required) The JSONPath expression that is used to determine the output value. • Type: (Optional) The data type of the value returned by the selector field. Valid type values are String, Integer, Boolean, StringList, StringMap, MapList. The default value is String. If the value of an output doesn't match the data type you've specified, Automation tries to convert the data type. For example, if the value returned is an Integer, but the Type specified is String, the final output value is a String value. The following type conversions are supported: • String values can be converted to StringList, Integer and Boolean. • Integer values can be converted to String and StringList. • Boolean values can be converted to String and StringList. Automation 1454 AWS Systems Manager User Guide • StringList, IntegerList, or BooleanList values containing one element can be converted to String, Integer, or Boolean. When using parameters or outputs with automation actions, the data type can't be dynamically changed within an action's input. Here is an example runbook that demonstrates how to define action outputs, and reference the value as input for a later action. The runbooks does the following: • Uses the aws:executeAwsApi action to call the Amazon EC2 DescribeImages API operation to get the name of a specific Windows Server 2016 AMI. It outputs the image ID as ImageId. • Uses the aws:executeAwsApi action to call the Amazon EC2 RunInstances API operation to launch one instance that uses the ImageId from the previous step. It outputs the instance ID as InstanceId. • Uses the aws:waitForAwsResourceProperty action to poll the Amazon EC2 DescribeInstanceStatus API operation to wait for the instance to reach the running state. The action times out in 60 seconds. The step times out if the instance state failed to reach running after 60 seconds of polling. • Uses the aws:assertAwsResourceProperty
systems-manager-ug-422
systems-manager-ug.pdf
422
get the name of a specific Windows Server 2016 AMI. It outputs the image ID as ImageId. • Uses the aws:executeAwsApi action to call the Amazon EC2 RunInstances API operation to launch one instance that uses the ImageId from the previous step. It outputs the instance ID as InstanceId. • Uses the aws:waitForAwsResourceProperty action to poll the Amazon EC2 DescribeInstanceStatus API operation to wait for the instance to reach the running state. The action times out in 60 seconds. The step times out if the instance state failed to reach running after 60 seconds of polling. • Uses the aws:assertAwsResourceProperty action to call the Amazon EC2 DescribeInstanceStatus API operation to assert that the instance is in the running state. The step fails if the instance state isn't running. --- description: Sample runbook using AWS API operations schemaVersion: '0.3' assumeRole: "{{ AutomationAssumeRole }}" parameters: AutomationAssumeRole: type: String description: "(Optional) The ARN of the role that allows Automation to perform the actions on your behalf." default: '' ImageName: type: String description: "(Optional) Image Name to launch EC2 instance with." default: "Windows_Server-2022-English-Full-Base*" mainSteps: - name: getImageId Automation 1455 AWS Systems Manager User Guide action: aws:executeAwsApi inputs: Service: ec2 Api: DescribeImages Filters: - Name: "name" Values: - "{{ ImageName }}" outputs: - Name: ImageId Selector: "$.Images[0].ImageId" Type: "String" - name: launchOneInstance action: aws:executeAwsApi inputs: Service: ec2 Api: RunInstances ImageId: "{{ getImageId.ImageId }}" MaxCount: 1 MinCount: 1 outputs: - Name: InstanceId Selector: "$.Instances[0].InstanceId" Type: "String" - name: waitUntilInstanceStateRunning action: aws:waitForAwsResourceProperty timeoutSeconds: 60 inputs: Service: ec2 Api: DescribeInstanceStatus InstanceIds: - "{{ launchOneInstance.InstanceId }}" PropertySelector: "$.InstanceStatuses[0].InstanceState.Name" DesiredValues: - running - name: assertInstanceStateRunning action: aws:assertAwsResourceProperty inputs: Service: ec2 Api: DescribeInstanceStatus InstanceIds: - "{{ launchOneInstance.InstanceId }}" PropertySelector: "$.InstanceStatuses[0].InstanceState.Name" DesiredValues: Automation 1456 AWS Systems Manager - running outputs: - "launchOneInstance.InstanceId" ... User Guide Each of the previously described automation actions allows you to call a specific API operation by specifying the service namespace, the API operation name, the input parameters, and the output parameters. Inputs are defined by the API operation that you choose. You can view the API operations (also called methods) by choosing a service in the left navigation on the following Services Reference page. Choose a method in the Client section for the service that you want to invoke. For example, all API operations (methods) for Amazon Relational Database Service (Amazon RDS) are listed on the following page: Amazon RDS methods. You can view the schema for each automation action in the following locations: • aws:assertAwsResourceProperty – Assert an AWS resource state or event state • aws:executeAwsApi – Call and run AWS API operations • aws:waitForAwsResourceProperty – Wait on an AWS resource property The schemas include descriptions of the required fields for using each action. Using the Selector/PropertySelector fields Each Automation action requires that you specify either an output Selector (for aws:executeAwsApi) or a PropertySelector (for aws:assertAwsResourceProperty and aws:waitForAwsResourceProperty). These fields are used to process the JSON response from an AWS API operation. These fields use the JSONPath syntax. Here is an example to help illustrate this concept for the aws:executeAwsAPi action. --- mainSteps: - name: getImageId action: aws:executeAwsApi inputs: Service: ec2 Api: DescribeImages Filters: - Name: "name" Values: Automation 1457 AWS Systems Manager User Guide - "{{ ImageName }}" outputs: - Name: ImageId Selector: "$.Images[0].ImageId" Type: "String" ... In the aws:executeAwsApi step getImageId, the automation invokes the DescribeImages API operation and receives a response from ec2. The automation then applies Selector - "$.Images[0].ImageId" to the API response and assigns the selected value to the output ImageId variable. Other steps in the same automation can use the value of ImageId by specifying "{{ getImageId.ImageId }}". Here is an example to help illustrate this concept for the aws:waitForAwsResourceProperty action. --- - name: waitUntilInstanceStateRunning action: aws:waitForAwsResourceProperty # timeout is strongly encouraged for action - aws:waitForAwsResourceProperty timeoutSeconds: 60 inputs: Service: ec2 Api: DescribeInstanceStatus InstanceIds: - "{{ launchOneInstance.InstanceId }}" PropertySelector: "$.InstanceStatuses[0].InstanceState.Name" DesiredValues: - running ... In the aws:waitForAwsResourceProperty step waitUntilInstanceStateRunning, the automation invokes the DescribeInstanceStatus API operation and receives a response from ec2. The automation then applies PropertySelector - "$.InstanceStatuses[0].InstanceState.Name" to the response and checks if the specified returned value matches a value in the DesiredValues list (in this case running). The step repeats the process until the response returns an instance state of running. Automation 1458 AWS Systems Manager Using JSONPath in runbooks User Guide A JSONPath expression is a string beginning with "$." that is used to select one of more components within a JSON element. The following list includes information about JSONPath operators that are supported by Systems Manager Automation: • Dot-notated child (.): Use with a JSON object. This operator selects the value of a specific key. • Deep-scan (..): Use with a JSON element. This operator scans the JSON element level by level and selects a list of values with the specific key. The return type
systems-manager-ug-423
systems-manager-ug.pdf
423
instance state of running. Automation 1458 AWS Systems Manager Using JSONPath in runbooks User Guide A JSONPath expression is a string beginning with "$." that is used to select one of more components within a JSON element. The following list includes information about JSONPath operators that are supported by Systems Manager Automation: • Dot-notated child (.): Use with a JSON object. This operator selects the value of a specific key. • Deep-scan (..): Use with a JSON element. This operator scans the JSON element level by level and selects a list of values with the specific key. The return type of this operator is always a JSON array. In the context of an automation action output type, the operator can be either StringList or MapList. • Array-Index ([ ]): Use with a JSON array. This operator gets the value of a specific index. • Filter ([?(expression)]): Use with a JSON array. This operator filters JSON array values that match the criteria defined in the filter expression. Filter expressions can only use the following operators: ==, !=, >, <, >=, or <=. Combining multiple filter expressions with AND (&&) or OR (||) is not supported. The return type of this operator is always a JSON array. To better understand JSONPath operators, review the following JSON response from the ec2 DescribeInstances API operation. Following this response are several examples that show different results by applying different JSONPath expressions to the response from the DescribeInstances API operation. { "NextToken": "abcdefg", "Reservations": [ { "OwnerId": "123456789012", "ReservationId": "r-abcd12345678910", "Instances": [ { "ImageId": "ami-12345678", "BlockDeviceMappings": [ { "Ebs": { "DeleteOnTermination": true, "Status": "attached", "VolumeId": "vol-000000000000" }, "DeviceName": "/dev/xvda" Automation 1459 AWS Systems Manager User Guide } ], "State": { "Code": 16, "Name": "running" } } ], "Groups": [] }, { "OwnerId": "123456789012", "ReservationId": "r-12345678910abcd", "Instances": [ { "ImageId": "ami-12345678", "BlockDeviceMappings": [ { "Ebs": { "DeleteOnTermination": true, "Status": "attached", "VolumeId": "vol-111111111111" }, "DeviceName": "/dev/xvda" } ], "State": { "Code": 80, "Name": "stopped" } } ], "Groups": [] } ] } JSONPath Example 1: Get a specific String from a JSON response JSONPath: $.Reservations[0].Instances[0].ImageId Returns: Automation 1460 AWS Systems Manager "ami-12345678" Type: String User Guide JSONPath Example 2: Get a specific Boolean from a JSON response JSONPath: $.Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.DeleteOnTermination Returns: true Type: Boolean JSONPath Example 3: Get a specific Integer from a JSON response JSONPath: $.Reservations[0].Instances[0].State.Code Returns: 16 Type: Integer JSONPath Example 4: Deep scan a JSON response, then get all of the values for VolumeId as a StringList JSONPath: $.Reservations..BlockDeviceMappings..VolumeId Returns: [ "vol-000000000000", "vol-111111111111" ] Type: StringList JSONPath Example 5: Get a specific BlockDeviceMappings object as a StringMap JSONPath: Automation 1461 AWS Systems Manager User Guide $.Reservations[0].Instances[0].BlockDeviceMappings[0] Returns: { "Ebs" : { "DeleteOnTermination" : true, "Status" : "attached", "VolumeId" : "vol-000000000000" }, "DeviceName" : "/dev/xvda" } Type: StringMap JSONPath Example 6: Deep scan a JSON response, then get all of the State objects as a MapList JSONPath: $.Reservations..Instances..State Returns: [ { "Code" : 16, "Name" : "running" }, { "Code" : 80, "Name" : "stopped" } ] Type: MapList JSONPath Example 7: Filter for instances in the running state JSONPath: $.Reservations..Instances[?(@.State.Name == 'running')] Returns: [ { "ImageId": "ami-12345678", "BlockDeviceMappings": [ Automation 1462 User Guide AWS Systems Manager { "Ebs": { "DeleteOnTermination": true, "Status": "attached", "VolumeId": "vol-000000000000" }, "DeviceName": "/dev/xvda" } ], "State": { "Code": 16, "Name": "running" } } ] Type: MapList JSONPath Example 8: Return the ImageId of instances which aren't in the running state JSONPath: $.Reservations..Instances[?(@.State.Name != 'running')].ImageId Returns: [ "ami-12345678" ] Type: StringList | String Creating webhook integrations for Automation To send messages using webhooks during an automation, create an integration. Integrations can be invoked during an automation by using the aws:invokeWebhook action in your runbook. If you haven't already created a webhook, see Creating webhooks for integrations. To learn more about the aws:invokeWebhook action, see aws:invokeWebhook – Invoke an Automation webhook integration. As shown in the following procedures, you can create an integration by using either the Systems Manager Automation console or your preferred command line tool. Automation 1463 AWS Systems Manager Creating integrations (console) To create an integration for Automation (console) User Guide 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Automation. 3. Choose the Integrations tab. 4. 5. Select Add integration, and choose Webhook. Enter the required values and any optional values you want to include for the integration. 6. Choose Add to create the integration. Creating integrations (command line) To create an integration using command line tools, you must create the required SecureString parameter for an integration. Automation uses a reserved namespace in Parameter Store, a tool in Systems Manager, to store information about your integration. If you create an integration using the AWS Management Console, Automation handles this process for you. Following the namespace, you must specify the type of integration
systems-manager-ug-424
systems-manager-ug.pdf
424
the Integrations tab. 4. 5. Select Add integration, and choose Webhook. Enter the required values and any optional values you want to include for the integration. 6. Choose Add to create the integration. Creating integrations (command line) To create an integration using command line tools, you must create the required SecureString parameter for an integration. Automation uses a reserved namespace in Parameter Store, a tool in Systems Manager, to store information about your integration. If you create an integration using the AWS Management Console, Automation handles this process for you. Following the namespace, you must specify the type of integration you want to create and then the name of your integration. Currently, Automation supports webhook type integrations. The supported fields for webhook type integrations are as follows: • Description • headers • payload • URL Before you begin If you haven't already, install and configure the AWS Command Line Interface (AWS CLI) or the AWS Tools for PowerShell. For information, see Installing or updating the latest version of the AWS CLI and Installing the AWS Tools for PowerShell. Automation 1464 AWS Systems Manager User Guide To create an integration for Automation (command line) • Run the following commands to create the required SecureString parameter for an integration. Replace each example resource placeholder with your own information. The /d9d01087-4a3f-49e0-b0b4-d568d7826553/ssm/integrations/ webhook/ namespace is reserved in Parameter Store for integrations. The name of your parameter must use this namespace followed by the name of your integration. For example /d9d01087-4a3f-49e0-b0b4-d568d7826553/ssm/integrations/ webhook/myWebhookIntegration. Linux & macOS aws ssm put-parameter \ --name "/d9d01087-4a3f-49e0-b0b4-d568d7826553/ssm/integrations/ webhook/myWebhookIntegration" \ --type "SecureString" \ --data-type "aws:ssm:integration" \ --value '{"description": "My first webhook integration for Automation.", "url": "myWebHookURL"}' Windows aws ssm put-parameter ^ --name "/d9d01087-4a3f-49e0-b0b4-d568d7826553/ssm/integrations/ webhook/myWebhookIntegration" ^ --type "SecureString" ^ --data-type "aws:ssm:integration" ^ --value "{\"description\":\"My first webhook integration for Automation.\", \"url\":\"myWebHookURL\"}" PowerShell Write-SSMParameter ` -Name "/d9d01087-4a3f-49e0-b0b4-d568d7826553/ssm/integrations/ webhook/myWebhookIntegration" ` -Type "SecureString" -DataType "aws:ssm:integration" -Value '{"description": "My first webhook integration for Automation.", "url": "myWebHookURL"}' Automation 1465 AWS Systems Manager User Guide Creating webhooks for integrations When creating webhooks with your provider, note the following: • Protocol must be HTTPS. • Custom request headers are supported. • A default request body can be specified. • The default request body can be overridden when an integration is invoked by using the aws:invokeWebhook action. Handling timeouts in runbooks The timeoutSeconds property is shared by all automation actions. You can use this property to specify the execution timeout value for an action. Further, you can change how an action timing out affects the automation and overall execution status. You can accomplish this by also defining the onFailure and isCritical shared properties for an action. For example, depending on your use case, you might want your automation to continue to a different action and not affect the overall status of the automation if an action times out. In this example, you specify the length of time to wait before the action times out using the timeoutSeconds property. Then you specify the action, or step, the automation should go to if there is a timeout. Specify a value using the format step:step name for the onFailure property rather than the default value of Abort. By default, if an action times out, the automation execution status will be Timed Out. To prevent a timeout from affecting the automation execution status, specify false for the isCritical property. The following example shows how to define the shared properties for an action described in this scenario. YAML - name: verifyImageAvailability action: 'aws:waitForAwsResourceProperty' timeoutSeconds: 600 isCritical: false onFailure: 'step:getCurrentImageState' inputs: Service: ec2 Api: DescribeImages Automation 1466 User Guide AWS Systems Manager ImageIds: - '{{ createImage.newImageId }}' PropertySelector: '$.Images[0].State' DesiredValues: - available nextStep: copyImage JSON { "name": "verifyImageAvailability", "action": "aws:waitForAwsResourceProperty", "timeoutSeconds": 600, "isCritical": false, "onFailure": "step:getCurrentImageState", "inputs": { "Service": "ec2", "Api": "DescribeImages", "ImageIds": [ "{{ createImage.newImageId }}" ], "PropertySelector": "$.Images[0].State", "DesiredValues": [ "available" ] }, "nextStep": "copyImage" } For more information about properties shared by all automation actions, see Properties shared by all actions. Systems Manager Automation runbook reference To help you get started quickly, AWS Systems Manager provides predefined runbooks. These runbooks are maintained by Amazon Web Services, AWS Support, and AWS Config. The runbook reference describes each of the predefined runbooks provided by Systems Manager, Support, and AWS Config. For more information, see Systems Manager Automation runbook reference. Automation 1467 AWS Systems Manager Tutorials User Guide The following tutorials help you to use AWS Systems Manager Automation to address common use cases. These tutorials demonstrate how to use your own runbooks, predefined runbooks provided by Automation, and other Systems Manager tools with other AWS services. Contents • Updating AMIs • Update a Linux AMI • Update a Linux AMI (AWS CLI) • Update a Windows Server AMI • Update a golden AMI using Automation, AWS Lambda, and Parameter Store • Task 1: Create a parameter in
systems-manager-ug-425
systems-manager-ug.pdf
425
and AWS Config. For more information, see Systems Manager Automation runbook reference. Automation 1467 AWS Systems Manager Tutorials User Guide The following tutorials help you to use AWS Systems Manager Automation to address common use cases. These tutorials demonstrate how to use your own runbooks, predefined runbooks provided by Automation, and other Systems Manager tools with other AWS services. Contents • Updating AMIs • Update a Linux AMI • Update a Linux AMI (AWS CLI) • Update a Windows Server AMI • Update a golden AMI using Automation, AWS Lambda, and Parameter Store • Task 1: Create a parameter in Systems Manager Parameter Store • Task 2: Create an IAM role for AWS Lambda • Task 3: Create an AWS Lambda function • Task 4: Create a runbook and patch the AMI • Updating AMIs using Automation and Jenkins • Updating AMIs for Auto Scaling groups • Create the PatchAMIAndUpdateASG runbook • Using AWS Support self-service runbooks • Run the EC2Rescue tool on unreachable instances • How it works • Before you begin • Granting AWSSupport-EC2Rescue permissions to perform actions on your instances • Granting permissions by using IAM policies • Granting permissions by using an AWS CloudFormation template • Running the Automation • Reset passwords and SSH keys on EC2 instances • How it works • Before you begin Automation • Granting AWSSupport-EC2Rescue permissions to perform actions on your instances 1468 • Granting permissions by using IAM policies AWS Systems Manager User Guide • Granting permissions by using an AWS CloudFormation template • Running the Automation • Passing data to Automation using input transformers Updating AMIs The following tutorials explain how to update Amazon Machine Image (AMIs) to include the latest patches. Topics • Update a Linux AMI • Update a Linux AMI (AWS CLI) • Update a Windows Server AMI • Update a golden AMI using Automation, AWS Lambda, and Parameter Store • Updating AMIs using Automation and Jenkins • Updating AMIs for Auto Scaling groups Update a Linux AMI This Systems Manager Automation walkthrough shows you how to use the console or AWS CLI and the AWS-UpdateLinuxAmi runbook to update a Linux AMI with the latest patches of packages that you specify. Automation is a tool in AWS Systems Manager. The AWS-UpdateLinuxAmi runbook also automates the installation of additional site-specific packages and configurations. You can update a variety of Linux distributions using this walkthrough, including Ubuntu Server, CentOS, RHEL, SLES, or Amazon Linux AMIs. For a full list of supported Linux versions, see Patch Manager prerequisites. The AWS-UpdateLinuxAmi runbook allows you to automate image maintenance tasks without having to author the runbook in JSON or YAML. You can use the AWS-UpdateLinuxAmi runbook to perform the following types of tasks. • Upgrade all distribution packages and Amazon software on an Amazon Linux, Red Hat Enterprise Linux, Ubuntu Server, SUSE Linux Enterprise Server, or CentOS Amazon Machine Image (AMI). This is the default runbook behavior. Automation 1469 AWS Systems Manager User Guide • Install AWS Systems Manager SSM Agent on an existing image to enable Systems Manager tools, such as running remote commands using AWS Systems Manager Run Command or software inventory collection using Inventory. • Install additional software packages. Before you begin Before you begin working with runbooks, configure roles and, optionally, EventBridge for Automation. For more information, see Setting up Automation. This walkthrough also requires that you specify the name of an AWS Identity and Access Management (IAM) instance profile. For more information about creating an IAM instance profile, see Configure instance permissions required for Systems Manager. The AWS-UpdateLinuxAmi runbook accepts the following input parameters. Parameter SourceAmiId Type String IamInstanceProfileName String AutomationAssumeRole String Description (Required) The source AMI ID. (Required) The name of the IAM instance profile role you created in Configure instance permissions required for Systems Manager. The instance profile role gives Automation permission to perform actions on your instances, such as running commands or starting and stopping services. The runbook uses only the name of the instance profile role. If you specify the Amazon Resource Name (ARN), the automation fails. (Required) The name of the IAM service role you created Automation 1470 AWS Systems Manager User Guide Parameter Type Description in Setting up Automation. The service role (also called an assume role) gives Automatio n permission to assume your IAM role and perform actions on your behalf. For example, the service role allows Automation to create a new AMI when running the aws:createImage action in a runbook. For this parameter, the complete ARN must be specified. (Optional) The name of the new AMI after it is created. The default name is a system- generated string that includes the source AMI ID, and the creation time and date. (Optional) The type of instance to launch as the workspace host. Instance types vary by region. The default
systems-manager-ug-426
systems-manager-ug.pdf
426
service role (also called an assume role) gives Automatio n permission to assume your IAM role and perform actions on your behalf. For example, the service role allows Automation to create a new AMI when running the aws:createImage action in a runbook. For this parameter, the complete ARN must be specified. (Optional) The name of the new AMI after it is created. The default name is a system- generated string that includes the source AMI ID, and the creation time and date. (Optional) The type of instance to launch as the workspace host. Instance types vary by region. The default type is t2.micro. (Optional) URL of a script to run before updates are applied. Default (\"none\") is to not run a script. (Optional) URL of a script to run after package updates are applied. Default (\"none\") is to not run a script. TargetAmiName String InstanceType String PreUpdateScript String PostUpdateScript String Automation 1471 AWS Systems Manager Parameter IncludePackages Type String ExcludePackages String User Guide Description (Optional) Only update these named packages. By default (\"all\"), all available updates are applied. (Optional) Names of packages to hold back from updates, under all conditions. By default (\"none\"), no package is excluded. Automation Steps The AWS-UpdateLinuxAmi runbook includes the following automation actions, by default. Step 1: launchInstance (aws:runInstances action) This step launches an instance using Amazon Elastic Compute Cloud (Amazon EC2) userdata and an IAM instance profile role. Userdata installs the appropriate SSM Agent, based on the operating system. Installing SSM Agent enables you to utilize Systems Manager tools such as Run Command, State Manager, and Inventory. Step 2: updateOSSoftware (aws:runCommand action) This step runs the following commands on the launched instance: • Downloads an update script from Amazon S3. • Runs an optional pre-update script. • Updates distribution packages and Amazon software. • Runs an optional post-update script. The execution log is stored in the /tmp folder for the user to view later. If you want to upgrade a specific set of packages, you can supply the list using the IncludePackages parameter. When provided, the system attempts to update only these packages and their dependencies. No other updates are performed. By default, when no include packages are specified, the program updates all available packages. Automation 1472 AWS Systems Manager User Guide If you want to exclude upgrading a specific set of packages, you can supply the list to the ExcludePackages parameter. If provided, these packages remain at their current version, independent of any other options specified. By default, when no exclude packages are specified, no packages are excluded. Step 3: stopInstance (aws:changeInstanceState action) This step stops the updated instance. Step 4: createImage (aws:createImage action) This step creates a new AMI with a descriptive name that links it to the source ID and creation time. For example: “AMI Generated by EC2 Automation on {{global:DATE_TIME}} from {{SourceAmiId}}” where DATE_TIME and SourceID represent Automation variables. Step 5: terminateInstance (aws:changeInstanceState action) This step cleans up the automation by terminating the running instance. Output The automation returns the new AMI ID as output. Note By default, when Automation runs the AWS-UpdateLinuxAmi runbook, the system creates a temporary instance in the default VPC (172.30.0.0/16). If you deleted the default VPC, you will receive the following error: VPC not defined 400 To solve this problem, you must make a copy of the AWS-UpdateLinuxAmi runbook and specify a subnet ID. For more information, see VPC not defined 400. To create a patched AMI using Automation (AWS Systems Manager) 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Automation. 3. Choose Execute automation. 4. In the Automation document list, choose AWS-UpdateLinuxAmi. Automation 1473 AWS Systems Manager User Guide 5. In the Document details section, verify that Document version is set to Default version at runtime. 6. Choose Next. 7. 8. In the Execution mode section, choose Simple Execution. In the Input parameters section, enter the information you collected in the Before you begin section. 9. Choose Execute. The console displays the status of the Automation execution. After the automation finishes, launch a test instance from the updated AMI to verify changes. Note If any step in the automation fails, information about the failure is listed on the Automation Executions page. The automation is designed to terminate the temporary instance after successfully completing all tasks. If a step fails, the system might not terminate the instance. So if a step fails, manually terminate the temporary instance. Update a Linux AMI (AWS CLI) This AWS Systems Manager Automation walkthrough shows you how to use the AWS Command Line Interface (AWS CLI) and the Systems Manager AWS-UpdateLinuxAmi runbook to automatically patch a Linux Amazon Machine Image (AMI) with the latest versions of packages that you specify. Automation is a tool in AWS Systems Manager. The AWS-UpdateLinuxAmi runbook also automates
systems-manager-ug-427
systems-manager-ug.pdf
427
the Automation Executions page. The automation is designed to terminate the temporary instance after successfully completing all tasks. If a step fails, the system might not terminate the instance. So if a step fails, manually terminate the temporary instance. Update a Linux AMI (AWS CLI) This AWS Systems Manager Automation walkthrough shows you how to use the AWS Command Line Interface (AWS CLI) and the Systems Manager AWS-UpdateLinuxAmi runbook to automatically patch a Linux Amazon Machine Image (AMI) with the latest versions of packages that you specify. Automation is a tool in AWS Systems Manager. The AWS-UpdateLinuxAmi runbook also automates the installation of additional site-specific packages and configurations. You can update a variety of Linux distributions using this walkthrough, including Ubuntu Server, CentOS, RHEL, SLES, or Amazon Linux AMIs. For a full list of supported Linux versions, see Patch Manager prerequisites. The AWS-UpdateLinuxAmi runbook enables you to automate image-maintenance tasks without having to author the runbook in JSON or YAML. You can use the AWS-UpdateLinuxAmi runbook to perform the following types of tasks. • Upgrade all distribution packages and Amazon software on an Amazon Linux, Red Hat Enterprise Linux, Ubuntu Server, SLES, or Cent OS Amazon Machine Image (AMI). This is the default runbook behavior. Automation 1474 AWS Systems Manager User Guide • Install AWS Systems Manager SSM Agent on an existing image to enable Systems Manager capabilities, such as running remote commands using AWS Systems Manager Run Command or software inventory collection using Inventory. • Install additional software packages. Before you begin Before you begin working with runbooks, configure roles and, optionally, EventBridge for Automation. For more information, see Setting up Automation. This walkthrough also requires that you specify the name of an AWS Identity and Access Management (IAM) instance profile. For more information about creating an IAM instance profile, see Configure instance permissions required for Systems Manager. The AWS-UpdateLinuxAmi runbook accepts the following input parameters. Parameter SourceAmiId Type String IamInstanceProfileName String Description (Required) The source AMI ID. You can automatically reference the latest ID of an Amazon EC2 AMI for Linux by using a AWS Systems Manager Parameter Store public parameter. For more information, see Query for the latest Amazon Linux AMI IDs using AWS Systems Manager Parameter Store. (Required) The name of the IAM instance profile role you created in Configure instance permissions required for Systems Manager. The instance profile role gives Automation permission to perform actions on your Automation 1475 AWS Systems Manager User Guide Parameter Type Description AutomationAssumeRole String TargetAmiName String InstanceType String instances, such as running commands or starting and stopping services. The runbook uses only the name of the instance profile role. (Required) The name of the IAM service role you created in Setting up Automation. The service role (also called an assume role) gives Automatio n permission to assume your IAM role and perform actions on your behalf. For example, the service role allows Automation to create a new AMI when running the aws:createImage action in a runbook. For this parameter, the complete ARN must be specified. (Optional) The name of the new AMI after it is created. The default name is a system- generated string that includes the source AMI ID, and the creation time and date. (Optional) The type of instance to launch as the workspace host. Instance types vary by Region. The default type is t2.micro. Automation 1476 AWS Systems Manager Parameter PreUpdateScript Type String PostUpdateScript String IncludePackages String ExcludePackages String User Guide Description (Optional) URL of a script to run before updates are applied. Default (\"none\") is to not run a script. (Optional) URL of a script to run after package updates are applied. Default (\"none\") is to not run a script. (Optional) Only update these named packages. By default (\"all\"), all available updates are applied. (Optional) Names of packages to hold back from updates, under all conditions. By default (\"none\"), no package is excluded. Automation Steps The AWS-UpdateLinuxAmi runbook includes the following steps, by default. Step 1: launchInstance (aws:runInstances action) This step launches an instance using Amazon Elastic Compute Cloud (Amazon EC2) user data and an IAM instance profile role. User data installs the appropriate SSM Agent, based on the operating system. Installing SSM Agent enables you to utilize Systems Manager tools such as Run Command, State Manager, and Inventory. Step 2: updateOSSoftware (aws:runCommand action) This step runs the following commands on the launched instance: • Downloads an update script from Amazon Simple Storage Service (Amazon S3). • Runs an optional pre-update script. Automation 1477 AWS Systems Manager User Guide • Updates distribution packages and Amazon software. • Runs an optional post-update script. The execution log is stored in the /tmp folder for the user to view later. If you want to upgrade a specific set of packages, you can supply the list using the IncludePackages parameter.
systems-manager-ug-428
systems-manager-ug.pdf
428
to utilize Systems Manager tools such as Run Command, State Manager, and Inventory. Step 2: updateOSSoftware (aws:runCommand action) This step runs the following commands on the launched instance: • Downloads an update script from Amazon Simple Storage Service (Amazon S3). • Runs an optional pre-update script. Automation 1477 AWS Systems Manager User Guide • Updates distribution packages and Amazon software. • Runs an optional post-update script. The execution log is stored in the /tmp folder for the user to view later. If you want to upgrade a specific set of packages, you can supply the list using the IncludePackages parameter. When provided, the system attempts to update only these packages and their dependencies. No other updates are performed. By default, when no include packages are specified, the program updates all available packages. If you want to exclude upgrading a specific set of packages, you can supply the list to the ExcludePackages parameter. If provided, these packages remain at their current version, independent of any other options specified. By default, when no exclude packages are specified, no packages are excluded. Step 3: stopInstance (aws:changeInstanceState action) This step stops the updated instance. Step 4: createImage (aws:createImage action) This step creates a new AMI with a descriptive name that links it to the source ID and creation time. For example: “AMI Generated by EC2 Automation on {{global:DATE_TIME}} from {{SourceAmiId}}” where DATE_TIME and SourceID represent Automation variables. Step 5: terminateInstance (aws:changeInstanceState action) This step cleans up the automation by terminating the running instance. Output The automation returns the new AMI ID as output. Note By default, when Automation runs the AWS-UpdateLinuxAmi runbook, the system creates a temporary instance in the default VPC (172.30.0.0/16). If you deleted the default VPC, you will receive the following error: VPC not defined 400 To solve this problem, you must make a copy of the AWS-UpdateLinuxAmi runbook and specify a subnet ID. For more information, see VPC not defined 400. Automation 1478 AWS Systems Manager User Guide To create a patched AMI using Automation 1. Install and configure the AWS Command Line Interface (AWS CLI), if you haven't already. For information, see Installing or updating the latest version of the AWS CLI. 2. Run the following command to run the AWS-UpdateLinuxAmi runbook. Replace each example resource placeholder with your own information. aws ssm start-automation-execution \ --document-name "AWS-UpdateLinuxAmi" \ --parameters \ SourceAmiId=AMI ID, \ IamInstanceProfileName=IAM instance profile, \ AutomationAssumeRole='arn:aws:iam:: {{global:ACCOUNT_ID}}:role/AutomationServiceRole' The command returns an execution ID. Copy this ID to the clipboard. You will use this ID to view the status of the automation. { "AutomationExecutionId": "automation execution ID" } 3. To view the automation using the AWS CLI, run the following command: aws ssm describe-automation-executions 4. To view details about the automation progress, run the following command. Replace automation execution ID with your own information. aws ssm get-automation-execution --automation-execution-id automation execution ID The update process can take 30 minutes or more to complete. Note You can also monitor the status of the automation in the console. In the list, choose the automation you just ran and then choose the Steps tab. This tab shows you the status of the automation actions. Automation 1479 AWS Systems Manager User Guide After the automation finishes, launch a test instance from the updated AMI to verify changes. Note If any step in the automation fails, information about the failure is listed on the Automation Executions page. The automation is designed to terminate the temporary instance after successfully completing all tasks. If a step fails, the system might not terminate the instance. So if a step fails, manually terminate the temporary instance. Update a Windows Server AMI The AWS-UpdateWindowsAmi runbook enables you to automate image maintenance tasks on your Amazon Windows Amazon Machine Image (AMI) without having to author the runbook in JSON or YAML. This runbook is supported for Windows Server 2008 R2 or later. You can use the AWS-UpdateWindowsAmi runbook to perform the following types of tasks. • Install all Windows updates and upgrade Amazon software (default behavior). • Install specific Windows updates and upgrade Amazon software. • Customize an AMI using your scripts. Before you begin Before you begin working with runbooks, configure roles for Automation to add an iam:PassRole policy that references the ARN of the instance profile you want to grant access to. Optionally, configure Amazon EventBridge for Automation, a tool in AWS Systems Manager. For more information, see Setting up Automation. This walkthrough also requires that you specify the name of an AWS Identity and Access Management (IAM) instance profile. For more information about creating an IAM instance profile, see Configure instance permissions required for Systems Manager. Note Updates to AWS Systems Manager SSM Agent are typically rolled out to different regions at different times. When you customize or update an AMI, use only source AMIs published for
systems-manager-ug-429
systems-manager-ug.pdf
429
that references the ARN of the instance profile you want to grant access to. Optionally, configure Amazon EventBridge for Automation, a tool in AWS Systems Manager. For more information, see Setting up Automation. This walkthrough also requires that you specify the name of an AWS Identity and Access Management (IAM) instance profile. For more information about creating an IAM instance profile, see Configure instance permissions required for Systems Manager. Note Updates to AWS Systems Manager SSM Agent are typically rolled out to different regions at different times. When you customize or update an AMI, use only source AMIs published for the region that you are working in. This will ensure that you are working with the latest SSM Agent released for that region and avoid compatibility issues. Automation 1480 AWS Systems Manager User Guide The AWS-UpdateWindowsAmi runbook accepts the following input parameters. Parameter SourceAmiId Type String SubnetId String IamInstanceProfileName String AutomationAssumeRole String Description (Required) The source AMI ID. You can automatically reference the latest Windows Server AMI ID by using a Systems Manager Parameter Store public parameter. For more information, see Query for the latest Windows AMI IDs using AWS Systems Manager Parameter Store. (Optional) The subnet you want to launch the temporary instance into. You must specify a value for this parameter if you've deleted your default VPC. (Required) The name of the IAM instance profile role you created in Configure instance permissions required for Systems Manager. The instance profile role gives Automation permission to perform actions on your instances, such as running commands or starting and stopping services. The runbook uses only the name of the instance profile role. (Required) The name of the IAM service role you created Automation 1481 AWS Systems Manager User Guide Parameter Type Description in Setting up Automation. The service role (also called an assume role) gives Automatio n permission to assume your IAM role and perform actions on your behalf. For example, the service role allows Automation to create a new AMI when running the aws:createImage action in a runbook. For this parameter, the complete ARN must be specified. (Optional) The name of the new AMI after it is created. The default name is a system- generated string that includes the source AMI ID, and the creation time and date. (Optional) The type of instance to launch as the workspace host. Instance types vary by region. The default type is t2.medium. (Optional) A script to run before updating the AMI. Enter a script in the runbook or at runtime as a parameter. (Optional) A script to run after updating the AMI. Enter a script in the runbook or at runtime as a parameter. TargetAmiName String InstanceType String PreUpdateScript String PostUpdateScript String Automation 1482 AWS Systems Manager Parameter IncludeKbs Type String ExcludeKbs String Categories String User Guide Description (Optional) Specify one or more Microsoft Knowledge Base (KB) article IDs to include. You can install multiple IDs using comma-sep arated values. Valid formats: KB9876543 or 9876543. (Optional) Specify one or more Microsoft Knowledge Base (KB) article IDs to exclude. You can exclude multiple IDs using comma-sep arated values. Valid formats: KB9876543 or 9876543. (Optional)Specify one or more update categories. You can filter categories using comma-separated values. Options: Critical Update, Security Update, Definitio n Update, Update Rollup, Service Pack, Tool, Update, or Driver. Valid formats include a single entry, for example: Critical Update. Or, you can specify a comma separated list: Critical Update,Security Update,Definition Update. Automation 1483 AWS Systems Manager Parameter SeverityLevels Type String User Guide Description (Optional) Specify one or more MSRC severity levels associated with an update. You can filter severity levels using comma-separated values. Options: Critical, Important, Low, Moderate or Unspecified. Valid formats include a single entry, for example: Critical. Or, you can specify a comma separated list: Critical,Important,Low. Automation Steps The AWS-UpdateWindowsAmi runbook includes the following steps, by default. Step 1: launchInstance (aws:runInstances action) This step launches an instance with an IAM instance profile role from the specified SourceAmiID. Step 2: runPreUpdateScript (aws:runCommand action) This step enables you to specify a script as a string that runs before updates are installed. Step 3: updateEC2Config (aws:runCommand action) This step uses the AWS-InstallPowerShellModule runbook to download an AWS public PowerShell module. Systems Manager verifies the integrity of the module by using an SHA-256 hash. Systems Manager then checks the operating system to determine whether to update EC2Config or EC2Launch. EC2Config runs on Windows Server 2008 R2 through Windows Server 2012 R2. EC2Launch runs on Windows Server 2016. Step 4: updateSSMAgent (aws:runCommand action) This step updates SSM Agent by using the AWS-UpdateSSMAgent runbook. Automation 1484 AWS Systems Manager User Guide Step 5: updateAWSPVDriver (aws:runCommand action) This step updates AWS PV drivers by using the AWS-ConfigureAWSPackage runbook. Step 6: updateAwsEnaNetworkDriver (aws:runCommand action) This step updates AWS ENA Network drivers by using the AWS-ConfigureAWSPackage runbook. Step
systems-manager-ug-430
systems-manager-ug.pdf
430
verifies the integrity of the module by using an SHA-256 hash. Systems Manager then checks the operating system to determine whether to update EC2Config or EC2Launch. EC2Config runs on Windows Server 2008 R2 through Windows Server 2012 R2. EC2Launch runs on Windows Server 2016. Step 4: updateSSMAgent (aws:runCommand action) This step updates SSM Agent by using the AWS-UpdateSSMAgent runbook. Automation 1484 AWS Systems Manager User Guide Step 5: updateAWSPVDriver (aws:runCommand action) This step updates AWS PV drivers by using the AWS-ConfigureAWSPackage runbook. Step 6: updateAwsEnaNetworkDriver (aws:runCommand action) This step updates AWS ENA Network drivers by using the AWS-ConfigureAWSPackage runbook. Step 7: installWindowsUpdates (aws:runCommand action) This step installs Windows updates by using the AWS-InstallWindowsUpdates runbook. By default, Systems Manager searches for and installs all missing updates. You can change the default behavior by specifying one of the following parameters: IncludeKbs, ExcludeKbs, Categories, or SeverityLevels. Step 8: runPostUpdateScript (aws:runCommand action) This step enables you to specify a script as a string that runs after the updates have been installed. Step 9: runSysprepGeneralize (aws:runCommand action) This step uses the AWS-InstallPowerShellModule runbook to download an AWS public PowerShell module. Systems Manager verifies the integrity of the module by using an SHA-256 hash. Systems Manager then runs sysprep using AWS-supported methods for either EC2Launch (Windows Server 2016) or EC2Config (Windows Server 2008 R2 through 2012 R2). Step 10: stopInstance (aws:changeInstanceState action) This step stops the updated instance. Step 11: createImage (aws:createImage action) This step creates a new AMI with a descriptive name that links it to the source ID and creation time. For example: “AMI Generated by EC2 Automation on {{global:DATE_TIME}} from {{SourceAmiId}}” where DATE_TIME and SourceID represent Automation variables. Step 12: TerminateInstance (aws:changeInstanceState action) This step cleans up the automation by terminating the running instance. Output This section enables you to designate the outputs of various steps or values of any parameter as the Automation output. By default, the output is the ID of the updated Windows AMI created by the automation. Automation 1485 AWS Systems Manager Note User Guide By default, when Automation runs the AWS-UpdateWindowsAmi runbook and creates a temporary instance, the system uses the default VPC (172.30.0.0/16). If you deleted the default VPC, you will receive the following error: VPC not defined 400 To solve this problem, you must make a copy of the AWS-UpdateWindowsAmi runbook and specify a subnet ID. For more information, see VPC not defined 400. To create a patched Windows AMI by using Automation 1. Install and configure the AWS Command Line Interface (AWS CLI), if you haven't already. For information, see Installing or updating the latest version of the AWS CLI. 2. Run the following command to run the AWS-UpdateWindowsAmi runbook. Replace each example resource placeholder with your own information. The example command below uses a recent Amazon EC2 AMI to minimize the number of patches that need to be applied. If you run this command more than once, you must specify a unique value for targetAMIname. AMI names must be unique. aws ssm start-automation-execution \ --document-name="AWS-UpdateWindowsAmi" \ --parameters SourceAmiId='AMI ID',IamInstanceProfileName='IAM instance profile',AutomationAssumeRole='arn:aws:iam:: {{global:ACCOUNT_ID}}:role/AutomationServiceRole' The command returns an execution ID. Copy this ID to the clipboard. You will use this ID to view the status of the automation. { "AutomationExecutionId": "automation execution ID" } 3. To view the automation using the AWS CLI, run the following command: aws ssm describe-automation-executions 4. To view details about the automation progress, run the following command. Automation 1486 AWS Systems Manager User Guide aws ssm get-automation-execution --automation-execution-id automation execution ID Note Depending on the number of patches applied, the Windows patching process run in this sample automation can take 30 minutes or more to complete. Update a golden AMI using Automation, AWS Lambda, and Parameter Store The following example uses the model where an organization maintains and periodically patches their own, proprietary AMIs rather than building from Amazon Elastic Compute Cloud (Amazon EC2) AMIs. The following procedure shows how to automatically apply operating system (OS) patches to an AMI that is already considered to be the most up-to-date or latest AMI. In the example, the default value of the parameter SourceAmiId is defined by a AWS Systems Manager Parameter Store parameter called latestAmi. The value of latestAmi is updated by an AWS Lambda function invoked at the end of the automation. As a result of this Automation process, the time and effort spent patching AMIs is minimized because patching is always applied to the most up-to-date AMI. Parameter Store and Automation are tools of AWS Systems Manager. Before you begin Configure Automation roles and, optionally, Amazon EventBridge for Automation. For more information, see Setting up Automation. Contents • Task 1: Create a parameter in Systems Manager Parameter Store • Task 2: Create an IAM role for AWS Lambda • Task 3: Create an AWS Lambda function • Task 4: Create
systems-manager-ug-431
systems-manager-ug.pdf
431
an AWS Lambda function invoked at the end of the automation. As a result of this Automation process, the time and effort spent patching AMIs is minimized because patching is always applied to the most up-to-date AMI. Parameter Store and Automation are tools of AWS Systems Manager. Before you begin Configure Automation roles and, optionally, Amazon EventBridge for Automation. For more information, see Setting up Automation. Contents • Task 1: Create a parameter in Systems Manager Parameter Store • Task 2: Create an IAM role for AWS Lambda • Task 3: Create an AWS Lambda function • Task 4: Create a runbook and patch the AMI Task 1: Create a parameter in Systems Manager Parameter Store Create a string parameter in Parameter Store that uses the following information: Automation 1487 AWS Systems Manager • Name: latestAmi. • Value: An AMI ID. For example: ami-188d6e0e. User Guide For information about how to create a Parameter Store string parameter, see Creating Parameter Store parameters in Systems Manager. Task 2: Create an IAM role for AWS Lambda Use the following procedure to create an IAM service role for AWS Lambda. These policies give Lambda permission to update the value of the latestAmi parameter using a Lambda function and Systems Manager. To create an IAM service role for Lambda 1. Sign in to the AWS Management Console and open the IAM console at https:// console.aws.amazon.com/iam/. 2. In the navigation pane, choose Policies, and then choose Create policy. 3. Choose the JSON tab. 4. Replace the default contents with the following policy. Replace each example resource placeholder with your own information. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "logs:CreateLogGroup", "Resource": "arn:aws:logs:region:123456789012:*" }, { "Effect": "Allow", "Action": [ "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": [ "arn:aws:logs:region:123456789012:log-group:/aws/lambda/function name:*" ] } Automation 1488 AWS Systems Manager ] } 5. Choose Next: Tags. User Guide 6. (Optional) Add one or more tag-key value pairs to organize, track, or control access for this policy. 7. Choose Next: Review. 8. On the Review policy page, for Name, enter a name for the inline policy, such as amiLambda. 9. Choose Create policy. 10. Repeat steps 2 and 3. 11. Paste the following policy. Replace each example resource placeholder with your own information. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ssm:PutParameter", "Resource": "arn:aws:ssm:region:123456789012:parameter/latestAmi" }, { "Effect": "Allow", "Action": "ssm:DescribeParameters", "Resource": "*" } ] } 12. Choose Next: Tags. 13. (Optional) Add one or more tag-key value pairs to organize, track, or control access for this policy. 14. Choose Next: Review. 15. On the Review policy page, for Name, enter a name for the inline policy, such as amiParameter. 16. Choose Create policy. 17. In the navigation pane, choose Roles, and then choose Create role. 18. Immediately under Use case, choose Lambda, and then choose Next. Automation 1489 AWS Systems Manager User Guide 19. On the Add permissions page, use the Search field to locate the two policies you created earlier. 20. Select the check box next to the policies, and then choose Next. 21. For Role name, enter a name for your new role, such as lambda-ssm-role or another name that you prefer. Note Because various entities might reference the role, you cannot change the name of the role after it has been created. 22. (Optional) Add one or more tag key-value pairs to organize, track, or control access for this role, and then choose Create role. Task 3: Create an AWS Lambda function Use the following procedure to create a Lambda function that automatically updates the value of the latestAmi parameter. To create a Lambda function 1. Sign in to the AWS Management Console and open the AWS Lambda console at https:// console.aws.amazon.com/lambda/. 2. Choose Create function. 3. On the Create function page, choose Author from scratch. 4. 5. 6. For Function name, enter Automation-UpdateSsmParam. For Runtime, choose Python 3.8. For Architecture, select the type of computer processor for Lambda to use to run the function, x86_64 or arm64, 7. In the Permissions section, expand Change default execution role. 8. Choose Use an existing role, and then choose the service role for Lambda that you created in Task 2. 9. Choose Create function. 10. In the Code source area, on the lambda_function tab, delete the pre-populated code in the field, and then paste the following code sample. Automation 1490 AWS Systems Manager User Guide from __future__ import print_function import json import boto3 print('Loading function') #Updates an SSM parameter #Expects parameterName, parameterValue def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) # get SSM client client = boto3.client('ssm') #confirm parameter exists before updating it response = client.describe_parameters( Filters=[ { 'Key': 'Name', 'Values': [ event['parameterName'] ] }, ] ) if not response['Parameters']: print('No such parameter') return 'SSM parameter not found.' #if parameter has a Description field, update it PLUS the Value if
systems-manager-ug-432
systems-manager-ug.pdf
432
the lambda_function tab, delete the pre-populated code in the field, and then paste the following code sample. Automation 1490 AWS Systems Manager User Guide from __future__ import print_function import json import boto3 print('Loading function') #Updates an SSM parameter #Expects parameterName, parameterValue def lambda_handler(event, context): print("Received event: " + json.dumps(event, indent=2)) # get SSM client client = boto3.client('ssm') #confirm parameter exists before updating it response = client.describe_parameters( Filters=[ { 'Key': 'Name', 'Values': [ event['parameterName'] ] }, ] ) if not response['Parameters']: print('No such parameter') return 'SSM parameter not found.' #if parameter has a Description field, update it PLUS the Value if 'Description' in response['Parameters'][0]: description = response['Parameters'][0]['Description'] response = client.put_parameter( Name=event['parameterName'], Value=event['parameterValue'], Description=description, Type='String', Overwrite=True ) #otherwise just update Value Automation 1491 AWS Systems Manager else: response = client.put_parameter( Name=event['parameterName'], Value=event['parameterValue'], Type='String', Overwrite=True ) User Guide responseString = 'Updated parameter %s with value %s.' % (event['parameterName'], event['parameterValue']) return responseString 11. Choose File, Save. 12. To test the Lambda function, from the Test menu, choose Configure test event. 13. For Event name, enter a name for the test event, such as MyTestEvent. 14. Replace the existing text with the following JSON. Replace AMI ID with your own information to set your latestAmi parameter value. { "parameterName":"latestAmi", "parameterValue":"AMI ID" } 15. Choose Save. 16. Choose Test to test the function. On the Execution result tab, the status should be reported as Succeeded, along with other details about the update. Task 4: Create a runbook and patch the AMI Use the following procedure to create and run a runbook that patches the AMI you specified for the latestAmi parameter. After the automation completes, the value of latestAmi is updated with the ID of the newly-patched AMI. Subsequent automations use the AMI created by the previous execution. To create and run the runbook 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Documents. Automation 1492 AWS Systems Manager User Guide 3. 4. For Create document, choose Automation. For Name, enter UpdateMyLatestWindowsAmi. 5. Choose the Editor tab, and then choose Edit. 6. Choose OK when prompted. 7. In the Document editor field, replace the default content with the following YAML sample runbook content. --- description: Systems Manager Automation Demo - Patch AMI and Update ASG schemaVersion: '0.3' assumeRole: '{{ AutomationAssumeRole }}' parameters: AutomationAssumeRole: type: String description: '(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to execute this document.' default: '' SourceAMI: type: String description: The ID of the AMI you want to patch. default: '{{ ssm:latestAmi }}' SubnetId: type: String description: The ID of the subnet where the instance from the SourceAMI parameter is launched. SecurityGroupIds: type: StringList description: The IDs of the security groups to associate with the instance that's launched from the SourceAMI parameter. NewAMI: type: String description: The name of of newly patched AMI. default: 'patchedAMI-{{global:DATE_TIME}}' InstanceProfile: type: String description: The name of the IAM instance profile you want the source instance to use. SnapshotId: type: String Automation 1493 AWS Systems Manager User Guide description: (Optional) The snapshot ID to use to retrieve a patch baseline snapshot. default: '' RebootOption: type: String description: '(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non- compliant until a subsequent reboot and scan.' allowedValues: - NoReboot - RebootIfNeeded default: RebootIfNeeded Operation: type: String description: (Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline. allowedValues: - Install - Scan default: Install mainSteps: - name: startInstances action: 'aws:runInstances' timeoutSeconds: 1200 maxAttempts: 1 onFailure: Abort inputs: ImageId: '{{ SourceAMI }}' InstanceType: m5.large MinInstanceCount: 1 MaxInstanceCount: 1 IamInstanceProfileName: '{{ InstanceProfile }}' SubnetId: '{{ SubnetId }}' SecurityGroupIds: '{{ SecurityGroupIds }}' - name: verifyInstanceManaged action: 'aws:waitForAwsResourceProperty' timeoutSeconds: 600 inputs: Service: ssm Api: DescribeInstanceInformation InstanceInformationFilterList: - key: InstanceIds valueSet: Automation 1494 AWS Systems Manager User Guide - '{{ startInstances.InstanceIds }}' PropertySelector: '$.InstanceInformationList[0].PingStatus' DesiredValues: - Online onFailure: 'step:terminateInstance' - name: installPatches action: 'aws:runCommand' timeoutSeconds: 7200 onFailure: Abort inputs: DocumentName: AWS-RunPatchBaseline Parameters: SnapshotId: '{{SnapshotId}}' RebootOption: '{{RebootOption}}' Operation: '{{Operation}}' InstanceIds: - '{{ startInstances.InstanceIds }}' - name: stopInstance action: 'aws:changeInstanceState' maxAttempts: 1 onFailure: Continue inputs: InstanceIds: - '{{ startInstances.InstanceIds }}' DesiredState: stopped - name: createImage action: 'aws:createImage' maxAttempts: 1 onFailure: Continue inputs: InstanceId: '{{ startInstances.InstanceIds }}' ImageName: '{{ NewAMI }}' NoReboot: false ImageDescription: Patched AMI created by Automation - name: terminateInstance action: 'aws:changeInstanceState' maxAttempts: 1 onFailure: Continue inputs: InstanceIds: - '{{ startInstances.InstanceIds }}' DesiredState: terminated - name: updateSsmParam action: aws:invokeLambdaFunction Automation 1495 AWS Systems Manager User Guide timeoutSeconds: 1200 maxAttempts: 1 onFailure: Abort inputs: FunctionName: Automation-UpdateSsmParam Payload: '{"parameterName":"latestAmi", "parameterValue":"{{createImage.ImageId}}"}' outputs: - createImage.ImageId 8.
systems-manager-ug-433
systems-manager-ug.pdf
433
Parameters: SnapshotId: '{{SnapshotId}}' RebootOption: '{{RebootOption}}' Operation: '{{Operation}}' InstanceIds: - '{{ startInstances.InstanceIds }}' - name: stopInstance action: 'aws:changeInstanceState' maxAttempts: 1 onFailure: Continue inputs: InstanceIds: - '{{ startInstances.InstanceIds }}' DesiredState: stopped - name: createImage action: 'aws:createImage' maxAttempts: 1 onFailure: Continue inputs: InstanceId: '{{ startInstances.InstanceIds }}' ImageName: '{{ NewAMI }}' NoReboot: false ImageDescription: Patched AMI created by Automation - name: terminateInstance action: 'aws:changeInstanceState' maxAttempts: 1 onFailure: Continue inputs: InstanceIds: - '{{ startInstances.InstanceIds }}' DesiredState: terminated - name: updateSsmParam action: aws:invokeLambdaFunction Automation 1495 AWS Systems Manager User Guide timeoutSeconds: 1200 maxAttempts: 1 onFailure: Abort inputs: FunctionName: Automation-UpdateSsmParam Payload: '{"parameterName":"latestAmi", "parameterValue":"{{createImage.ImageId}}"}' outputs: - createImage.ImageId 8. Choose Create automation. 9. In the navigation pane, choose Automation, and then choose Execute automation. 10. In the Choose document page, choose the Owned by me tab. 11. Search for the UpdateMyLatestWindowsAmi runbook, and select the button in the UpdateMyLatestWindowsAmi card. 12. Choose Next. 13. Choose Simple execution. 14. Specify values for the input parameters. 15. Choose Execute. 16. After the automation completes, choose Parameter Store in the navigation pane and confirm that the new value for latestAmi matches the value returned by the automation. You can also verify the new AMI ID matches the Automation output in the AMIs section of the Amazon EC2 console. Updating AMIs using Automation and Jenkins If your organization uses Jenkins software in a CI/CD pipeline, you can add Automation as a post- build step to pre-install application releases into Amazon Machine Images (AMIs). Automation is a tool in AWS Systems Manager. You can also use the Jenkins scheduling feature to call Automation and create your own operating system (OS) patching cadence. The example below shows how to invoke Automation from a Jenkins server that is running either on-premises or in Amazon Elastic Compute Cloud (Amazon EC2). For authentication, the Jenkins server uses AWS credentials based on an IAM policy that you create in the example and attach to your instance profile. Automation 1496 AWS Systems Manager Note User Guide Be sure to follow Jenkins security best practices when configuring your instance. Before you begin Complete the following tasks before you configure Automation with Jenkins: • Complete the Update a golden AMI using Automation, AWS Lambda, and Parameter Store example. The following example uses the UpdateMyLatestWindowsAmi runbook created in that example. • Configure IAM roles for Automation. Systems Manager requires an instance profile role and a service role ARN to process automations. For more information, see Setting up Automation. To create an IAM policy for the Jenkins server 1. Sign in to the AWS Management Console and open the IAM console at https:// console.aws.amazon.com/iam/. 2. In the navigation pane, choose Policies, and then choose Create policy. 3. Choose the JSON tab. 4. Replace each example resource placeholder with your own information. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ssm:StartAutomationExecution", "Resource": [ "arn:aws:ssm:region:account ID:document/ UpdateMyLatestWindowsAmi", "arn:aws:ssm:region:account ID:automation-definition/ UpdateMyLatestWindowsAmi:$DEFAULT" ] } ] } Automation 1497 AWS Systems Manager 5. Choose Review policy. User Guide 6. On the Review policy page, for Name, enter a name for the inline policy, such as JenkinsPolicy. 7. Choose Create policy. 8. In the navigation pane, choose Roles. 9. Choose the instance profile that's attached to your Jenkins server. 10. In the Permissions tab, select Add permissions and choose Attach policies. 11. In the Other permissions policies section, enter the name of policy you created in the previous steps. For example, JenkinsPolicy. 12. Select the check box next to your policy, and choose Attach policies. Use the following procedure to configure the AWS CLI on your Jenkins server. To configure the Jenkins server for Automation 1. Connect to your Jenkins server on port 8080 using your preferred browser to access the management interface. 2. Enter the password found in /var/lib/jenkins/secrets/initialAdminPassword. To display your password, run the following command. sudo cat /var/lib/jenkins/secrets/initialAdminPassword 3. The Jenkins installation script directs you to the Customize Jenkins page. Select Install suggested plugins. 4. Once the installation is complete, choose Administrator Credentials, select Save Credentials, and then select Start Using Jenkins. 5. In the left navigation pane, choose Manage Jenkins, and then choose Manage Plugins. 6. Choose the Available tab, and then enter Amazon EC2 plugin. 7. Select the check box for Amazon EC2 plugin, and then select Install without restart. 8. When the installation completes, select Go back to the top page. 9. Choose Manage Jenkins, and then choose Manage nodes and clouds. 10. In the Configure Clouds section, select Add a new cloud, and then choose Amazon EC2. 11. Enter your information in the remaining fields. Make sure you select the Use EC2 instance profile to obtain credentials option. Automation 1498 AWS Systems Manager User Guide Use the following procedure to configure your Jenkins project to invoke Automation. To configure your Jenkins server to invoke Automation 1. Open the Jenkins console in a
systems-manager-ug-434
systems-manager-ug.pdf
434
and then select Install without restart. 8. When the installation completes, select Go back to the top page. 9. Choose Manage Jenkins, and then choose Manage nodes and clouds. 10. In the Configure Clouds section, select Add a new cloud, and then choose Amazon EC2. 11. Enter your information in the remaining fields. Make sure you select the Use EC2 instance profile to obtain credentials option. Automation 1498 AWS Systems Manager User Guide Use the following procedure to configure your Jenkins project to invoke Automation. To configure your Jenkins server to invoke Automation 1. Open the Jenkins console in a web browser. 2. Choose the project that you want to configure with Automation, and then choose Configure. 3. On the Build tab, choose Add Build Step. 4. Choose Execute shell or Execute Windows batch command (depending on your operating system). 5. In the Command field, run an AWS CLI command like the following. Replace each example resource placeholder with your own information. aws ssm start-automation-execution \ --document-name runbook name \ --region AWS Region of your source AMI \ --parameters runbook parameters The following example command uses the UpdateMyLatestWindowsAmi runbook and the Systems Manager Parameter latestAmi created in Update a golden AMI using Automation, AWS Lambda, and Parameter Store. aws ssm start-automation-execution \ --document-name UpdateMyLatestWindowsAmi \ --parameters \ "sourceAMIid='{{ssm:latestAmi}}'" --region region In Jenkins, the command looks like the example in the following screenshot. Automation 1499 AWS Systems Manager User Guide 6. In the Jenkins project, choose Build Now. Jenkins returns output similar to the following example. Updating AMIs for Auto Scaling groups The following example updates an Auto Scaling group with a newly patched AMI. This approach ensures that new images are automatically made available to different computing environments that use Auto Scaling groups. The final step of the automation in this example uses a Python function to create a new launch template that uses the newly patched AMI. Then the Auto Scaling group is updated to use the new launch template. In this type of Auto Scaling scenario, users could terminate existing instances in the Auto Scaling group to force a new instance to launch that uses the new image. Or, users could wait and allow scale-in or scale-out events to naturally launch newer instances. Before you begin Complete the following tasks before you begin this example. Automation 1500 AWS Systems Manager User Guide • Configure IAM roles for Automation, a tool in AWS Systems Manager. Systems Manager requires an instance profile role and a service role ARN to process automations. For more information, see Setting up Automation. Create the PatchAMIAndUpdateASG runbook Use the following procedure to create the PatchAMIAndUpdateASG runbook that patches the AMI you specify for the SourceAMI parameter. The runbook also updates an Auto Scaling group to use the latest, patched AMI. To create and run the runbook 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. 3. 4. In the navigation pane, choose Documents. In the Create document dropdown, choose Automation. In the Name field, enter PatchAMIAndUpdateASG. 5. Choose the Editor tab, and choose the Edit. 6. Choose OK when prompted, and delete the content in the Document editor field. 7. In the Document editor field, paste the following YAML sample runbook content. --- description: Systems Manager Automation Demo - Patch AMI and Update ASG schemaVersion: '0.3' assumeRole: '{{ AutomationAssumeRole }}' parameters: AutomationAssumeRole: type: String description: '(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to execute this document.' default: '' SourceAMI: type: String description: '(Required) The ID of the AMI you want to patch.' SubnetId: type: String description: '(Required) The ID of the subnet where the instance from the SourceAMI parameter is launched.' Automation 1501 AWS Systems Manager SecurityGroupIds: User Guide type: StringList description: '(Required) The IDs of the security groups to associate with the instance launched from the SourceAMI parameter.' NewAMI: type: String description: '(Optional) The name of of newly patched AMI.' default: 'patchedAMI-{{global:DATE_TIME}}' TargetASG: type: String description: '(Required) The name of the Auto Scaling group you want to update.' InstanceProfile: type: String description: '(Required) The name of the IAM instance profile you want the source instance to use.' SnapshotId: type: String description: (Optional) The snapshot ID to use to retrieve a patch baseline snapshot. default: '' RebootOption: type: String description: '(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non- compliant until a subsequent reboot and scan.' allowedValues: - NoReboot - RebootIfNeeded default: RebootIfNeeded Operation: type: String description: (Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from
systems-manager-ug-435
systems-manager-ug.pdf
435
want the source instance to use.' SnapshotId: type: String description: (Optional) The snapshot ID to use to retrieve a patch baseline snapshot. default: '' RebootOption: type: String description: '(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non- compliant until a subsequent reboot and scan.' allowedValues: - NoReboot - RebootIfNeeded default: RebootIfNeeded Operation: type: String description: (Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline. allowedValues: - Install - Scan default: Install mainSteps: - name: startInstances action: 'aws:runInstances' timeoutSeconds: 1200 maxAttempts: 1 Automation 1502 AWS Systems Manager User Guide onFailure: Abort inputs: ImageId: '{{ SourceAMI }}' InstanceType: m5.large MinInstanceCount: 1 MaxInstanceCount: 1 IamInstanceProfileName: '{{ InstanceProfile }}' SubnetId: '{{ SubnetId }}' SecurityGroupIds: '{{ SecurityGroupIds }}' - name: verifyInstanceManaged action: 'aws:waitForAwsResourceProperty' timeoutSeconds: 600 inputs: Service: ssm Api: DescribeInstanceInformation InstanceInformationFilterList: - key: InstanceIds valueSet: - '{{ startInstances.InstanceIds }}' PropertySelector: '$.InstanceInformationList[0].PingStatus' DesiredValues: - Online onFailure: 'step:terminateInstance' - name: installPatches action: 'aws:runCommand' timeoutSeconds: 7200 onFailure: Abort inputs: DocumentName: AWS-RunPatchBaseline Parameters: SnapshotId: '{{SnapshotId}}' RebootOption: '{{RebootOption}}' Operation: '{{Operation}}' InstanceIds: - '{{ startInstances.InstanceIds }}' - name: stopInstance action: 'aws:changeInstanceState' maxAttempts: 1 onFailure: Continue inputs: InstanceIds: - '{{ startInstances.InstanceIds }}' DesiredState: stopped - name: createImage Automation 1503 AWS Systems Manager User Guide action: 'aws:createImage' maxAttempts: 1 onFailure: Continue inputs: InstanceId: '{{ startInstances.InstanceIds }}' ImageName: '{{ NewAMI }}' NoReboot: false ImageDescription: Patched AMI created by Automation - name: terminateInstance action: 'aws:changeInstanceState' maxAttempts: 1 onFailure: Continue inputs: InstanceIds: - '{{ startInstances.InstanceIds }}' DesiredState: terminated - name: updateASG action: 'aws:executeScript' timeoutSeconds: 300 maxAttempts: 1 onFailure: Abort inputs: Runtime: python3.8 Handler: update_asg InputPayload: TargetASG: '{{TargetASG}}' NewAMI: '{{createImage.ImageId}}' Script: |- from __future__ import print_function import datetime import json import time import boto3 # create auto scaling and ec2 client asg = boto3.client('autoscaling') ec2 = boto3.client('ec2') def update_asg(event, context): print("Received event: " + json.dumps(event, indent=2)) target_asg = event['TargetASG'] new_ami = event['NewAMI'] Automation 1504 AWS Systems Manager User Guide # get object for the ASG we're going to update, filter by name of target ASG asg_query = asg.describe_auto_scaling_groups(AutoScalingGroupNames=[target_asg]) if 'AutoScalingGroups' not in asg_query or not asg_query['AutoScalingGroups']: return 'No ASG found matching the value you specified.' # gets details of an instance from the ASG that we'll use to model the new launch template after source_instance_id = asg_query.get('AutoScalingGroups')[0]['Instances'] [0]['InstanceId'] instance_properties = ec2.describe_instances( InstanceIds=[source_instance_id] ) source_instance = instance_properties['Reservations'][0]['Instances'] [0] # create list of security group IDs security_groups = [] for group in source_instance['SecurityGroups']: security_groups.append(group['GroupId']) # create a list of dictionary objects for block device mappings mappings = [] for block in source_instance['BlockDeviceMappings']: volume_query = ec2.describe_volumes( VolumeIds=[block['Ebs']['VolumeId']] ) volume_details = volume_query['Volumes'] device_name = block['DeviceName'] volume_size = volume_details[0]['Size'] volume_type = volume_details[0]['VolumeType'] device = {'DeviceName': device_name, 'Ebs': {'VolumeSize': volume_size, 'VolumeType': volume_type}} mappings.append(device) # create new launch template using details returned from instance in the ASG and specify the newly patched AMI time_stamp = time.time() time_stamp_string = datetime.datetime.fromtimestamp(time_stamp).strftime('%m-%d-%Y_%H-%M-%S') new_template_name = f'{new_ami}_{time_stamp_string}' try: Automation 1505 AWS Systems Manager User Guide ec2.create_launch_template( LaunchTemplateName=new_template_name, LaunchTemplateData={ 'BlockDeviceMappings': mappings, 'ImageId': new_ami, 'InstanceType': source_instance['InstanceType'], 'IamInstanceProfile': { 'Arn': source_instance['IamInstanceProfile']['Arn'] }, 'KeyName': source_instance['KeyName'], 'SecurityGroupIds': security_groups } ) except Exception as e: return f'Exception caught: {str(e)}' else: # update ASG to use new launch template asg.update_auto_scaling_group( AutoScalingGroupName=target_asg, LaunchTemplate={ 'LaunchTemplateName': new_template_name } ) return f'Updated ASG {target_asg} with new launch template {new_template_name} which uses AMI {new_ami}.' outputs: - createImage.ImageId 8. Choose Create automation. 9. In the navigation pane, choose Automation, and then choose Execute automation. 10. In the Choose document page, choose the Owned by me tab. 11. Search for the PatchAMIAndUpdateASG runbook, and select the button in the PatchAMIAndUpdateASG card. 12. Choose Next. 13. Choose Simple execution. 14. Specify values for the input parameters. Be sure the SubnetId and SecurityGroupIds you specify allow access to the public Systems Manager endpoints, or your interface endpoints for Systems Manager. 15. Choose Execute. Automation 1506 AWS Systems Manager User Guide 16. After automation completes, in the Amazon EC2 console, choose Auto Scaling, and then choose Launch Templates. Verify that you see the new launch template, and that it uses the new AMI. 17. Choose Auto Scaling, and then choose Auto Scaling Groups. Verify that the Auto Scaling group uses the new launch template. 18. Terminate one or more instances in your Auto Scaling group. Replacement instances will be launched using the new AMI. Using AWS Support self-service runbooks This section describes how to use some of the self-service automations created by the AWS Support team. These automations help you manage your AWS resources. Support Automation Workflows Support Automation Workflows (SAW) are automation runbooks written and maintained by the AWS Support team. These runbooks help you troubleshoot common issues with your AWS resources, proactively monitor and identify network issues, collect and analyze logs, and more. SAW runbooks use
systems-manager-ug-436
systems-manager-ug.pdf
436
group uses the new launch template. 18. Terminate one or more instances in your Auto Scaling group. Replacement instances will be launched using the new AMI. Using AWS Support self-service runbooks This section describes how to use some of the self-service automations created by the AWS Support team. These automations help you manage your AWS resources. Support Automation Workflows Support Automation Workflows (SAW) are automation runbooks written and maintained by the AWS Support team. These runbooks help you troubleshoot common issues with your AWS resources, proactively monitor and identify network issues, collect and analyze logs, and more. SAW runbooks use the AWSSupport prefix. For example, AWSSupport- ActivateWindowsWithAmazonLicense. Additionally, AWS Enterprise and Business Support customers also have access to runbooks that use the AWSPremiumSupport prefix. For example, AWSPremiumSupport- TroubleshootEC2DiskUsage. To learn more about AWS Support, see Getting started with AWS Support. Topics • Run the EC2Rescue tool on unreachable instances • Reset passwords and SSH keys on EC2 instances Run the EC2Rescue tool on unreachable instances EC2Rescue can help you diagnose and troubleshoot problems on Amazon Elastic Compute Cloud (Amazon EC2) instances for Linux and Windows Server. You can run the tool manually, as described in Using EC2Rescue for Linux Server and Using EC2Rescue for Windows Server. Or, you can run the tool automatically by using Systems Manager Automation and the AWSSupport- ExecuteEC2Rescue runbook. Automation is a tool in AWS Systems Manager. The AWSSupport- Automation 1507 AWS Systems Manager User Guide ExecuteEC2Rescue runbook is designed to perform a combination of Systems Manager actions, AWS CloudFormation actions, and Lambda functions that automate the steps normally required to use EC2Rescue. You can use the AWSSupport-ExecuteEC2Rescue runbook to troubleshoot and potentially remediate different types of operating system (OS) issues. Instances with encypted root volumes are not supported. See the following topics for a complete list: Windows: See Rescue Action in Using EC2Rescue for Windows Server with the Command Line. Linux and macOS: Some EC2Rescue for Linux modules detect and attempt to remediate issues. For more information, see the aws-ec2rescue-linux documentation for each module on GitHub. How it works Troubleshooting an instance with Automation and the AWSSupport-ExecuteEC2Rescue runbook works as follows: • You specify the ID of the unreachable instance and start the runbook. • The system creates a temporary VPC, and then runs a series of Lambda functions to configure the VPC. • The system identifies a subnet for your temporary VPC in the same Availability Zone as your original instance. • The system launches a temporary, SSM-enabled helper instance. • The system stops your original instance, and creates a backup. It then attaches the original root volume to the helper instance. • The system uses Run Command to run EC2Rescue on the helper instance. EC2Rescue identifies and attempts to fix issues on the attached, original root volume. When finished, EC2Rescue reattaches the root volume back to the original instance. • The system restarts your original instance, and terminates the temporary instance. The system also terminates the temporary VPC and the Lambda functions created at the start of the automation. Before you begin Before you run the following Automation, do the following: • Copy the instance ID of the unreachable instance. You will specify this ID in the procedure. Automation 1508 AWS Systems Manager User Guide • Optionally, collect the ID of a subnet in the same availability zone as your unreachable instance. The EC2Rescue instance will be created in this subnet. If you don’t specify a subnet, then Automation creates a new temporary VPC in your AWS account. Verify that your AWS account has at least one VPC available. By default, you can create five VPCs in a Region. If you already created five VPCs in the Region, the automation fails without making changes to your instance. For more information about Amazon VPC quotas, see VPC and Subnets in the Amazon VPC User Guide. • Optionally, you can create and specify an AWS Identity and Access Management (IAM) role for Automation. If you don't specify this role, then Automation runs in the context of the user who ran the automation. Granting AWSSupport-EC2Rescue permissions to perform actions on your instances EC2Rescue needs permission to perform a series of actions on your instances during the automation. These actions invoke the AWS Lambda, IAM, and Amazon EC2 services to safely and securely attempt to remediate issues with your instances. If you have Administrator-level permissions in your AWS account and/or VPC, you might be able to run the automation without configuring permissions, as described in this section. If you don't have Administrator-level permissions, then you or an administrator must configure permissions by using one of the following options. • Granting permissions by using IAM policies • Granting permissions by using an AWS CloudFormation template Granting permissions by using IAM policies You can either attach the following IAM
systems-manager-ug-437
systems-manager-ug.pdf
437
automation. These actions invoke the AWS Lambda, IAM, and Amazon EC2 services to safely and securely attempt to remediate issues with your instances. If you have Administrator-level permissions in your AWS account and/or VPC, you might be able to run the automation without configuring permissions, as described in this section. If you don't have Administrator-level permissions, then you or an administrator must configure permissions by using one of the following options. • Granting permissions by using IAM policies • Granting permissions by using an AWS CloudFormation template Granting permissions by using IAM policies You can either attach the following IAM policy to your user, group, or role as an inline policy; or, you can create a new IAM managed policy and attach it to your user, group, or role. For more information about adding an inline policy to your user, group, or role see Working With Inline Policies. For more information about creating a new managed policy, see Working With Managed Policies. Automation 1509 AWS Systems Manager Note User Guide If you create a new IAM managed policy, you must also attach the AmazonSSMAutomationRole managed policy to it so that your instances can communicate with the Systems Manager API. IAM Policy for AWSSupport-EC2Rescue Replace account ID with your own information. { "Version": "2012-10-17", "Statement": [ { "Action": [ "lambda:InvokeFunction", "lambda:DeleteFunction", "lambda:GetFunction" ], "Resource": "arn:aws:lambda:*:account ID:function:AWSSupport-EC2Rescue-*", "Effect": "Allow" }, { "Action": [ "s3:GetObject", "s3:GetObjectVersion" ], "Resource": [ "arn:aws:s3:::awssupport-ssm.*/*.template", "arn:aws:s3:::awssupport-ssm.*/*.zip" ], "Effect": "Allow" }, { "Action": [ "iam:CreateRole", "iam:CreateInstanceProfile", "iam:GetRole", "iam:GetInstanceProfile", "iam:PutRolePolicy", "iam:DetachRolePolicy", Automation 1510 AWS Systems Manager User Guide "iam:AttachRolePolicy", "iam:PassRole", "iam:AddRoleToInstanceProfile", "iam:RemoveRoleFromInstanceProfile", "iam:DeleteRole", "iam:DeleteRolePolicy", "iam:DeleteInstanceProfile" ], "Resource": [ "arn:aws:iam::account ID:role/AWSSupport-EC2Rescue-*", "arn:aws:iam::account ID:instance-profile/AWSSupport-EC2Rescue-*" ], "Effect": "Allow" }, { "Action": [ "lambda:CreateFunction", "ec2:CreateVpc", "ec2:ModifyVpcAttribute", "ec2:DeleteVpc", "ec2:CreateInternetGateway", "ec2:AttachInternetGateway", "ec2:DetachInternetGateway", "ec2:DeleteInternetGateway", "ec2:CreateSubnet", "ec2:DeleteSubnet", "ec2:CreateRoute", "ec2:DeleteRoute", "ec2:CreateRouteTable", "ec2:AssociateRouteTable", "ec2:DisassociateRouteTable", "ec2:DeleteRouteTable", "ec2:CreateVpcEndpoint", "ec2:DeleteVpcEndpoints", "ec2:ModifyVpcEndpoint", "ec2:Describe*", "autoscaling:DescribeAutoScalingInstances" ], "Resource": "*", "Effect": "Allow" } ] } Automation 1511 AWS Systems Manager User Guide Granting permissions by using an AWS CloudFormation template AWS CloudFormation automates the process of creating IAM roles and policies by using a preconfigured template. Use the following procedure to create the required IAM roles and policies for the EC2Rescue Automation by using AWS CloudFormation. To create the required IAM roles and policies for EC2Rescue 1. Download AWSSupport-EC2RescueRole.zip and extract the AWSSupport- EC2RescueRole.json file to a directory on your local machine. 2. If your AWS account is in a special partition, edit the template to change the ARN values to those for your partition. For example, for the China Regions, change all cases of arn:aws to arn:aws-cn. 3. Sign in to the AWS Management Console and open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 4. Choose Create stack, With new resources (standard). 5. On the Create stack page, for Prerequisite - Prepare template, choose Template is ready. 6. For Specify template, choose Upload a template file. 7. Choose Choose file, and then browse to and select the AWSSupport-EC2RescueRole.json file from the directory where you extracted it. 8. Choose Next. 9. On the Specify stack details page, for Stack name field, enter a name to identify this stack, and then choose Next. 10. (Optional) In the Tags area, apply one or more tag key name/value pairs to the stack. Tags are optional metadata that you assign to a resource. Tags enable you to categorize a resource in different ways, such as by purpose, owner, or environment. For example, you might want to tag a stack to identify the type of tasks it runs, the types of targets or other resources involved, and the environment it runs in. 11. Choose Next 12. On the Review page, review the stack details, and then scroll down and choose the I acknowledge that AWS CloudFormation might create IAM resources option. 13. Choose Create stack. Automation 1512 AWS Systems Manager User Guide AWS CloudFormation shows the CREATE_IN_PROGRESS status for a few minutes. The status changes to CREATE_COMPLETE after the stack has been created. You can also choose the refresh icon to check the status of the create process. 14. In the Stacks list, choose the option button the stack you just created, and then choose the Outputs tab. 15. Note the Value. The is the ARN of the AssumeRole. You specify this ARN when you run the Automation in the next procedure, Running the Automation. Running the Automation Important The following automation stops the unreachable instance. Stopping the instance can result in lost data on attached instance store volumes (if present). Stopping the instance can also cause the public IP to change, if no Elastic IP is associated. To run the AWSSupport-ExecuteEC2Rescue Automation 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Automation. 3. Choose Execute automation. 4. 5. 6. 7. In the Automation document section, choose Owned by Amazon from the list. In the runbooks
systems-manager-ug-438
systems-manager-ug.pdf
438
when you run the Automation in the next procedure, Running the Automation. Running the Automation Important The following automation stops the unreachable instance. Stopping the instance can result in lost data on attached instance store volumes (if present). Stopping the instance can also cause the public IP to change, if no Elastic IP is associated. To run the AWSSupport-ExecuteEC2Rescue Automation 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Automation. 3. Choose Execute automation. 4. 5. 6. 7. In the Automation document section, choose Owned by Amazon from the list. In the runbooks list, choose the button in the card for AWSSupport-ExecuteEC2Rescue, and then choose Next. In the Execute automation document page, choose Simple execution. In the Document details section, verify that Document version is set to the highest default version. For example, $DEFAULT or 3 (default). 8. In the Input parameters section, specify the following parameters: For UnreachableInstanceId, specify the ID of the unreachable instance. (Optional) For EC2RescueInstanceType, specify an instance type for the EC2Rescue instance. The default instance type is t2.medium. a. b. Automation 1513 AWS Systems Manager User Guide c. d. e. For AutomationAssumeRole, if you created roles for this Automation by using the AWS CloudFormation procedure described earlier in this topic, then choose the ARN of the AssumeRole that you created in the AWS CloudFormation console. (Optional) For LogDestination, specify an S3 bucket if you want to collect operating system-level logs while troubleshooting your instance. Logs are automatically uploaded to the specified bucket. For SubnetId, specify a subnet in an existing VPC in the same availability zone as the unreachable instance. By default, Systems Manager creates a new VPC, but you can specify a subnet in an existing VPC if you want. Note If you don't see the option to specify a bucket or a subnet ID, verify that you are using the latest Default version of the runbook. 9. (Optional) In the Tags area, apply one or more tag key name/value pairs to help identify the automation, for example Key=Purpose,Value=EC2Rescue. 10. Choose Execute. The runbook creates a backup AMI as part of the automation. All other resources created by the automation are automatically deleted, but this AMI remains in your account. The AMI is named using the following convention: Backup AMI: AWSSupport-EC2Rescue:UnreachableInstanceId You can locate this AMI in the Amazon EC2 console by searching on the Automation execution ID. Reset passwords and SSH keys on EC2 instances You can use the AWSSupport-ResetAccess runbook to automatically re-enable local Administrator password generation on Amazon Elastic Compute Cloud (Amazon EC2) instances for Windows Server and to generate a new SSH key on EC2 instances for Linux. The AWSSupport- ResetAccess runbook is designed to perform a combination of AWS Systems Manager actions, AWS CloudFormation actions, and AWS Lambda functions that automate the steps normally required to reset the local administrator password. You can use Automation, a tool in AWS Systems Manager, with the AWSSupport-ResetAccess runbook to solve the following problems: Automation 1514 AWS Systems Manager Windows User Guide You lost the EC2 key pair: To resolve this problem, you can use the AWSSupport-ResetAccess runbook to create a password-enabled AMI from your current instance, launch a new instance from the AMI, and select a key pair you own. You lost the local Administrator password: To resolve this problem, you can use the AWSSupport- ResetAccess runbook to generate a new password that you can decrypt with the current EC2 key pair. Linux You lost your EC2 key pair, or you configured SSH access to the instance with a key you lost: To resolve this problem, you can use the AWSSupport-ResetAccess runbook to create a new SSH key for your current instance, which enables you to connect to the instance again. Note If your EC2 instance for Windows Server is configured for Systems Manager, you can also reset your local Administrator password by using EC2Rescue and AWS Systems Manager Run Command. For more information, see Using EC2Rescue for Windows Server with Systems Manager Run Command in the Amazon EC2 User Guide. Related information Connect to your Linux instance from Windows using PuTTY in the Amazon EC2 User Guide How it works Troubleshooting an instance with Automation and the AWSSupport-ResetAccess runbook works as follows: • You specify the ID of the instance and run the runbook. • The system creates a temporary VPC, and then runs a series of Lambda functions to configure the VPC. • The system identifies a subnet for your temporary VPC in the same Availability Zone as your original instance. Automation 1515 AWS Systems Manager User Guide • The system launches a temporary, SSM-enabled helper instance. • The system stops your original instance, and creates a backup. It then attaches the original root volume to the helper instance. • The system uses
systems-manager-ug-439
systems-manager-ug.pdf
439
Automation and the AWSSupport-ResetAccess runbook works as follows: • You specify the ID of the instance and run the runbook. • The system creates a temporary VPC, and then runs a series of Lambda functions to configure the VPC. • The system identifies a subnet for your temporary VPC in the same Availability Zone as your original instance. Automation 1515 AWS Systems Manager User Guide • The system launches a temporary, SSM-enabled helper instance. • The system stops your original instance, and creates a backup. It then attaches the original root volume to the helper instance. • The system uses Run Command to run EC2Rescue on the helper instance. On Windows, EC2Rescue enables password generation for the local Administrator by using EC2Config or EC2Launch on the attached, original root volume. On Linux, EC2Rescue generates and injects a new SSH key and saves the private key, encrypted, in Parameter Store. When finished, EC2Rescue reattaches the root volume back to the original instance. • The system creates a new Amazon Machine Image (AMI) of your instance, now that password generation is enabled. You can use this AMI to create a new EC2 instance, and associate a new key pair if needed. • The system restarts your original instance, and terminates the temporary instance. The system also terminates the temporary VPC and the Lambda functions created at the start of the automation. • Windows: Your instance generates a new password you can decode from the Amazon EC2 console using the current key pair assigned to the instance. Linux: You can SSH to the instance by using the SSH key stored in Systems Manager Parameter Store as /ec2rl/openssh/instance ID/key. Before you begin Before you run the following Automation, do the following: • Copy the instance ID of the instance on which you want to reset the Administrator password. You will specify this ID in the procedure. • Optionally, collect the ID of a subnet in the same availability zone as your unreachable instance. The EC2Rescue instance will be created in this subnet. If you don’t specify a subnet, then Automation creates a new temporary VPC in your AWS account. Verify that your AWS account has at least one VPC available. By default, you can create five VPCs in a Region. If you already created five VPCs in the Region, the automation fails without making changes to your instance. For more information about Amazon VPC quotas, see VPC and Subnets in the Amazon VPC User Guide. • Optionally, you can create and specify an AWS Identity and Access Management (IAM) role for Automation. If you don't specify this role, then Automation runs in the context of the user who ran the automation. Automation 1516 AWS Systems Manager User Guide Granting AWSSupport-EC2Rescue permissions to perform actions on your instances EC2Rescue needs permission to perform a series of actions on your instances during the automation. These actions invoke the AWS Lambda, IAM, and Amazon EC2 services to safely and securely attempt to remediate issues with your instances. If you have Administrator-level permissions in your AWS account and/or VPC, you might be able to run the automation without configuring permissions, as described in this section. If you don't have Administrator-level permissions, then you or an administrator must configure permissions by using one of the following options. • Granting permissions by using IAM policies • Granting permissions by using an AWS CloudFormation template Granting permissions by using IAM policies You can either attach the following IAM policy to your user, group, or role as an inline policy; or, you can create a new IAM managed policy and attach it to your user, group, or role. For more information about adding an inline policy to your user, group, or role see Working With Inline Policies. For more information about creating a new managed policy, see Working With Managed Policies. Note If you create a new IAM managed policy, you must also attach the AmazonSSMAutomationRole managed policy to it so that your instances can communicate with the Systems Manager API. IAM Policy for AWSSupport-ResetAccess Replace account ID with your own information. { "Version": "2012-10-17", "Statement": [ { "Action": [ "lambda:InvokeFunction", "lambda:DeleteFunction", "lambda:GetFunction" Automation 1517 AWS Systems Manager ], User Guide "Resource": "arn:aws:lambda:*:account ID:function:AWSSupport-EC2Rescue-*", "Effect": "Allow" }, { "Action": [ "s3:GetObject", "s3:GetObjectVersion" ], "Resource": [ "arn:aws:s3:::awssupport-ssm.*/*.template", "arn:aws:s3:::awssupport-ssm.*/*.zip" ], "Effect": "Allow" }, { "Action": [ "iam:CreateRole", "iam:CreateInstanceProfile", "iam:GetRole", "iam:GetInstanceProfile", "iam:PutRolePolicy", "iam:DetachRolePolicy", "iam:AttachRolePolicy", "iam:PassRole", "iam:AddRoleToInstanceProfile", "iam:RemoveRoleFromInstanceProfile", "iam:DeleteRole", "iam:DeleteRolePolicy", "iam:DeleteInstanceProfile" ], "Resource": [ "arn:aws:iam::account ID:role/AWSSupport-EC2Rescue-*", "arn:aws:iam::account ID:instance-profile/AWSSupport-EC2Rescue-*" ], "Effect": "Allow" }, { "Action": [ "lambda:CreateFunction", "ec2:CreateVpc", "ec2:ModifyVpcAttribute", "ec2:DeleteVpc", "ec2:CreateInternetGateway", Automation 1518 AWS Systems Manager User Guide "ec2:AttachInternetGateway", "ec2:DetachInternetGateway", "ec2:DeleteInternetGateway", "ec2:CreateSubnet", "ec2:DeleteSubnet", "ec2:CreateRoute", "ec2:DeleteRoute", "ec2:CreateRouteTable", "ec2:AssociateRouteTable", "ec2:DisassociateRouteTable", "ec2:DeleteRouteTable", "ec2:CreateVpcEndpoint", "ec2:DeleteVpcEndpoints", "ec2:ModifyVpcEndpoint", "ec2:Describe*" ], "Resource": "*", "Effect": "Allow" } ] } Granting permissions by using an AWS CloudFormation template AWS CloudFormation automates the process of creating IAM
systems-manager-ug-440
systems-manager-ug.pdf
440
"arn:aws:lambda:*:account ID:function:AWSSupport-EC2Rescue-*", "Effect": "Allow" }, { "Action": [ "s3:GetObject", "s3:GetObjectVersion" ], "Resource": [ "arn:aws:s3:::awssupport-ssm.*/*.template", "arn:aws:s3:::awssupport-ssm.*/*.zip" ], "Effect": "Allow" }, { "Action": [ "iam:CreateRole", "iam:CreateInstanceProfile", "iam:GetRole", "iam:GetInstanceProfile", "iam:PutRolePolicy", "iam:DetachRolePolicy", "iam:AttachRolePolicy", "iam:PassRole", "iam:AddRoleToInstanceProfile", "iam:RemoveRoleFromInstanceProfile", "iam:DeleteRole", "iam:DeleteRolePolicy", "iam:DeleteInstanceProfile" ], "Resource": [ "arn:aws:iam::account ID:role/AWSSupport-EC2Rescue-*", "arn:aws:iam::account ID:instance-profile/AWSSupport-EC2Rescue-*" ], "Effect": "Allow" }, { "Action": [ "lambda:CreateFunction", "ec2:CreateVpc", "ec2:ModifyVpcAttribute", "ec2:DeleteVpc", "ec2:CreateInternetGateway", Automation 1518 AWS Systems Manager User Guide "ec2:AttachInternetGateway", "ec2:DetachInternetGateway", "ec2:DeleteInternetGateway", "ec2:CreateSubnet", "ec2:DeleteSubnet", "ec2:CreateRoute", "ec2:DeleteRoute", "ec2:CreateRouteTable", "ec2:AssociateRouteTable", "ec2:DisassociateRouteTable", "ec2:DeleteRouteTable", "ec2:CreateVpcEndpoint", "ec2:DeleteVpcEndpoints", "ec2:ModifyVpcEndpoint", "ec2:Describe*" ], "Resource": "*", "Effect": "Allow" } ] } Granting permissions by using an AWS CloudFormation template AWS CloudFormation automates the process of creating IAM roles and policies by using a preconfigured template. Use the following procedure to create the required IAM roles and policies for the EC2Rescue Automation by using AWS CloudFormation. To create the required IAM roles and policies for EC2Rescue 1. Download AWSSupport-EC2RescueRole.zip and extract the AWSSupport- EC2RescueRole.json file to a directory on your local machine. 2. If your AWS account is in a special partition, edit the template to change the ARN values to those for your partition. For example, for the China Regions, change all cases of arn:aws to arn:aws-cn. 3. Sign in to the AWS Management Console and open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 4. Choose Create stack, With new resources (standard). 5. On the Create stack page, for Prerequisite - Prepare template, choose Template is ready. Automation 1519 AWS Systems Manager User Guide 6. For Specify template, choose Upload a template file. 7. Choose Choose file, and then browse to and select the AWSSupport-EC2RescueRole.json file from the directory where you extracted it. 8. Choose Next. 9. On the Specify stack details page, for Stack name field, enter a name to identify this stack, and then choose Next. 10. (Optional) In the Tags area, apply one or more tag key name/value pairs to the stack. Tags are optional metadata that you assign to a resource. Tags enable you to categorize a resource in different ways, such as by purpose, owner, or environment. For example, you might want to tag a stack to identify the type of tasks it runs, the types of targets or other resources involved, and the environment it runs in. 11. Choose Next 12. On the Review page, review the stack details, and then scroll down and choose the I acknowledge that AWS CloudFormation might create IAM resources option. 13. AWS CloudFormation shows the CREATE_IN_PROGRESS status for a few minutes. The status changes to CREATE_COMPLETE after the stack has been created. You can also choose the refresh icon to check the status of the create process. 14. In the stack list, choose the option next to the stack you just created, and then choose the Outputs tab. 15. Copy the Value. The is the ARN of the AssumeRole. You will specify this ARN when you run the Automation. Running the Automation The following procedure describes how to run the AWSSupport-ResetAccess runbook by using the AWS Systems Manager console. Important The following automation stops the instance. Stopping the instance can result in lost data on attached instance store volumes (if present). Stopping the instance can also cause the public IP to change, if no Elastic IP is associated. To avoid these configuration changes, use Run Command to reset access. For more information, see Using EC2Rescue for Windows Server with Systems Manager Run Command in the Amazon EC2 User Guide. Automation 1520 AWS Systems Manager User Guide To run the AWSSupport-ResetAccess Automation 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Automation. 3. Choose Execute automation. 4. 5. 6. 7. In the Automation document section, choose Owned by Amazon from the list. In the runbooks list, choose the button in the card for AWSSupport-ResetAccess, and then choose Next. In the Execute automation document page, choose Simple execution. In the Document details section, verify that Document version is set to the highest default version. For example, $DEFAULT or 3 (default). 8. In the Input parameters section, specify the following parameters: a. b. For InstanceID, specify the ID of the unreachable instance. For SubnetId, specify a subnet in an existing VPC in the same availability zone as the instance you specified. By default, Systems Manager creates a new VPC, but you can specify a subnet in an existing VPC if you want. Note If you don't see the option to specify a subnet ID, verify that you are using the latest Default version of the runbook. c. For EC2RescueInstanceType, specify an instance type for the EC2Rescue instance. The default instance type is t2.medium. d. For AssumeRole, if you created roles for this Automation by using the AWS CloudFormation procedure described earlier in this topic, then specify the AssumeRole ARN that you noted in the AWS CloudFormation console. 9. (Optional) In the Tags
systems-manager-ug-441
systems-manager-ug.pdf
441
default, Systems Manager creates a new VPC, but you can specify a subnet in an existing VPC if you want. Note If you don't see the option to specify a subnet ID, verify that you are using the latest Default version of the runbook. c. For EC2RescueInstanceType, specify an instance type for the EC2Rescue instance. The default instance type is t2.medium. d. For AssumeRole, if you created roles for this Automation by using the AWS CloudFormation procedure described earlier in this topic, then specify the AssumeRole ARN that you noted in the AWS CloudFormation console. 9. (Optional) In the Tags area, apply one or more tag key name/value pairs to help identify the automation, for example Key=Purpose,Value=ResetAccess. 10. Choose Execute. 11. To monitor the automation progress, choose the running automation, and then choose the Steps tab. When the automation is finished, choose the Descriptions tab, and then choose Automation 1521 AWS Systems Manager User Guide View output to view the results. To view the output of individual steps, choose the Steps tab, and then choose View Outputs next to a step. The runbook creates a backup AMI and a password-enabled AMI as part of the automation. All other resources created by the automation are automatically deleted, but these AMIs remain in your account. The AMIs are named using the following conventions: • Backup AMI: AWSSupport-EC2Rescue:InstanceID • Password-enabled AMI: AWSSupport-EC2Rescue: Password-enabled AMI from Instance ID You can locate these AMIs by searching on the Automation execution ID. For Linux, the new SSH private key for your instance is saved, encrypted, in Parameter Store. The parameter name is /ec2rl/openssh/instance ID/key. Passing data to Automation using input transformers This AWS Systems Manager Automation tutorial shows how to use the input transformer feature of Amazon EventBridge to extract the instance-id of an Amazon Elastic Compute Cloud (Amazon EC2) instance from an instance state change event. Automation is a tool in AWS Systems Manager. We use the input transformer to pass that data to the AWS-CreateImage runbook target as the InstanceId input parameter. The rule is triggered when any instance changes to the stopped state. For more information about working with input transformers, see Tutorial: Use Input Transformer to Customize What is Passed to the Event Target in the Amazon EventBridge User Guide. Before you begin Verify that you added the required permissions and trust policy for EventBridge to your Systems Manager Automation service role. For more information, see Overview of Managing Access Permissions to Your EventBridge Resources in the Amazon EventBridge User Guide. To use input transformers with Automation 1. Open the Amazon EventBridge console at https://console.aws.amazon.com/events/. 2. In the navigation pane, choose Rules. 3. Choose Create rule. 4. Enter a name and description for the rule. Automation 1522 AWS Systems Manager User Guide A rule can't have the same name as another rule in the same Region and on the same event bus. 5. For Event bus, choose the event bus that you want to associate with this rule. If you want this rule to respond to matching events that come from your own AWS account, select default. When an AWS service in your account emits an event, it always goes to your account’s default event bus. 6. For Rule type, choose Rule with an event pattern. 7. Choose Next. 8. 9. For Event source, choose AWS events or EventBridge partner events. In the Event pattern section, choose Event pattern form. 10. For Event source, choose AWS services. 11. For AWS service, choose EC2. 12. For Event type, choose EC2 Instance State-change Notification. 13. For Specific state(s), choose stopped. 14. Choose Next. 15. For Target types, choose AWS service. 16. For Select a target, choose Systems Manager Automation. 17. For Document, choose AWS-CreateImage. 18. In the Configure automation parameter(s) section, choose Input Transformer. 19. For Input path, enter {"instance":"$.detail.instance-id"}. 20. For Template, enter {"InstanceId":[<instance>]}. 21. For Execution role, choose Use existing role and choose your Automation service role. 22. Choose Next. 23. (Optional) Enter one or more tags for the rule. For more information, see Tagging Your Amazon EventBridge Resources in the Amazon EventBridge User Guide. 24. Choose Next. 25. Review the details of the rule and choose Create rule. Learn about statuses returned by Systems Manager Automation AWS Systems Manager Automation reports detailed status information about the various statuses an automation action or step goes through when you run an automation and for the overall Automation 1523 AWS Systems Manager User Guide automation. Automation is a tool in AWS Systems Manager. You can monitor automation statuses using the following methods: • Monitor the Execution status in the Systems Manager Automation console. • Use your preferred command line tools. For the AWS Command Line Interface (AWS CLI), you can use describe-automation-step-executions or get-automation-execution. For the AWS Tools for Windows PowerShell, you can use
systems-manager-ug-442
systems-manager-ug.pdf
442
returned by Systems Manager Automation AWS Systems Manager Automation reports detailed status information about the various statuses an automation action or step goes through when you run an automation and for the overall Automation 1523 AWS Systems Manager User Guide automation. Automation is a tool in AWS Systems Manager. You can monitor automation statuses using the following methods: • Monitor the Execution status in the Systems Manager Automation console. • Use your preferred command line tools. For the AWS Command Line Interface (AWS CLI), you can use describe-automation-step-executions or get-automation-execution. For the AWS Tools for Windows PowerShell, you can use Get-SSMAutomationStepExecution or Get- SSMAutomationExecution. • Configure Amazon EventBridge to respond to action or automation status changes. For more information about handling timeouts in an automation, see Handling timeouts in runbooks. About automation statuses Automation reports status details for individual automation actions in addition to the overall automation. The overall automation status can be different than the status reported by an individual action or step as noted in the following tables. Detailed status for actions Status Pending InProgress Waiting Success Details The step hasn't started running. If your automation uses conditional actions, steps remain in this state after an automation has completed if the condition wasn't met to run the step. Steps also remain in this state if the automation is canceled before the step runs. The step is running. The step is waiting for input. The step completed successfully. This is a terminal state. Automation 1524 AWS Systems Manager Status TimedOut Cancelling Cancelled Failed Exited Detailed status for an automation Status Pending InProgress Waiting Success TimedOut User Guide Details A step or approval wasn't completed before the specified timeout period. This is a terminal state. The step is in the process of stopping after being canceled by a requester. The step was stopped by a requester before it completed. This is a terminal state. The step didn't complete successfully. This is a terminal state. Only returned by the aws:loop action. The loop didn't fully complete. A step inside the loop moved to an outside step using the nextStep, onCancel, or onFailure properties. Details The automation hasn't started running. The automation is running. The automation is waiting for input. The automation completed successfully. This is a terminal state. A step or approval wasn't completed before the specified timeout period. This is a terminal state. Automation 1525 AWS Systems Manager User Guide Status Cancelling Cancelled Failed Details The automation is in the process of stopping after being canceled by a requester. The automation was stopped by a requester before it completed. This is a terminal state. The automation didn't complete successfully. This is a terminal state. Troubleshooting Systems Manager Automation Use the following information to help you troubleshoot problems with AWS Systems Manager Automation, a tool in AWS Systems Manager. This topic includes specific tasks to resolve issues based on Automation error messages. Topics • Common Automation errors • Automation execution failed to start • Execution started, but status is failed • Execution started, but timed out Common Automation errors This section includes information about common Automation errors. VPC not defined 400 By default, when Automation runs either the AWS-UpdateLinuxAmi runbook or the AWS- UpdateWindowsAmi runbook, the system creates a temporary instance in the default VPC (172.30.0.0/16). If you deleted the default VPC, you will receive the following error: VPC not defined 400 To solve this problem, you must specify a value for the SubnetId input parameter. Automation 1526 AWS Systems Manager User Guide Automation execution failed to start An automation can fail with an access denied error or an invalid assume role error if you haven't properly configured AWS Identity and Access Management (IAM) roles, and policies for Automation. Access denied The following examples describe situations when an automation failed to start with an access denied error. Access Denied to Systems Manager API Error message: User: user arn isn't authorized to perform: ssm:StartAutomationExecution on resource: document arn (Service: AWSSimpleSystemsManagement; Status Code: 400; Error Code: AccessDeniedException; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) • Possible cause 1: The user attempting to start the automation doesn't have permission to invoke the StartAutomationExecution API. To resolve this issue, attach the required IAM policy to the user that was used to start the automation. • Possible cause 2: The user attempting to start the automation has permission to invoke the StartAutomationExecution API but doesn't have permission to invoke the API by using the specific runbook. To resolve this issue, attach the required IAM policy to the user that was used to start the automation. Access denied due to missing PassRole permissions Error message: User: user arn isn't authorized to perform: iam:PassRole on resource: automation assume role arn (Service: AWSSimpleSystemsManagement; Status Code: 400; Error Code: AccessDeniedException; Request ID: xxxxxxxx- xxxx-xxxx-xxxx-xxxxxxxxxxxx) The user attempting to start the automation doesn't have PassRole
systems-manager-ug-443
systems-manager-ug.pdf
443
used to start the automation. • Possible cause 2: The user attempting to start the automation has permission to invoke the StartAutomationExecution API but doesn't have permission to invoke the API by using the specific runbook. To resolve this issue, attach the required IAM policy to the user that was used to start the automation. Access denied due to missing PassRole permissions Error message: User: user arn isn't authorized to perform: iam:PassRole on resource: automation assume role arn (Service: AWSSimpleSystemsManagement; Status Code: 400; Error Code: AccessDeniedException; Request ID: xxxxxxxx- xxxx-xxxx-xxxx-xxxxxxxxxxxx) The user attempting to start the automation doesn't have PassRole permission for the assume role. To resolve this issue, attach the iam:PassRole policy to the role of the user attempting to start the automation. For more information, see Task 2: Attach the iam:PassRole policy to your Automation role. Automation 1527 AWS Systems Manager Invalid assume role User Guide When you run an Automation, an assume role is either provided in the runbook or passed as a parameter value for the runbook. Different types of errors can occur if the assume role isn't specified or configured properly. Malformed Assume Role Error message: The format of the supplied assume role ARN isn't valid. The assume role is improperly formatted. To resolve this issue, verify that a valid assume role is specified in your runbook or as a runtime parameter when starting the automation. Assume role can't be assumed Error message: The defined assume role is unable to be assumed. (Service: AWSSimpleSystemsManagement; Status Code: 400; Error Code: InvalidAutomationExecutionParametersException; Request ID: xxxxxxxx-xxxx- xxxx-xxxx-xxxxxxxxxxxx) • Possible cause 1: The assume role doesn't exist. To resolve this issue, create the role. For more information, see the section called “Setting up Automation”. Specific details for creating this role are described in the following topic, Task 1: Create a service role for Automation. • Possible cause 2: The assume role doesn't have a trust relationship with the Systems Manager service. To resolve this issue, create the trust relationship. For more information, see I Can't Assume A Role in the IAM User Guide. Execution started, but status is failed Action-specific failures Runbooks contain steps and steps run in order. Each step invokes one or more AWS service APIs. The APIs determine the inputs, behavior, and outputs of the step. There are multiple places where an error can cause a step to fail. Failure messages indicate when and where an error occurred. To see a failure message in the Amazon Elastic Compute Cloud (Amazon EC2) console, choose the View Outputs link of the failed step. To see a failure message from the AWS CLI, call get-automation-execution and look for the FailureMessage attribute in a failed StepExecution. Automation 1528 AWS Systems Manager User Guide In the following examples, a step associated with the aws:runInstance action failed. Each example explores a different type of error. Missing Image Error message: Automation Step Execution fails when it's launching the instance(s). Get Exception from RunInstances API of ec2 Service. Exception Message from RunInstances API: [The image id '[ami id]' doesn't exist (Service: AmazonEC2; Status Code: 400; Error Code: InvalidAMIID.NotFound; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)]. Please refer to Automation Service Troubleshooting Guide for more diagnosis details. The aws:runInstances action received input for an ImageId that doesn't exist. To resolve this problem, update the runbook or parameter values with the correct AMI ID. Assume role policy lacks sufficient permissions Error message: Automation Step Execution fails when it's launching the instance(s). Get Exception from RunInstances API of ec2 Service. Exception Message from RunInstances API: [You aren't authorized to perform this operation. Encoded authorization failure message: xxxxxxx (Service: AmazonEC2; Status Code: 403; Error Code: UnauthorizedOperation; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)]. Please refer to Automation Service Troubleshooting Guide for more diagnosis details. The assume role doesn't have sufficient permission to invoke the RunInstances API on EC2 instances. To resolve this problem, attach an IAM policy to the assume role that has permission to invoke the RunInstances API. For more information, see the Create the service roles for Automation using the console. Unexpected State Error message: Step fails when it's verifying launched instance(s) are ready to be used. Instance i-xxxxxxxxx entered unexpected state: shutting-down. Please refer to Automation Service Troubleshooting Guide for more diagnosis details. • Possible cause 1: There is a problem with the instance or the Amazon EC2 service. To resolve this problem, login to the instance or review the instance system log to understand why the instance started shutting down. Automation 1529 AWS Systems Manager User Guide • Possible cause 2: The user data script specified for the aws:runInstances action has a problem or incorrect syntax. Verify the syntax of the user data script. Also, verify that the user data scripts doesn't shut down the instance, or invoke other scripts that shut down the instance. Action-Specific Failures Reference When a step fails,
systems-manager-ug-444
systems-manager-ug.pdf
444
• Possible cause 1: There is a problem with the instance or the Amazon EC2 service. To resolve this problem, login to the instance or review the instance system log to understand why the instance started shutting down. Automation 1529 AWS Systems Manager User Guide • Possible cause 2: The user data script specified for the aws:runInstances action has a problem or incorrect syntax. Verify the syntax of the user data script. Also, verify that the user data scripts doesn't shut down the instance, or invoke other scripts that shut down the instance. Action-Specific Failures Reference When a step fails, the failure message might indicate which service was being invoked when the failure occurred. The following table lists the services invoked by each action. The table also provides links to information about each service. Action aws:runIn stances AWS services invoked by this action Amazon EC2 For information about this service Troubleshooting content Amazon EC2 User Guide Troubleshooting EC2 Instances aws:chang Amazon EC2 eInstanceState Amazon EC2 User Guide Troubleshooting EC2 instances aws:runCommand Systems Manager aws:createImage Amazon EC2 aws:createStack AWS CloudFormation aws:deleteStack AWS CloudFormation Troubleshooting Systems Manager Run Command AWS Systems Manager Run Command Amazon Machine Images AWS CloudFormation User Guide Troubleshooting AWS CloudFormation AWS CloudFormation User Guide Troubleshooting AWS CloudFormation aws:deleteImage Amazon EC2 aws:copyImage Amazon EC2 Amazon Machines Images Amazon Machine Images Automation 1530 AWS Systems Manager Action AWS services invoked by this action For information about this service Troubleshooting content User Guide aws:createTag Amazon EC2, Systems Manager EC2 Resource and Tags aws:invok eLambdaFu nction AWS Lambda AWS Lambda Developer Guide Troubleshooting Lambda Automation service internal error Error message: Internal Server Error. Please refer to Automation Service Troubleshooting Guide for more diagnosis details. A problem with the Automation service is preventing the specified runbook from running correctly. To resolve this issue, contact AWS Support. Provide the execution ID and customer ID, if available. Execution started, but timed out Error message: Step timed out while step is verifying launched instance(s) are ready to be used. Please refer to Automation Service Troubleshooting Guide for more diagnosis details. A step in the aws:runInstances action timed out. This can happen if the step action takes longer to run than the value specified for timeoutSeconds in the step. To resolve this issue, specify a longer value for the timeoutSeconds parameter in the aws:runInstances action. If that doesn't solve the problem, investigate why the step takes longer to run than expected AWS Systems Manager Change Calendar Change Calendar, a tool in AWS Systems Manager, allows you to set up date and time ranges when actions you specify (for example, in Systems Manager Automation runbooks) might or might not be performed in your AWS account. In Change Calendar, these ranges are called events. When you create a Change Calendar entry, you're creating a Systems Manager document of the type ChangeCalendar. In Change Calendar, the document stores iCalendar 2.0 data in plaintext format. Events that you add to the Change Calendar entry become part of the document. To get Change Calendar 1531 AWS Systems Manager User Guide started with Change Calendar, open the Systems Manager console. In the navigation pane, choose Change Calendar. You can create a calendar and its events in the Systems Manager console. You can also import an iCalendar (.ics) file that you have exported from a supported third-party calendar provider to add its events to your calendar. Supported providers include Google Calendar, Microsoft Outlook, and iCloud Calendar. A Change Calendar entry can be one of two types: DEFAULT_OPEN, or Open by default All actions can run by default, except during calendar events. During events, the state of a DEFAULT_OPEN calendar is CLOSED and events are blocked from running. DEFAULT_CLOSED, or Closed by default All actions are blocked by default, except during calendar events. During events, the state of a DEFAULT_CLOSED calendar is OPEN and actions are permitted to run. You can choose to have all scheduled Automation workflows, maintenance windows, and State Manager associations added automatically to a calendar. You can also remove any of those individual types from the calendar display. Who should use Change Calendar? • AWS customers who perform the following action types: • Create or run Automation runbooks. • Create change requests in Change Manager. • Run maintenance windows. • Create associations in State Manager. Automation, Change Manager, Maintenance Windows, and State Manager are all tools AWS Systems Manager. By integrating these tools with Change Calendar, you can allow or block these action types depending on the current state of the change calendar you associate with each one. • Administrators who are responsible for keeping the configurations of Systems Manager managed nodes consistent, stable, and functional. Change Calendar 1532 AWS Systems Manager User Guide Benefits of Change Calendar The following are some benefits of Change Calendar. • Review changes before they're
systems-manager-ug-445
systems-manager-ug.pdf
445
requests in Change Manager. • Run maintenance windows. • Create associations in State Manager. Automation, Change Manager, Maintenance Windows, and State Manager are all tools AWS Systems Manager. By integrating these tools with Change Calendar, you can allow or block these action types depending on the current state of the change calendar you associate with each one. • Administrators who are responsible for keeping the configurations of Systems Manager managed nodes consistent, stable, and functional. Change Calendar 1532 AWS Systems Manager User Guide Benefits of Change Calendar The following are some benefits of Change Calendar. • Review changes before they're applied A Change Calendar entry can help ensure that potentially destructive changes to your environment are reviewed before they're applied. • Apply changes only during appropriate times Change Calendar entries help keep your environment stable during event times. For example, you can create a Change Calendar entry to block changes when you expect high demand on your resources, such as during a conference or public marketing promotion. A calendar entry can also block changes when you expect limited administrator support, such as during vacations or holidays. You can use a calendar entry to allow changes except for certain times of the day or week when there is limited administrator support to troubleshoot failed actions or deployments. • Get the current or upcoming state of the calendar You can run the Systems Manager GetCalendarState API operation to show you the current state of the calendar, the state at a specified time, or the next time that the calendar state is scheduled to change. • EventBridge support This Systems Manager tool is supported as an event type in Amazon EventBridge rules. For information, see Monitoring Systems Manager events with Amazon EventBridge and Reference: Amazon EventBridge event patterns and types for Systems Manager. Topics • Setting up Change Calendar • Working with Change Calendar • Adding Change Calendar dependencies to Automation runbooks • Troubleshooting Change Calendar Setting up Change Calendar Complete the following before using Change Calendar, a tool in AWS Systems Manager. Change Calendar 1533 AWS Systems Manager Install latest command line tools User Guide Install the latest command line tools to get state information about calendars. Requirement AWS CLI AWS Tools for PowerShell Description (Optional) To use the AWS Command Line Interface (AWS CLI) to get state information about calendars, install the newest release of the AWS CLI on your local computer. For more information about how to install or upgrade the CLI, see Installing, updating, and uninstalling the AWS CLI in the AWS Command Line Interface User Guide. (Optional) To use the Tools for PowerShell to get state information about calendars, install the newest release of Tools for PowerShell on your local computer. For more information about how to install or upgrade the Tools for PowerShell, see Installin g the AWS Tools for PowerShell in the AWS Tools for PowerShell User Guide. Set up permissions If your user, group, or role is assigned administrator permissions, then you have full access to Change Calendar. If you don't have administrator permissions, then an administrator must give you permission by either assigning the AmazonSSMFullAccess managed policy, or assigning a policy that provides the necessary permissions to your user, group, or role. The following permissions are required to work with Change Calendar. Change Calendar entries To create, update, or delete a Change Calendar entry, including adding and removing events from the entry, a policy attached to your user, group, or role must allow the following actions: Change Calendar 1534 AWS Systems Manager User Guide • ssm:CreateDocument • ssm:DeleteDocument • ssm:DescribeDocument • ssm:DescribeDocumentPermission • ssm:GetCalendar • ssm:ListDocuments • ssm:ModifyDocumentPermission • ssm:PutCalendar • ssm:UpdateDocument • ssm:UpdateDocumentDefaultVersion Calendar state To get information about the current or upcoming state of the calendar, a policy attached to your user, group, or role must allow the following action: • ssm:GetCalendarState Operational events To view operational events, such as maintenance windows, associations, and planned automations, the policy attached to your user, group, or role must allow the following actions: • ssm:DescribeMaintenanceWindows • ssm:DescribeMaintenanceWindowExecution • ssm:DescribeAutomationExecutions • ssm:ListAssociations Note Change Calendar entries that are owned by (that is, created by) accounts other than yours are read-only, even if they're shared with your account. Maintenance windows, State Manager associations, and automations aren't shared. Change Calendar 1535 AWS Systems Manager User Guide Working with Change Calendar You can use the AWS Systems Manager console to add, manage, or delete entries in Change Calendar, a tool in AWS Systems Manager. You can also import events from supported third- party calendar providers by importing an iCalendar (.ics) file that you exported from the source calendar. And, you can use the GetCalendarState API operation or the get-calendar-state AWS Command Line Interface (AWS CLI) command to get information about the state of Change Calendar at a specific time.
systems-manager-ug-446
systems-manager-ug.pdf
446
account. Maintenance windows, State Manager associations, and automations aren't shared. Change Calendar 1535 AWS Systems Manager User Guide Working with Change Calendar You can use the AWS Systems Manager console to add, manage, or delete entries in Change Calendar, a tool in AWS Systems Manager. You can also import events from supported third- party calendar providers by importing an iCalendar (.ics) file that you exported from the source calendar. And, you can use the GetCalendarState API operation or the get-calendar-state AWS Command Line Interface (AWS CLI) command to get information about the state of Change Calendar at a specific time. Topics • Creating a change calendar • Creating and managing events in Change Calendar • Importing and managing events from third-party calendars • Updating a change calendar • Sharing a change calendar • Deleting a change calendar • Getting the state of a change calendar Creating a change calendar When you create an entry in Change Calendar, a tool in AWS Systems Manager, you're creating a Systems Manager document (SSM document) that uses the text format. To create a change calendar 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Change Calendar. 3. Choose Create calendar. -or- If the Change Calendar home page opens first, choose Create change calendar. 4. On the Create calendar page, in Calendar details, enter a name for your calendar entry. Calendar entry names can contain letters, numbers, periods, dashes, and underscores. The name should be specific enough to identify the purpose of the calendar entry at a glance. An Change Calendar 1536 AWS Systems Manager User Guide example is support-off-hours. You can't update this name after you create the calendar entry. (Optional) For Description, enter a description for your calendar entry. (Optional) In the Import calendar area, choose Choose file to select an iCalendar (.ics) file that you have exported from a third-party calendar provider. Importing the file will add its 5. 6. events to your calendar. Supported providers include Google Calendar, Microsoft Outlook, and iCloud Calendar. For more information, see Importing events from third-party calendar providers. 7. In Calendar type, choose one of the following. • Open by default - The calendar is open (Automation actions can run until an event starts), then closed for the duration of an associated event. • Closed by default - The calendar is closed (Automation actions can't run until an event starts) but open for the duration of an associated event. 8. (Optional) In Change management events, select Add change management events to the calendar. This selection displays all scheduled maintenance windows, State Manager associations, Automation workflows, and Change Manager change requests in your monthly calendar display. Tip If later you want to permanently remove these events types from the calendar display, edit the calendar, clear this check box, and then choose Save. 9. Choose Create calendar. After the calendar entry is created, Systems Manager displays your calendar entry in the Change Calendar list. The columns show the calendar version and the calendar owner's AWS account number. Your calendar entry can't prevent or allow any actions until you have created or imported at least one event. For information about creating an event, see Creating a Change Calendar event. For information about importing events, see Importing events from third-party calendar providers. Change Calendar 1537 AWS Systems Manager User Guide Creating and managing events in Change Calendar After you create a calendar in AWS Systems Manager Change Calendar, you can create, update, and delete events that are included in your open or closed calendar. Change Calendar is a tool in AWS Systems Manager. Tip As an alternative to creating events directly in the Systems Manager console, you can import an iCalendar (.ics) file from a supported third-party calendar application. For information, see Importing and managing events from third-party calendars. Topics • Creating a Change Calendar event • Updating a Change Calendar event • Deleting a Change Calendar event Creating a Change Calendar event When you add an event to an entry in Change Calendar, a tool in AWS Systems Manager, you're specifying a period of time during which the default action of the calendar entry is suspended. For example, if the calendar entry type is closed by default, the calendar is open to changes during events. (Alternatively, you can create an advisory event, which serves an informational role on the calendar only.) Currently, you can only create a Change Calendar event by using the console. Events are added to the Change Calendar document that you create when you create a Change Calendar entry. To create a Change Calendar event 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. In the navigation pane, choose Change Calendar. In the list of calendars, choose the name of the calendar entry to which you want to
systems-manager-ug-447
systems-manager-ug.pdf
447
type is closed by default, the calendar is open to changes during events. (Alternatively, you can create an advisory event, which serves an informational role on the calendar only.) Currently, you can only create a Change Calendar event by using the console. Events are added to the Change Calendar document that you create when you create a Change Calendar entry. To create a Change Calendar event 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. In the navigation pane, choose Change Calendar. In the list of calendars, choose the name of the calendar entry to which you want to add an 2. 3. event. 4. On the calendar entry's details page, choose Create event. Change Calendar 1538 AWS Systems Manager User Guide 5. On the Create scheduled event page, in Event details, enter a display name for your event. Event names can contain letters, numbers, periods, dashes, and underscores. The name should be specific enough to identify the purpose of the event. An example is nighttime-hours. 6. 7. 8. 9. For Description, enter a description for your event. For example, The support team isn't available during these hours. (Optional) If you want this event to serve as a visual notification or reminder only, select the Advisory check box. Advisory events play no functional role on your calendar. They serve informational purposes only for those who view your calendar. For Event start date, enter or choose a day in the format MM/DD/YYYY to start the event, and enter a time on the specified day in the format hh:mm:ss (hours, minutes, and seconds) to start the event. For Event end date, enter or choose a day in the format MM/DD/YYYY to end the event, and enter a time on the specified day in the format hh:mm:ss (hours, minutes, and seconds) to end the event. 10. For Schedule time zone, choose a time zone that applies to the start and end times of the event. You can enter part of a city name or time zone difference from Greenwich Mean Time (GMT) to find a time zone faster. The default is Coordinated Universal Time (UTC). 11. (Optional) To create an event that recurs daily, weekly, or monthly, turn on Recurrence, and then specify the frequency and optional end date for the recurrence. 12. Choose Create scheduled event. The new event is added to your calendar entry, and is displayed on the Events tab of the calendar entry's details page. Updating a Change Calendar event Use the following procedure to update a Change Calendar event in the AWS Systems Manager console. Change Calendar is a tool in AWS Systems Manager. To update a Change Calendar event 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. In the navigation pane, choose Change Calendar. In the list of calendars, choose the name of the calendar entry for which you want to edit an 2. 3. event. 4. On the calendar entry's details page, choose Events. Change Calendar 1539 AWS Systems Manager User Guide 5. In the calendar page, choose the event that you want to edit. Tip Use the buttons on the upper left to move back or forward one year, or back or forward one month. Change the time zone, if required, by choosing the correct time zone from the list on the upper right. 6. In Event details, choose Edit. 7. 8. 9. To change the event name and description, add to or replace the current text values. To change the Event start date value, choose the current start date, and then choose a new date from the calendar. To change the start time, choose the current start time, and then choose a new time from the list. To change the Event end date value, choose the current date, and then choose a new end date from the calendar. To change the end time, choose the current end time, and then choose a new time from the list. To change the Schedule time zone value, choose a time zone to apply to the start and end times of the event. You can enter part of a city name or time zone difference from Greenwich Mean Time (GMT) to find a time zone faster. The default is Coordinated Universal Time (UTC). 10. (Optional) If you want this event to serve as a visual notification or reminder only, select the Advisory check box. Advisory events play no functional role on your calendar. They serve informational purposes only for those who view your calendar. 11. Choose Save. Your changes are displayed on the Events tab of the calendar entry's details page. Choose the event that you updated to view your changes. Deleting a Change Calendar event You can delete one event at a time in Change Calendar, a tool in AWS Systems Manager, by using
systems-manager-ug-448
systems-manager-ug.pdf
448
faster. The default is Coordinated Universal Time (UTC). 10. (Optional) If you want this event to serve as a visual notification or reminder only, select the Advisory check box. Advisory events play no functional role on your calendar. They serve informational purposes only for those who view your calendar. 11. Choose Save. Your changes are displayed on the Events tab of the calendar entry's details page. Choose the event that you updated to view your changes. Deleting a Change Calendar event You can delete one event at a time in Change Calendar, a tool in AWS Systems Manager, by using the AWS Management Console. Tip If you selected Add change management events to the calendar when you created the calendar, you can do the following: Change Calendar 1540 AWS Systems Manager User Guide • To temporarily hide a change management event type from the calendar display, choose the X for the type at the top of the monthly preview. • To permanently remove these types from the calendar display, edit the calendar, clear the Add change management events to the calendar check box, and then choose Save. Removing the types from the calendar display doesn't delete them from your account. To delete a Change Calendar event 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- 2. 3. manager/. In the navigation pane, choose Change Calendar. In the list of calendars, choose the name of the calendar entry from which you want to delete an event. 4. On the calendar entry's details page, choose Events. 5. In the calendar page, choose the event that you want to delete. Tip Use the buttons on the upper left to move the calendar back or forward one year, or back or forward one month. Change the time zone, if required, by choosing the correct time zone from the list on the upper right. 6. On the Event details page, choose Delete. When you're prompted to confirm that you want to delete the event, choose Confirm. Importing and managing events from third-party calendars As an alternative to creating events directly in the AWS Systems Manager console, you can import an iCalendar (.ics) file from a supported third-party calendar application. Your calendar can include both imported events and events that you create in Change Calendar, which is a tool in AWS Systems Manager. Before you begin Before you attempt to import a calendar file, review the following requirements and constraints: Change Calendar 1541 AWS Systems Manager Calendar file format Only valid iCalendar files (.ics) are supported. Supported calendar providers User Guide Only .ics files exported from the following third-party calendar providers are supported: • Google Calendar (Export instructions) • Microsoft Outlook (Export instructions) • iCloud Calendar (Export instructions) File size You can import any number of valid .ics files. However, the total size of all imported files for each calendar can't exceed 64KB. Tip To minimize the size of the .ics file, ensure that you are exporting only basic details about your calendar entries. If necessary, reduce the length of the time period that you are exporting. Time zone In addition to a calendar name, a calendar provider, and at least one event, your exported .ics file should also indicate the time zone for the calendar. If it does not, or there is a problem identifying the time zone, you will be prompted to specify one after you import the file. Recurring event limitation Your exported .ics file can include recurring events. However, if one or more occurrences of a recurring event had been deleted in the source calendar, the import fails. Topics • Importing events from third-party calendar providers • Updating all events from a third-party calendar provider • Deleting all events imported from a third-party calendar Change Calendar 1542 AWS Systems Manager User Guide Importing events from third-party calendar providers Use the following procedure to import an iCalendar (.ics) file from a supported third-party calendar application. The events contained in the file are incorporated into the rules for your open or closed calendar. You can import a file into a new calendar you are creating with Change Calendar (a tool in AWS Systems Manager) or into an existing calendar. After you import the .ics file, you can remove individual events from it using the Change Calendar interface. For information, see Deleting a Change Calendar event. You can also delete all events from the source calendar by deleting the .ics file. For information, see Deleting all events imported from a third-party calendar. To import events from third-party calendar providers 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- 2. 3. manager/. In the navigation pane, choose Change Calendar. To start with a new calendar, choose Create calendar. In the Import calendar area, choose Choose file. For information about other steps to create a new calendar,
systems-manager-ug-449
systems-manager-ug.pdf
449
file, you can remove individual events from it using the Change Calendar interface. For information, see Deleting a Change Calendar event. You can also delete all events from the source calendar by deleting the .ics file. For information, see Deleting all events imported from a third-party calendar. To import events from third-party calendar providers 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- 2. 3. manager/. In the navigation pane, choose Change Calendar. To start with a new calendar, choose Create calendar. In the Import calendar area, choose Choose file. For information about other steps to create a new calendar, see Creating a change calendar. -or- To import third-party events into an existing calendar, choose the name of an existing calendar to open it. 4. Choose Actions, Edit, and then in the Import calendar area, choose Choose file. 5. Navigate to and select the exported .ics file on your local computer. 6. If prompted, for Select a time zone, select which time zone applies to the calendar. 7. Choose Save. Updating all events from a third-party calendar provider If several events are added to or removed from your source calendar after you have imported its iCalendar .ics file, you can reflect those changes in Change Calendar. First, re-export the source calendar, and then import the new file into Change Calendar, which is a tool in AWS Systems Manager. Events in your change calendar will be updated to reflect the contents of the newer file. Change Calendar 1543 AWS Systems Manager User Guide To update all events from a third-party calendar provider 1. In your third-party calendar, add or remove events as you want them to be reflected in Change Calendar, and then re-export the calendar to a new .ics file. 2. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 3. 4. In the navigation pane, choose Change Calendar. From the list of calendars, choose the calendar name from the list. 5. Choose Choose file, and then navigate to and select the replacement .ics file. 6. In response to the notification about overwriting the existing file, choose Confirm. Deleting all events imported from a third-party calendar If you no longer want any of the events that you imported from a third-party provider included in your calendar, you can delete the imported iCalendar .ics file. To delete all events imported from a third-party calendar 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- 2. 3. 4. manager/. In the navigation pane, choose Change Calendar. From the list of calendars, choose the calendar name from the list. In the Import calendar area, under My imported calendars, locate the name of the imported calendar, and then choose the X in its card. 5. Choose Save. Updating a change calendar You can update the description of a change calendar, but not its name. Although you can change the default state of a calendar, be aware that this reverses the behavior of change actions during events that are associated with the calendar. For example, if you change the state of a calendar from Open by default to Closed by default, unwanted changes might be made during event periods when the users who created the associated events aren't expecting changes. When you update a change calendar, you're editing the Change Calendar document that you created when you created the entry. Change Calendar is a tool in AWS Systems Manager. Change Calendar 1544 AWS Systems Manager To update a change calendar User Guide 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. In the navigation pane, choose Change Calendar. In the list of calendars, choose the name of the calendar that you want to update. 2. 3. 4. On the calendar's details page, choose Actions, Edit. 5. 6. In Description, you can change the description text. You can't edit the name of a change calendar. To change the calendar state, in Calendar type, choose a different value. Be aware that this reverses the behavior of change actions during events that are associated with the calendar. Before you change the calendar type, you should verify with other Change Calendar users that changing the calendar type doesn't allow unwanted changes during events that they have created. • Open by default – The calendar is open (Automation actions can run until an event starts) then closed for the duration of an associated event. • Closed by default – The calendar is closed (Automation actions can't run until an event starts) but open for the duration of an associated event. 7. Choose Save. Your calendar can't prevent or allow any actions until you add at least one event. For information about how to add an event, see Creating a Change Calendar event. Sharing a change calendar You can share a calendar in Change Calendar, a tool in AWS Systems Manager,
systems-manager-ug-450
systems-manager-ug.pdf
450
by default – The calendar is open (Automation actions can run until an event starts) then closed for the duration of an associated event. • Closed by default – The calendar is closed (Automation actions can't run until an event starts) but open for the duration of an associated event. 7. Choose Save. Your calendar can't prevent or allow any actions until you add at least one event. For information about how to add an event, see Creating a Change Calendar event. Sharing a change calendar You can share a calendar in Change Calendar, a tool in AWS Systems Manager, with other AWS accounts by using the AWS Systems Manager console. When you share a calendar, the calendar is read-only to users in the shared account. Maintenance windows, State Manager associations, and automations aren't shared. To share a change calendar 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Change Calendar. Change Calendar 1545 AWS Systems Manager User Guide 3. In the list of calendars, choose the name of the calendar that you want to share. 4. On the calendar's details page, choose the Sharing tab. 5. Choose Actions, Share. 6. In Share calendar, for Account ID, enter the ID number of a valid AWS account, and then choose Share. Users of the shared account can read the change calendar, but they can't make changes. Deleting a change calendar You can delete a calendar in Change Calendar, a tool in AWS Systems Manager, by using either the Systems Manager console or the AWS Command Line Interface (AWS CLI). Deleting a change calendar deletes all associated events. To delete a change calendar 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. In the navigation pane, choose Change Calendar. In the list of calendars, choose the name of the calendar that you want to delete. 2. 3. 4. On the calendar's details page, choose Actions, Delete. When you're prompted to confirm that you want to delete the calendar, choose Delete. Getting the state of a change calendar You can get the overall state of a calendar or the state of a calendar at a specific time in Change Calendar, a tool in AWS Systems Manager. You can also show the next time that the calendar state changes from OPEN to CLOSED, or the reverse. You can do this task only by using the GetCalendarState API operation. The procedure in this section uses the AWS Command Line Interface (AWS CLI). To get the state of a change calendar • Run the following command to show the state of one or more calendars at a specific time. The --calendar-names parameter is required, but --at-time is optional. Replace each example resource placeholder with your own information. Change Calendar 1546 AWS Systems Manager Linux & macOS User Guide aws ssm get-calendar-state \ --calendar-names "Calendar_name_or_document_ARN_1" "Calendar_name_or_document_ARN_2" \ --at-time "ISO_8601_time_format" The following is an example. aws ssm get-calendar-state \ --calendar-names "arn:aws:ssm:us-east-2:123456789012:document/ MyChangeCalendarDocument" "arn:aws:ssm:us-east-2:123456789012:document/ SupportOffHours" \ --at-time "2020-07-30T11:05:14-0700" Windows aws ssm get-calendar-state ^ --calendar-names "Calendar_name_or_document_ARN_1" "Calendar_name_or_document_ARN_2" ^ --at-time "ISO_8601_time_format" The following is an example. aws ssm get-calendar-state ^ --calendar-names "arn:aws:ssm:us-east-2:123456789012:document/ MyChangeCalendarDocument" "arn:aws:ssm:us-east-2:123456789012:document/ SupportOffHours" ^ --at-time "2020-07-30T11:05:14-0700" The command returns information like the following. { "State": "OPEN", "AtTime": "2020-07-30T16:18:18Z", "NextTransitionTime": "2020-07-31T00:00:00Z" } Change Calendar 1547 AWS Systems Manager User Guide The results show the state of the calendar (whether the calendar is of type DEFAULT_OPEN or DEFAULT_CLOSED) for the specified calendar entries that are owned by or shared with your account, at the time specified as the value of --at-time, and the time of the next transition. If you don't add the --at-time parameter, the current time is used. Note If you specify more than one calendar in a request, the command returns the status of OPEN only if all calendars in the request are open. If one or more calendars in the request are closed, the status returned is CLOSED. Adding Change Calendar dependencies to Automation runbooks To make Automation actions adhere to Change Calendar, a tool in AWS Systems Manager, add a step in an Automation runbook that uses the aws:assertAwsResourceProperty action. Configure the action to run GetCalendarState to verify that a specified calendar entry is in the state that you want (OPEN or CLOSED). The Automation runbook is only allowed to continue to the next step if the calendar state is OPEN. The following is a YAML-based sample excerpt of an Automation runbook that can't advance to the next step, LaunchInstance, unless the calendar state matches OPEN, the state specified in DesiredValues. The following is an example. mainSteps: - name: MyCheckCalendarStateStep action: 'aws:assertAwsResourceProperty' inputs: Service: ssm Api: GetCalendarState CalendarNames: ["arn:aws:ssm:us-east-2:123456789012:document/SaleDays"] PropertySelector: '$.State' DesiredValues: - OPEN description: "Use GetCalendarState to determine whether a calendar is open or closed." nextStep: LaunchInstance - name: LaunchInstance action: 'aws:executeScript' Change Calendar 1548 AWS Systems
systems-manager-ug-451
systems-manager-ug.pdf
451
you want (OPEN or CLOSED). The Automation runbook is only allowed to continue to the next step if the calendar state is OPEN. The following is a YAML-based sample excerpt of an Automation runbook that can't advance to the next step, LaunchInstance, unless the calendar state matches OPEN, the state specified in DesiredValues. The following is an example. mainSteps: - name: MyCheckCalendarStateStep action: 'aws:assertAwsResourceProperty' inputs: Service: ssm Api: GetCalendarState CalendarNames: ["arn:aws:ssm:us-east-2:123456789012:document/SaleDays"] PropertySelector: '$.State' DesiredValues: - OPEN description: "Use GetCalendarState to determine whether a calendar is open or closed." nextStep: LaunchInstance - name: LaunchInstance action: 'aws:executeScript' Change Calendar 1548 AWS Systems Manager inputs: Runtime: python3.8 ... Troubleshooting Change Calendar User Guide Use the following information to help you troubleshoot problems with Change Calendar, a tool in AWS Systems Manager. Topics • 'Calendar import failed' error 'Calendar import failed' error Problem: When importing an iCalendar (.ics) file, the system reports that the calendar import failed. • Solution 1 – Ensure that you are importing a file that was exported from a supported third-party calendar provider, which include the following: • Google Calendar (Export instructions) • Microsoft Outlook (Export instructions) • iCloud Calendar (Export instructions) • Solution 2 – If your source calendar contains any recurring events, ensure that no individual occurrences of the event have been canceled or deleted. Currently, Change Calendar doesn't support importing recurring events with individual cancellations. To resolve the issue, remove the recurring event from the source calendar, re-export the calendar and re-import it into Change Calendar, and then add the recurring event using the Change Calendar interface. For information, see Creating a Change Calendar event. • Solution 3 – Ensure that your source calendar contains at least one event. Uploads of .ics files that don't contain events don't succeed. • Solution 4 – If the system reports that the import failed because the .ics is too large, ensure that you are exporting only basic details about your calendar entries. If necessary, reduce the length of the time period that you export. • Solution 5 – If Change Calendar is unable to determine the time zone of your exported calendar when you attempt to import it from the Events tab, you might receive this message: "Calendar import failed. Change Calendar couldn't locate a valid time zone. You can import the calendar Change Calendar 1549 AWS Systems Manager User Guide from the Edit menu." In this case, choose Actions, Edit, and then try importing the file from the Edit calendar page. • Solution 6 – Don't edit the .ics file before import. Attempting to modify the contents of the file can corrupt the calendar data. If you have modified the file before attempting the import, export the calendar from the source calendar again, and then re-attempt the upload. AWS Systems Manager Change Manager Change Manager, a tool in AWS Systems Manager, is an enterprise change management framework for requesting, approving, implementing, and reporting on operational changes to your application configuration and infrastructure. From a single delegated administrator account, if you use AWS Organizations, you can manage changes across multiple AWS accounts and across AWS Regions. Alternatively, using a local account, you can manage changes for a single AWS account. Use Change Manager for managing changes to both AWS resources and on-premises resources. To get started with Change Manager, open the Systems Manager console. In the navigation pane, choose Change Manager. With Change Manager, you can use pre-approved change templates to help automate change processes for your resources and help avoid unintentional results when making operational changes. Each change template specifies the following: • One or more Automation runbooks for a user to choose from when creating a change request. The changes that are made to your resources are defined in Automation runbooks. You can include custom runbooks or AWS managed runbooks in the change templates you create. When a user creates a change request, they can choose which one of the available runbooks to include in the request. Additionally, you can create change templates that let the user making the request specify any runbook in the change request. • The users in the account who must review change requests that were made using that change template. • The Amazon Simple Notification Service (Amazon SNS) topic that is used to notify assigned approvers that a change request is ready for review. • The Amazon CloudWatch alarm that is used to monitor the runbook workflow. • The Amazon SNS topic that is used to send notifications about status changes for change requests that are created using the change template. • The tags to apply to the change template for use in categorizing and filtering your change templates. Change Manager 1550 AWS Systems Manager User Guide • Whether change requests created from the change template can be run without an approval step
systems-manager-ug-452
systems-manager-ug.pdf
452
Simple Notification Service (Amazon SNS) topic that is used to notify assigned approvers that a change request is ready for review. • The Amazon CloudWatch alarm that is used to monitor the runbook workflow. • The Amazon SNS topic that is used to send notifications about status changes for change requests that are created using the change template. • The tags to apply to the change template for use in categorizing and filtering your change templates. Change Manager 1550 AWS Systems Manager User Guide • Whether change requests created from the change template can be run without an approval step (auto-approved requests). Through its integration with Change Calendar, which is another tool in Systems Manager, Change Manager also helps you safely implement changes while avoiding schedule conflicts with important business events. Change Manager integration with AWS Organizations and AWS IAM Identity Center helps you manage changes across your organization from a single account using your existing identity management system. You can monitor change progress from Change Manager and audit operational changes across your organization, providing improved visibility and accountability. Change Manager complements the safety controls of your continuous integration (CI) practices and continuous delivery (CD) methodology. Change Manager isn't intended for changes made as part of an automated release process, such as a CI/CD pipeline, unless there is an exception or approval required. How Change Manager works When the need for a standard or emergency operational change is identified, someone in the organization creates a change request that is based on one of the change templates created for use in your organization or account. If the requested change requires manual approvals, Change Manager notifies the designated approvers through an Amazon SNS notification that a change request is ready for their review. You can designate approvers for change requests in the change template, or let users designate approvers in the change request itself. You can assign different reviewers to different templates. For example, assign one user, user group, or AWS Identity and Access Management (IAM) role who must approve requests for changes to managed nodes, and another user, group, or IAM role for database changes. If the change template allows auto-approvals, and a requester's user policy doesn't prohibit it, the user can also choose to run the Automation runbook for their request without a review step (with the exception of change freeze events). For each change template, you can add up to five levels of approvers. For example, you might require technical reviewers to approve a change request created from a change template first, and then require a second level of approvals from one or more managers. Change Manager is integrated with AWS Systems Manager Change Calendar. When a requested change is approved, the system first determines whether the request conflicts with other scheduled business activities. If a conflict is detected, Change Manager can block the change or require Change Manager 1551 AWS Systems Manager User Guide additional approvals before starting the runbook workflow. For example, you might allow changes only during business hours to ensure that teams are available to manage any unexpected problems. For any changes requested to run outside those hours, you can require higher-level management approval in the form of change freeze approvers. For emergency changes, Change Manager can skip the step of checking Change Calendar for conflicts or blocking events after a change request is approved. When it's time to implement an approved change, Change Manager runs the Automation runbook that is specified in the associated change request. Only the operations defined in approved change requests are permitted when runbook workflows run. This approach helps you avoid unintentional results while changes are being implemented. In addition to restricting the changes that can be made when a runbook workflow runs, Change Manager also helps you control concurrency and error thresholds. You choose how many resources a runbook workflow can run on at once, how many accounts the change can run in at once, and how many failures to allow before the process is stopped and (if the runbook includes a rollback script) rolled back. You can also monitor the progress of changes being made by using CloudWatch alarms. After a runbook workflow has completed, you can review details about the changes made. These details include the reason for a change request, which change template was used, who requested and approved the changes, and how the changes were implemented. More info Introducing AWS Systems Manager Change Manager on the AWS News Blog How can Change Manager benefit my operations? Benefits of Change Manager include the following: • Reduce risk of service disruption and downtime Change Manager can make operational changes safer by ensuring that only approved changes are implemented when a runbook workflow runs. You can block unplanned and unreviewed changes. Change Manager helps you avoid the types
systems-manager-ug-453
systems-manager-ug.pdf
453
details about the changes made. These details include the reason for a change request, which change template was used, who requested and approved the changes, and how the changes were implemented. More info Introducing AWS Systems Manager Change Manager on the AWS News Blog How can Change Manager benefit my operations? Benefits of Change Manager include the following: • Reduce risk of service disruption and downtime Change Manager can make operational changes safer by ensuring that only approved changes are implemented when a runbook workflow runs. You can block unplanned and unreviewed changes. Change Manager helps you avoid the types of unintentional results caused by human error that require costly hours of research and backtracking. • Get detailed auditing and reporting on change histories Change Manager 1552 AWS Systems Manager User Guide Change Manager provides accountability with a consistent way to report and audit changes made across your organization, the intent of the changes, and details about who approved and implemented them. • Avoid schedule conflicts or violations Change Manager can detect schedule conflicts such as holiday events or new product launches, based on the active change calendar for your organization. You can allow runbook workflows to run only during business hours, or allow them only with additional approvals. • Adapt change requirements to your changing business During different business periods, you can implement different change management requirements. For example, during end-of-month reporting, tax season, or other critical business periods, you can block changes or require director-level approval for changes that could introduce unnecessary operational risks. • Centrally manage changes across accounts Through its integration with Organizations, Change Manager makes it possible for you to manage changes throughout all of your organizational units (OUs) from a single delegated administrator account. You can turn on Change Manager for use with your entire organization or with only some of your OUs. Who should use Change Manager? Change Manager is appropriate for the following AWS customers and organizations: • Any AWS customer who wants to improve the safety and governance of operational changes made to their cloud or on-premises environments. • Organizations that want to increase collaboration and visibility across teams, improve application availability by avoiding downtime, and reduce the risk associated with manual and repetitive tasks. • Organizations that must comply with best practices for change management. • Customers who need a fully auditable history of changes made to their application configuration and infrastructure. Change Manager 1553 AWS Systems Manager User Guide What are the main features of Change Manager? Primary features of Change Manager include the following: • Integrated support for change management best practices With Change Manager, you can apply select change management best practices to your operations. You can choose to turn on the following options: • Check Change Calendar to see if events are currently restricted so changes are made only during open calendar periods. • Allow changes during restricted events with extra approvals from change freeze approvers. • Require CloudWatch alarms to be specified for all change templates. • Require all change templates created in your account to be reviewed and approved before they can be used to create change requests. • Different approval paths for closed calendar periods and emergency change requests You can allow an option to check Change Calendar for restricted events and block approved change requests until the event is complete. However, you can also designate a second group of approvers, change freeze approvers, who can permit the change to be made even if the calendar is closed. You can also create emergency change templates. Change requests created from an emergency change template still require regular approvals but aren't subject to calendar restrictions and don't require change freeze approvals. • Control how and when runbook workflows are started Runbook workflows can be started according to a schedule, or as soon as approvals are complete (subject to calendar restriction rules). • Built-in notification support Specify who in your organization should review and approve change templates and change requests. Assign an Amazon SNS topic to a change template to send notifications to the topic's subscribers about status changes for change requests created with that change template. • Integration with AWS Systems Manager Change Calendar Change Manager allows administrators to restrict scheduling changes during specified time periods. For instance, you can create a policy that allows changes only during business hours to ensure that the team is available to handle any issues. You can also restrict changes during Change Manager 1554 AWS Systems Manager User Guide important business events. For example, retail businesses might restrict changes during large sales events. You can also require additional approvals during restricted periods. • Integration with AWS IAM Identity Center and Active Directory support With IAM Identity Center integration, members of your organization can access AWS accounts and manage their
systems-manager-ug-454
systems-manager-ug.pdf
454
Manager allows administrators to restrict scheduling changes during specified time periods. For instance, you can create a policy that allows changes only during business hours to ensure that the team is available to handle any issues. You can also restrict changes during Change Manager 1554 AWS Systems Manager User Guide important business events. For example, retail businesses might restrict changes during large sales events. You can also require additional approvals during restricted periods. • Integration with AWS IAM Identity Center and Active Directory support With IAM Identity Center integration, members of your organization can access AWS accounts and manage their resources using Systems Manager based on a common user identity. Using IAM Identity Center, you can assign your users access to accounts across AWS. Integration with Active Directory makes it possible to assign users in your Active Directory account as approvers for change templates created for your Change Manager operations. • Integration with Amazon CloudWatch alarms Change Manager is integrated with CloudWatch alarms. Change Manager listens for CloudWatch alarms during the runbook workflow and takes any actions, including sending notifications, that are defined for the alarm. • Integration with AWS CloudTrail Lake By creating an event data store in AWS CloudTrail Lake, you can view auditable information about the changes made by change requests that run in your account or organization. The event information stored includes such details as the following: • The API actions that were run • Tthe request parameters included for those actions • The user that ran the action • The resources that were updated during the process • Integration with AWS Organizations Using the cross-account capabilities provided by Organizations, you can use a delegated administrator account for managing Change Manager operations in OUs in your organization. In your Organizations management account, you can specify which account is to be the delegated administrator account. You can also control which of your OUs Change Manager can be used in. Is there a charge to use Change Manager? Yes. Change Manager is priced on a pay-per-use basis. You pay only for what you use. For more information, see AWS Systems Manager Pricing. Change Manager 1555 AWS Systems Manager User Guide What are the primary components of Change Manager? Change Manager components that you use to manage the change process in your organization or account include the following: Delegated administrator account If you use Change Manager across an organization, you use a delegated administrator account. This is the AWS account designated as the account for managing operations activities across Systems Manager, including Change Manager. The delegated administrator account manages change activities across your organization. When you set up your organization for use with Change Manager, you specify which of your accounts serves in this role. The delegated administrator account must be the only member of the organizational unit (OU) to which it's assigned. The delegated administrator account isn't required if you use Change Manager with a single AWS account only. Important If you use Change Manager across an organization, we recommend always making changes from the delegated administrator account. Although you can make changes from other accounts in the organization, those changes won't be reported in or viewable from the delegated administrator account. Change template A change template is a collection of configuration settings in Change Manager that define such things as required approvals, available runbooks, and notification options for change requests. You can require that the change templates created by users in your organization or account go through an approval process before they can be used. Change Manager supports two types of change templates. For an approved change request that is based on an emergency change template, the requested change can be made even if there are blocking events in Change Calendar. For an approved change request that is based on a standard change template, the requested change can't be made if there are blocking events in Change Calendar unless additional approvals are received from designated change freeze event approvers. Change Manager 1556 AWS Systems Manager Change request User Guide A change request is a request in Change Manager to run an Automation runbook that updates one or more resources in your AWS or on-premises environments. A change request is created using a change template. When you create a change request, one or more approvers in your organization or account must review and approve the request. Without the required approvals, the runbook workflow, which applies the changes you request, isn't permitted to run. In the system, change requests are a type of OpsItem in AWS Systems Manager OpsCenter. However, OpsItems of the type /aws/changerequest aren't displayed in OpsCenter. As OpsItems, change requests are subject to the same enforced quotas as other types of OpsItems. Additionally, to create a change request programmatically, you don't call the CreateOpsItem API operation.
systems-manager-ug-455
systems-manager-ug.pdf
455
request is created using a change template. When you create a change request, one or more approvers in your organization or account must review and approve the request. Without the required approvals, the runbook workflow, which applies the changes you request, isn't permitted to run. In the system, change requests are a type of OpsItem in AWS Systems Manager OpsCenter. However, OpsItems of the type /aws/changerequest aren't displayed in OpsCenter. As OpsItems, change requests are subject to the same enforced quotas as other types of OpsItems. Additionally, to create a change request programmatically, you don't call the CreateOpsItem API operation. Instead, you use the StartChangeRequestExecution API operation. But rather than running immediately, the change request must be approved, and there must not any blocking events in Change Calendar to prevent the workflow from running. When approvals have been received and the calendar isn't blocked (or permission has been given to bypass blocking calendar events), the StartChangeRequestExecution action is able to complete. Runbook workflow A runbook workflow is the process of requested changes being made to the targeted resources in your cloud or on-premises environment. Each change request designates a single Automation runbook to use to make the requested change. The runbook workflow occurs after all required approvals have been granted and there are no blocking events in Change Calendar. If the change has been scheduled for a specific date and time, the runbook workflow doesn't begin until scheduled, even if all approvals have been received and the calendar isn't blocked. Topics • Setting up Change Manager • Working with Change Manager • Auditing and logging Change Manager activity • Troubleshooting Change Manager Change Manager 1557 AWS Systems Manager User Guide Setting up Change Manager You can use Change Manager, a tool in AWS Systems Manager, to manage changes for an entire organization, as configured in AWS Organizations, or for a single AWS account. If you're using Change Manager with an organization, begin with the topic Setting up Change Manager for an organization (management account), and then proceed to Configuring Change Manager options and best practices. If you're using Change Manager with a single account, proceed directly to Configuring Change Manager options and best practices. Note If you begin using Change Manager with a single account, but that account is later added to an organizational unit for which Change Manager is allowed, your single account settings are disregarded. Topics • Setting up Change Manager for an organization (management account) • Configuring Change Manager options and best practices • Configuring roles and permissions for Change Manager • Controlling access to auto-approval runbook workflows Setting up Change Manager for an organization (management account) The tasks in this topic apply if you're using Change Manager, a tool in AWS Systems Manager, with an organization that is set up in AWS Organizations. If you want to use Change Manager only with a single AWS account, skip to the topic Configuring Change Manager options and best practices. Perform the tasks in this section in an AWS account that is serving as the management account in Organizations. For information about the management account and other Organizations concepts, see AWS Organizations terminology and concepts. If you need to turn on Organizations and specify your account as the management account before proceeding, see Creating and managing an organization in the AWS Organizations User Guide. Change Manager 1558 AWS Systems Manager Note This setup process can't be performed in the following AWS Regions: User Guide • Europe (Milan) (eu-south-1) • Middle East (Bahrain) (me-south-1) • Africa (Cape Town) (af-south-1) • Asia Pacific (Hong Kong) (ap-east-1) Ensure that you're working in a different Region in your management account for this procedure. During the setup procedure, you perform the following major tasks in Quick Setup, a tool in AWS Systems Manager. • Task 1: Register the delegated administrator account for your organization The change-related tasks that are performed using Change Manager are managed in one of your member accounts, which you specify to be the delegated administrator account. The delegated administrator account you register for Change Manager becomes the delegated administrator account for all your Systems Manager operations. (You might have delegated administrator accounts for other AWS services). Your delegated administrator account for Change Manager, which isn't the same as your management account, manages change activities across your organization, including change templates, change requests, and approvals for each. In the delegated administrator account, you also specify other configuration options for your Change Manager operations. Important The delegated administrator account must be the only member of the organizational unit (OU) to which it's assigned in Organizations. • Task 2: Define and specify runbook access policies for change requester roles, or custom job functions, that you want to use for your Change Manager operations Change Manager 1559 AWS Systems Manager User Guide In order
systems-manager-ug-456
systems-manager-ug.pdf
456
for Change Manager, which isn't the same as your management account, manages change activities across your organization, including change templates, change requests, and approvals for each. In the delegated administrator account, you also specify other configuration options for your Change Manager operations. Important The delegated administrator account must be the only member of the organizational unit (OU) to which it's assigned in Organizations. • Task 2: Define and specify runbook access policies for change requester roles, or custom job functions, that you want to use for your Change Manager operations Change Manager 1559 AWS Systems Manager User Guide In order to create change requests in Change Manager, users in your member accounts must be granted AWS Identity and Access Management (IAM) permissions that allow them to access only the Automation runbooks and change templates you choose to make available to them. Note When a user creates a change request, they first select a change template. This change template might make multiple runbooks available, but the user can select only one runbook for each change request. Change templates can also be configured to allow users to include any available runbook in their requests. To grant the needed permissions, Change Manager uses the concept of job functions, which is also used by IAM. However, unlike the AWS managed policies for job functions in IAM, you specify both the names of your Change Manager job functions and the IAM permissions for those job functions. When you configure a job function, we recommend creating a custom policy and providing only the permissions needed to perform change management tasks. For instance, you might specify permissions that limit users to that specific set of runbooks based on job functions that you define. For example, you might create a job function with the name DBAdmin. For this job function, you might grant only permissions needed for runbooks related to Amazon DynamoDB databases, such as AWS-CreateDynamoDbBackup and AWSConfigRemediation- DeleteDynamoDbTable. As another example, you might want to grant some users only the permissions needed to work with runbooks related to Amazon Simple Storage Service (Amazon S3) buckets, such as AWS-ConfigureS3BucketLogging and AWSConfigRemediation- ConfigureS3BucketPublicAccessBlock. The configuration process in Quick Setup for Change Manager also makes a set of full Systems Manager administrative permissions available for you to apply to an administrative role you create. Each Change Manager Quick Setup configuration you deploy creates a job function in your delegated administrator account with permissions to run Change Manager templates and Change Manager 1560 AWS Systems Manager User Guide Automation runbooks in the organizational units you have selected. You can create up to 15 Quick Setup configurations for Change Manager. • Task 3: Choose which member accounts in your organization to use with Change Manager You can use Change Manager with all the member accounts in all your organizational units that are set up in Organizations, and in all the AWS Regions they operate in. If you prefer, you can instead use Change Manager with only some of your organizational units. Important We strongly recommend, before you begin this procedure, that you read through its steps to understand the configuration choices you're making and the permissions you're granting. In particular, plan the custom job functions you will create and the permissions you assign to each job function. This ensures that when later you attach the job function policies you create to individual users, user groups, or IAM roles, they're being granted only the permissions you intend for them to have. As a best practice, begin by setting up the delegated administrator account using the login for an AWS account administrator. Then configure job functions and their permissions after you have created change templates and identified the runbooks that each one uses. To set up Change Manager for use with an organization, perform the following task in the Quick Setup area of the Systems Manager console. You repeat this task for each job function you want to create for your organization. Each job function you create can have permissions for a different set of organizational units. To set up an organization for Change Manager in the Organizations management account 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Quick Setup. 3. On the Change Manager card, choose Create. 4. For Delegated administrator account, enter the ID of the AWS account you want to use for managing change templates, change requests, and runbook workflows in Change Manager. Change Manager 1561 AWS Systems Manager User Guide If you have previously specified a delegated administrator account for Systems Manager, its ID is already reported in this field. Important The delegated administrator account must be the only member of the organizational unit (OU) to which it's assigned in Organizations. If the delegated administrator account you register is later deregistered from
systems-manager-ug-457
systems-manager-ug.pdf
457
pane, choose Quick Setup. 3. On the Change Manager card, choose Create. 4. For Delegated administrator account, enter the ID of the AWS account you want to use for managing change templates, change requests, and runbook workflows in Change Manager. Change Manager 1561 AWS Systems Manager User Guide If you have previously specified a delegated administrator account for Systems Manager, its ID is already reported in this field. Important The delegated administrator account must be the only member of the organizational unit (OU) to which it's assigned in Organizations. If the delegated administrator account you register is later deregistered from that role, the system removes its permissions for managing Systems Manager operations at the same time. Keep in mind that it will be necessary for you return to Quick Setup, designate a different delegated administrator account, and specify all job functions and permissions again. If you use Change Manager across an organization, we recommend always making changes from the delegated administrator account. Although you can make changes from other accounts in the organization, those changes won't be reported in or viewable from the delegated administrator account. 5. In the Permissions to request and make changes section, do the following. Note Each deployment configuration you create provides the permissions policy for just one job function. You can return to Quick Setup later to create more job functions when you have created change templates to use in your operations. To create an administrative role – For an administrator job function that has IAM permissions for all AWS actions, do the following. Important Granting users full administrative permissions should be done sparingly, and only if their roles require full Systems Manager access. For important information about security considerations for Systems Manager access, see Identity and access management for AWS Systems Manager and Security best practices for Systems Manager. Change Manager 1562 AWS Systems Manager User Guide 1. For Job function, enter a name to identify this role and its permissions, such as MyAWSAdmin. 2. For Role and permissions option, choose Administrator permissions. To create other job functions – To create a non-administrative role, do the following: 1. For Job function, enter a name to identify this role and suggest its permissions. The name you choose should represent scope of the runbooks for which you will provide permissions, such as DBAdmin or S3Admin. 2. For Role and permissions option, choose Custom permissions. 3. In the Permissions policy editor, enter the IAM permissions, in JSON format, to grant to this job function. Tip We recommend that you use the IAM policy editor to construct your policy and then paste the policy JSON into the Permissions policy field. Sample policy: DynamoDB database management For example, you might begin with policy content that provides permissions for working with the Systems Manager documents (SSM documents) the job function needs access to. Here is a sample policy content that grants access to all the AWS managed Automation runbooks related to DynamoDB databases and two change templates that have been created in the sample AWS account 123456789012, in the US East (Ohio) Region (us-east-2). The policy also includes permission for the StartChangeRequestExecution operation, which is required for creating a change request in Change Calendar. Note This example isn't comprehensive. Additional permissions might be needed for working with other AWS resources, such as databases and nodes. Change Manager 1563 AWS Systems Manager User Guide { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ssm:CreateDocument", "ssm:DescribeDocument", "ssm:DescribeDocumentParameters", "ssm:DescribeDocumentPermission", "ssm:GetDocument", "ssm:ListDocumentVersions", "ssm:ModifyDocumentPermission", "ssm:UpdateDocument", "ssm:UpdateDocumentDefaultVersion" ], "Resource": [ "arn:aws:ssm:region:*:document/AWS-CreateDynamoDbBackup", "arn:aws:ssm:region:*:document/AWS-AWS-DeleteDynamoDbBackup", "arn:aws:ssm:region:*:document/AWS-DeleteDynamoDbTableBackups", "arn:aws:ssm:region:*:document/AWSConfigRemediation- DeleteDynamoDbTable", "arn:aws:ssm:region:*:document/AWSConfigRemediation- EnableEncryptionOnDynamoDbTable", "arn:aws:ssm:region:*:document/AWSConfigRemediation- EnablePITRForDynamoDbTable", "arn:aws:ssm:region:123456789012:document/MyFirstDBChangeTemplate", "arn:aws:ssm:region:123456789012:document/MySecondDBChangeTemplate" ] }, { "Effect": "Allow", "Action": "ssm:ListDocuments", "Resource": "*" }, { "Effect": "Allow", "Action": "ssm:StartChangeRequestExecution", "Resource": "arn:aws:ssm:region:123456789012:automation-definition/*:*" } ] Change Manager 1564 AWS Systems Manager } User Guide For more information about IAM policies, see Access management for AWS resources and Creating IAM policies in the IAM User Guide. 6. In the Targets section, choose whether to grant permissions for the job function you're creating to your entire organization or only some of your organizational units. If you choose Entire organization, continue to step 9. If you choose Custom, continue to step 8. 7. In the Target OUs section, select the check boxes of the organizational units to use with Change Manager. 8. Choose Create. After the system finishes setting up Change Manager for your organization, it displays a summary of your deployments. This summary information includes the name of the role that was created for the job function you configured. For example, AWS-QuickSetup-SSMChangeMgr- DBAdminInvocationRole. Note Quick Setup uses AWS CloudFormation StackSets to deploy your configurations. You can also view information about a completed deployment configuration in the AWS CloudFormation console. For information about StackSets, see Working with AWS CloudFormation StackSets in the AWS CloudFormation User Guide. Your next step is to configure additional
systems-manager-ug-458
systems-manager-ug.pdf
458
the organizational units to use with Change Manager. 8. Choose Create. After the system finishes setting up Change Manager for your organization, it displays a summary of your deployments. This summary information includes the name of the role that was created for the job function you configured. For example, AWS-QuickSetup-SSMChangeMgr- DBAdminInvocationRole. Note Quick Setup uses AWS CloudFormation StackSets to deploy your configurations. You can also view information about a completed deployment configuration in the AWS CloudFormation console. For information about StackSets, see Working with AWS CloudFormation StackSets in the AWS CloudFormation User Guide. Your next step is to configure additional Change Manager options. You can complete this task in either your delegated administrator account or any account in an organization unit that you have allowed for use with Change Manager. You configure options such as choosing a user identity management option, specifying which users can review and approve or reject change templates and change requests, and choosing which best practice options to allow for your organization. For information, see Configuring Change Manager options and best practices. Configuring Change Manager options and best practices The tasks in this section must be performed whether you're using Change Manager, a tool in AWS Systems Manager, across an organization or in a single AWS account. Change Manager 1565 AWS Systems Manager User Guide If you're using Change Manager for an organization, you can perform the following tasks in either your delegated administrator account or any account in an organization unit that you have allowed for use with Change Manager. Topics • Task 1: Configuring Change Manager user identity management and template reviewers • Task 2: Configuring Change Manager change freeze event approvers and best practices • Configuring Amazon SNS topics for Change Manager notifications Task 1: Configuring Change Manager user identity management and template reviewers Perform the task in this procedure the first time you access Change Manager. You can update these configuration settings later by returning to Change Manager and choosing Edit on the Settings tab. To configure Change Manager user identity management and template reviewers 1. Sign in to the AWS Management Console. If you're using Change Manager for an organization, sign in using your credentials for your delegated administrator account. The user must have the necessary AWS Identity and Access Management (IAM) permissions for making updates to your Change Manager settings. 2. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 3. In the navigation pane, choose Change Manager. 4. On the service home page, depending on the available options, do one of the following: • If you're using Change Manager with AWS Organizations , choose Set up delegated account. • If you're using Change Manager with a single AWS account, choose Set up Change Manager. -or- Choose Create sample change request, Skip, and then choose the Settings tab. 5. For User identity management, choose one of the following. • AWS Identity and Access Management (IAM) – Identify the users who make and approve requests and perform other actions in Change Manager by using your existing user, groups, and roles. Change Manager 1566 AWS Systems Manager User Guide • AWS IAM Identity Center (IAM Identity Center) – Allow IAM Identity Center to create and manage identities, or connect to your existing identity source to identify the users who perform actions in Change Manager. 6. In the Template reviewer notification section, specify the Amazon Simple Notification Service (Amazon SNS) topics to use to notify template reviewers that a new change template or change template version is ready for review. Ensure that the Amazon SNS topic you choose is configured to send notifications to your template reviewers. For information about creating and configuring Amazon SNS topics for change template reviewer notifications, see Configuring Amazon SNS topics for Change Manager notifications. 1. To specify the Amazon SNS topic for template reviewer notification, choose one of the following: • Enter an SNS Amazon Resource Name (ARN) – For Topic ARN, enter the ARN of an existing Amazon SNS topic. This topic can be in any of your organization's accounts. • Select an existing SNS topic – For Target notification topic, select the ARN of an existing Amazon SNS topic in your current AWS account. (This option isn't available if you haven't yet created any Amazon SNS topics in your current AWS account and AWS Region.) Note The Amazon SNS topic you select must be configured to specify the notifications it sends and the subscribers they're sent to. Its access policy must also grant permissions to Systems Manager so Change Manager can send notifications. For information, see Configuring Amazon SNS topics for Change Manager notifications. 2. Choose Add notification. 7. In the Change template reviewers section, select the users in your organization or account to review new change templates or change template versions before they can
systems-manager-ug-459
systems-manager-ug.pdf
459
option isn't available if you haven't yet created any Amazon SNS topics in your current AWS account and AWS Region.) Note The Amazon SNS topic you select must be configured to specify the notifications it sends and the subscribers they're sent to. Its access policy must also grant permissions to Systems Manager so Change Manager can send notifications. For information, see Configuring Amazon SNS topics for Change Manager notifications. 2. Choose Add notification. 7. In the Change template reviewers section, select the users in your organization or account to review new change templates or change template versions before they can be used in your operations. Change template reviewers are responsible for verifying the suitability and security of templates other users have submitted for use in Change Manager runbook workflows. Select change template reviewers by doing the following: 1. Choose Add. Change Manager 1567 AWS Systems Manager User Guide 2. Select the check box next to the name of each user, group, or IAM role you want to assign as a change template reviewer. 3. Choose Add approvers. 8. Choose Submit. After you complete this initial setup process, configure additional Change Manager settings and best practices by following the steps in Task 2: Configuring Change Manager change freeze event approvers and best practices. Task 2: Configuring Change Manager change freeze event approvers and best practices After you complete the steps in Task 1: Configuring Change Manager user identity management and template reviewers, you can designate extra reviewers for change requests during change freeze events and specify which available best practices you want to allow for your Change Manager operations. A change freeze event means that restrictions are in place in the current change calendar (the calendar state in AWS Systems Manager Change Calendar is CLOSED). In these cases, in addition to regular approvers for change requests, or if the change request is created using a template that allow auto-approvals, change freeze approvers must grant permission for this change request to run. If they don't, the change won't be processed until the calendar state is again OPEN. To configure Change Manager change freeze event approvers and best practices 1. In the navigation pane, choose Change Manager. 2. Choose the Settings tab, and then choose Edit. 3. In the Approvers for change freeze events section, select the users in your organization or account who can approve changes to run even when the calendar in use in Change Calendar is currently CLOSED. Note To allow change freeze reviews, you must turn on the Check Change Calendar for restricted change events option in Best practices. Select approvers for change freeze events by doing the following: Change Manager 1568 AWS Systems Manager 1. Choose Add. User Guide 2. Select the check box next to the name of each user, group, or IAM role you want to assign as an approver for change freeze events. 3. Choose Add approvers. 4. In the Best practices section near the bottom of the page, turn on the best practices you want to enforce for each of the following options. • Option: Check Change Calendar for restricted change events To specify that Change Manager checks a calendar in Change Calendar to make sure changes aren't blocked by scheduled events, first select the Enabled check box, and then select the calendar to check for restricted events from the Change Calendar list. For more information about Change Calendar, see AWS Systems Manager Change Calendar. • Option: SNS topic for approvers for closed events 1. Choose one of the following to specify the Amazon Simple Notification Service (Amazon SNS) topic in your account to use for sending notifications to approvers during change freeze events. (Note that you must also specify approvers in the Approvers for change freeze events section above Best practices.) • Enter an SNS Amazon Resource Name (ARN) – For Topic ARN, enter the ARN of an existing Amazon SNS topic. This topic can be in any of your organization's accounts. • Select an existing SNS topic – For Target notification topic, select the ARN of an existing Amazon SNS topic in your current AWS account. (This option isn't available if you haven't yet created any Amazon SNS topics in your current AWS account and AWS Region.) Note The Amazon SNS topic you select must be configured to specify the notifications it sends and the subscribers they're sent to. Its access policy must also grant permissions to Systems Manager so Change Manager can send notifications. For information, see Configuring Amazon SNS topics for Change Manager notifications. 2. Choose Add notification. • Option: Require monitors for all templates Change Manager 1569 AWS Systems Manager User Guide If you want to ensure that all templates for your organization or account specify an Amazon CloudWatch alarm to monitor your change operation, select the Enabled check
systems-manager-ug-460
systems-manager-ug.pdf
460
AWS account and AWS Region.) Note The Amazon SNS topic you select must be configured to specify the notifications it sends and the subscribers they're sent to. Its access policy must also grant permissions to Systems Manager so Change Manager can send notifications. For information, see Configuring Amazon SNS topics for Change Manager notifications. 2. Choose Add notification. • Option: Require monitors for all templates Change Manager 1569 AWS Systems Manager User Guide If you want to ensure that all templates for your organization or account specify an Amazon CloudWatch alarm to monitor your change operation, select the Enabled check box. • Option: Require template review and approval before use To ensure that no change requests are created, and no runbook workflows run, without being based on a template that has been reviewed and approved, select the Enabled check box. 5. Choose Save. Configuring Amazon SNS topics for Change Manager notifications You can configure Change Manager, a tool in AWS Systems Manager, to send notifications to an Amazon Simple Notification Service (Amazon SNS) topic for events related to change requests and change templates. Complete the following tasks to receive notifications for the Change Manager events you add a topic to. Topics • Task 1: Create and subscribe to an Amazon SNS topic • Task 2: Update the Amazon SNS access policy • Task 3: (Optional) Update the AWS Key Management Service access policy Task 1: Create and subscribe to an Amazon SNS topic First, you must create and subscribe to an Amazon SNS topic. For more information, see Creating a Amazon SNS topic and Subscribing to an Amazon SNS topic in the Amazon Simple Notification Service Developer Guide. Note To receive notifications, you must specify the Amazon Resource Name (ARN) of an Amazon SNS topic that is in the same AWS Region and AWS account as the delegated administrator account. Change Manager 1570 AWS Systems Manager User Guide Task 2: Update the Amazon SNS access policy Use the following procedure to update the Amazon SNS access policy so that Systems Manager can publish Change Manager notifications to the Amazon SNS topic you created in Task 1. Without completing this task, Change Manager doesn't have permission to send notifications for the events you add the topic for. 1. Sign in to the AWS Management Console and open the Amazon SNS console at https:// console.aws.amazon.com/sns/v3/home. 2. In the navigation pane, choose Topics. 3. Choose the topic you created in Task 1, and then choose Edit. 4. Expand Access policy. 5. Add and update the following Sid block to the existing policy and replace each user input placeholder with your own information . { "Sid": "Allow Change Manager to publish to this topic", "Effect": "Allow", "Principal": { "Service": "ssm.amazonaws.com" }, "Action": "sns:Publish", "Resource": "arn:aws:sns:region:account-id:topic-name", "Condition": { "StringEquals": { "aws:SourceAccount": [ "account-id" ] } } } Enter this block after the existing Sid block, and replace region, account-id, and topic- name with the appropriate values for the topic you created. 6. Choose Save changes. The system now sends notifications to the Amazon SNS topic when the event type you add to topic for occurs. Change Manager 1571 AWS Systems Manager Important User Guide If you configured the Amazon SNS topic with an AWS Key Management Service (AWS KMS) server-side encryption key, then you must complete Task 3. Task 3: (Optional) Update the AWS Key Management Service access policy If you turned on AWS Key Management Service (AWS KMS) server-side encryption for your Amazon SNS topic, then you must also update the access policy of the AWS KMS key you chose when you configured the topic. Use the following procedure to update the access policy so that Systems Manager can publish Change Manager approval notifications to the Amazon SNS topic you created in Task 1. 1. Open the AWS KMS console at https://console.aws.amazon.com/kms. 2. In the navigation pane, choose Customer managed keys. 3. Choose the ID of the customer managed key you chose when you created the topic. 4. In the Key policy section, choose Switch to policy view. 5. Choose Edit. 6. Enter the following Sid block after one of the existing Sid blocks in the existing policy. Replace each user input placeholder with your own information. { "Sid": "Allow Change Manager to decrypt the key", "Effect": "Allow", "Principal": { "Service": "ssm.amazonaws.com" }, "Action": [ "kms:Decrypt", "kms:GenerateDataKey*" ], "Resource": "arn:aws:kms:region:account-id:key/key-id", "Condition": { "StringEquals": { "aws:SourceAccount": [ "account-id" ] } Change Manager 1572 AWS Systems Manager } } User Guide 7. Now enter the following Sid block after one of the existing Sid blocks in the resource policy to help prevent the cross-service confused deputy problem. This block uses the aws:SourceArn and aws:SourceAccount global condition context keys to limit the permissions that Systems Manager gives another service to the resource. Replace each user input placeholder
systems-manager-ug-461
systems-manager-ug.pdf
461
your own information. { "Sid": "Allow Change Manager to decrypt the key", "Effect": "Allow", "Principal": { "Service": "ssm.amazonaws.com" }, "Action": [ "kms:Decrypt", "kms:GenerateDataKey*" ], "Resource": "arn:aws:kms:region:account-id:key/key-id", "Condition": { "StringEquals": { "aws:SourceAccount": [ "account-id" ] } Change Manager 1572 AWS Systems Manager } } User Guide 7. Now enter the following Sid block after one of the existing Sid blocks in the resource policy to help prevent the cross-service confused deputy problem. This block uses the aws:SourceArn and aws:SourceAccount global condition context keys to limit the permissions that Systems Manager gives another service to the resource. Replace each user input placeholder with your own information. { "Version": "2008-10-17", "Statement": [ { "Sid": "Configure confused deputy protection for AWS KMS keys used in Amazon SNS topic when called from Systems Manager", "Effect": "Allow", "Principal": { "Service": "ssm.amazonaws.com" }, "Action": [ "sns:Publish" ], "Resource": "arn:aws:sns:region:account-id:topic-name", "Condition": { "ArnLike": { "aws:SourceArn": "arn:aws:ssm:region:account-id:*" }, "StringEquals": { "aws:SourceAccount": "account-id" } } } ] } 8. Choose Save changes. Change Manager 1573 AWS Systems Manager User Guide Configuring roles and permissions for Change Manager By default, Change Manager doesn't have permission to perform actions on your resources. You must grant access by using an AWS Identity and Access Management (IAM) service role, or assume role. This role enables Change Manager to securely run the runbook workflows specified in an approved change request on your behalf. The role grants AWS Security Token Service (AWS STS) AssumeRole trust to Change Manager. By providing these permissions to a role to act on behalf of users in an organization, users don't need to be granted that array of permissions themselves. The actions allowed by the permissions are limited to approved operations only. When users in your account or organization create a change request, they can select this assume role to perform the change operations. You can create a new assume role for Change Manager or update an existing role with the needed permissions. If you need to create a service role for Change Manager, complete the following tasks. Tasks • Task 1: Creating an assume role policy for Change Manager • Task 2: Creating an assume role for Change Manager • Task 3: Attaching the iam:PassRole policy to other roles • Task 4: Adding inline policies to an assume role to invoke other AWS services • Task 5: Configuring user access to Change Manager Task 1: Creating an assume role policy for Change Manager Use the following procedure to create the policy that you will attach to your Change Manager assume role. To create an assume role policy for Change Manager 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. In the navigation pane, choose Policies, and then choose Create Policy. 3. On the Create policy page, choose the JSON tab and replace the default content with the following, which you will modify for your own Change Manager operations in following steps. Change Manager 1574 AWS Systems Manager Note User Guide If you're creating a policy to use with a single AWS account, and not an organization with multiple accounts and AWS Regions, you can omit the first statement block. The iam:PassRole permission isn't required in the case of a single account using Change Manager. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "iam:PassRole", "Resource": "arn:aws:iam::delegated-admin-account-id:role/AWS- SystemsManager-job-functionAdministrationRole", "Condition": { "StringEquals": { "iam:PassedToService": "ssm.amazonaws.com" } } }, { "Effect": "Allow", "Action": [ "ssm:DescribeDocument", "ssm:GetDocument", "ssm:StartChangeRequestExecution" ], "Resource": [ "arn:aws:ssm:region:account-id:automation-definition/template-name: $DEFAULT", "arn:aws:ssm:region::document/template-name" ] }, { "Effect": "Allow", "Action": [ "ssm:ListOpsItemEvents", "ssm:GetOpsItem", "ssm:ListDocuments", Change Manager 1575 AWS Systems Manager User Guide "ssm:DescribeOpsItems" ], "Resource": "*" } ] } 4. For the iam:PassRole action, update the Resource value to include the ARNs of all job functions defined for your organization that you want to grant permissions to initiate runbook workflows. 5. Replace the region, account-id, template-name, delegated-admin-account-id, and job-function placeholders with values for your Change Manager operations. 6. For the second Resource statement, modify the list to include all change templates that you want to grant permissions for. Alternatively, specify "Resource": "*" to grant permissions for all change templates in your organization. 7. Choose Next: Tags. 8. (Optional) Add one or more tag-key value pairs to organize, track, or control access for this policy. 9. Choose Next: Review. 10. On the Review policy page, enter a name in the Name box, such as MyChangeManagerAssumeRole, and then enter an optional description. 11. Choose Create policy, and continue to Task 2: Creating an assume role for Change Manager. Task 2: Creating an assume role for Change Manager Use the following procedure to create a Change Manager assume role, a type of service role, for Change Manager. To create an assume role for Change Manager 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. 3. In the navigation pane, choose Roles, and then choose Create role. For Select trusted
systems-manager-ug-462
systems-manager-ug.pdf
462
Choose Next: Review. 10. On the Review policy page, enter a name in the Name box, such as MyChangeManagerAssumeRole, and then enter an optional description. 11. Choose Create policy, and continue to Task 2: Creating an assume role for Change Manager. Task 2: Creating an assume role for Change Manager Use the following procedure to create a Change Manager assume role, a type of service role, for Change Manager. To create an assume role for Change Manager 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. 3. In the navigation pane, choose Roles, and then choose Create role. For Select trusted entity, make the following choices: 1. For Trusted entity type, choose AWS service 2. For Use cases for other AWS services, choose Systems Manager 3. Choose Systems Manager, as shown in the following image. Change Manager 1576 AWS Systems Manager User Guide 4. Choose Next. 5. On the Attached permissions policy page, search for the assume role policy you created in Task 1: Creating an assume role policy for Change Manager, such as MyChangeManagerAssumeRole. 6. 7. 8. 9. Select the check box next to the assume role policy name, and then choose Next: Tags. For Role name, enter a name for your new instance profile, such as MyChangeManagerAssumeRole. (Optional) For Description, update the description for this instance role. (Optional) Add one or more tag-key value pairs to organize, track, or control access for this role. 10. Choose Next: Review. 11. (Optional) For Tags, add one or more tag-key value pairs to organize, track, or control access for this role, and then choose Create role. The system returns you to the Roles page. 12. Choose Create role. The system returns you to the Roles page. 13. On the Roles page, choose the role you just created to open the Summary page. Task 3: Attaching the iam:PassRole policy to other roles Use the following procedure to attach the iam:PassRole policy to an IAM instance profile or IAM service role. (The Systems Manager service uses IAM instance profiles to communicate with EC2 instances. For non-EC2 managed nodes in a hybrid and multicloud environment, an IAM service role is used instead.) By attaching the iam:PassRole policy, the Change Manager service can pass assume role permissions to other services or Systems Manager tools when running runbook workflows. Change Manager 1577 AWS Systems Manager User Guide To attach the iam:PassRole policy to an IAM instance profile or service role 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. 3. In the navigation pane, choose Roles. Search for the Change Manager assume role you created, such as MyChangeManagerAssumeRole, and choose its name. 4. In the Summary page for the assume role, choose the Permissions tab. 5. Choose Add permissions, Create inline policy. 6. On the Create policy page, choose the Visual editor tab. 7. Choose Service, and then choose IAM. 8. 9. 10. In the Filter actions text box, enter PassRole, and then choose the PassRole option. Expand Resources. Verify that Specific is selected, and then choose Add ARN. In the Specify ARN for role field, enter the ARN of the IAM instance profile role or IAM service role to which you want to pass assume role permissions. The system populates the Account and Role name with path fields. 11. Choose Add. 12. Choose Review policy. 13. For Name, enter a name to identify this policy, and then choose Create policy. More info • Configure instance permissions required for Systems Manager • Create the IAM service role required for Systems Manager in hybrid and multicloud environments Task 4: Adding inline policies to an assume role to invoke other AWS services When a change request invokes other AWS services by using the Change Manager assume role, the assume role must be configured with permission to invoke those services. This requirement applies to all AWS Automation runbooks (AWS-* runbooks) that might be used in a change request, such as the AWS-ConfigureS3BucketLogging, AWS-CreateDynamoDBBackup, and AWS- RestartEC2Instance runbooks. This requirement also applies to any custom runbooks you create that invoke other AWS services by using actions that call other services. For example, if you use the aws:executeAwsApi, aws:CreateStack, or aws:copyImage actions, then you must Change Manager 1578 AWS Systems Manager User Guide configure the service role with permission to invoke those services. You can enable permissions to other AWS services by adding an IAM inline policy to the role. To add an inline policy to an assume role to invoke other AWS services (IAM console) 1. Sign in to the AWS Management Console and open the IAM console at https:// console.aws.amazon.com/iam/. In the navigation pane, choose Roles. In the list, choose the name of the assume role that you want to update, such as 2. 3. MyChangeManagerAssumeRole. 4. Choose the Permissions tab. 5. Choose Add permissions, Create inline policy. 6. Choose the
systems-manager-ug-463
systems-manager-ug.pdf
463
configure the service role with permission to invoke those services. You can enable permissions to other AWS services by adding an IAM inline policy to the role. To add an inline policy to an assume role to invoke other AWS services (IAM console) 1. Sign in to the AWS Management Console and open the IAM console at https:// console.aws.amazon.com/iam/. In the navigation pane, choose Roles. In the list, choose the name of the assume role that you want to update, such as 2. 3. MyChangeManagerAssumeRole. 4. Choose the Permissions tab. 5. Choose Add permissions, Create inline policy. 6. Choose the JSON tab. 7. Enter a JSON policy document for the AWS services you want to invoke. Here are two example JSON policy documents. Amazon S3 PutObject and GetObject example { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:GetObject" ], "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*" } ] } Amazon EC2 CreateSnapshot and DescribeSnapShots example { "Version":"2012-10-17", "Statement":[ { Change Manager 1579 AWS Systems Manager User Guide "Effect":"Allow", "Action":"ec2:CreateSnapshot", "Resource":"*" }, { "Effect":"Allow", "Action":"ec2:DescribeSnapshots", "Resource":"*" } ] } For details about the IAM policy language, see IAM JSON policy reference in the IAM User Guide. 8. When you're finished, choose Review policy. The Policy Validator reports any syntax errors. 9. For Name, enter a name to identify the policy that you're creating. Review the policy Summary to see the permissions that are granted by your policy. Then choose Create policy to save your work. 10. After you create an inline policy, it's automatically embedded in your role. Task 5: Configuring user access to Change Manager If your user, group, or role is assigned administrator permissions, then you have access to Change Manager. If you don't have administrator permissions, then an administrator must assign the AmazonSSMFullAccess managed policy, or a policy that provides comparable permissions, to your user, group, or role. Use the following procedure to configure a user to use Change Manager. The user you choose will have permission to configure and run Change Manager. Depending on the identity application that you are using in your organization, you can select any of the three options available to configure user access. While configuring the user access, assign or add the following: 1. Assign the AmazonSSMFullAccess policy or a comparable policy that gives permission to access Systems Manager. 2. Assign the iam:PassRole policy. 3. Add the ARN for the Change Manager assume role you copied at the end of Task 2: Creating an assume role for Change Manager. Change Manager 1580 AWS Systems Manager User Guide To provide access, add permissions to your users, groups, or roles: • Users and groups in AWS IAM Identity Center: Create a permission set. Follow the instructions in Create a permission set in the AWS IAM Identity Center User Guide. • Users managed in IAM through an identity provider: Create a role for identity federation. Follow the instructions in Create a role for a third-party identity provider (federation) in the IAM User Guide. • IAM users: • Create a role that your user can assume. Follow the instructions in Create a role for an IAM user in the IAM User Guide. • (Not recommended) Attach a policy directly to a user or add a user to a user group. Follow the instructions in Adding permissions to a user (console) in the IAM User Guide. You have finished configuring the required roles for Change Manager. You can now use the Change Manager assume role ARN in your Change Manager operations. Controlling access to auto-approval runbook workflows In each change template created for your organization or account, you can specify whether change requests created from that template can run as auto-approved change requests, meaning that they run automatically without a review step (with the exception of change freeze events). However, you might want to prevent certain users, groups, or AWS Identity and Access Management (IAM) roles from running auto-approved change requests even if a change template allows it. You can do this through the use of the ssm:AutoApprove condition key for the StartChangeRequestExecution operation in an IAM policy assigned to the user, group, or IAM role. You can add the following policy as an inline policy, where the condition is specified as false, to prevent users from running auto-approvable change requests. { "Version": "2012-10-17", "Statement": [ { Change Manager 1581 AWS Systems Manager User Guide "Effect": "Allow", "Action": "ssm:StartChangeRequestExecution", "Resource": "*", "Condition": { "BoolIfExists": { "ssm:AutoApprove": "false" } } } ] } For information about specifying inline policies, see Inline policies and Adding and removing IAM identity permissions in the IAM User Guide. For more information about condition keys for Systems Manager policies, see Condition keys for Systems Manager. Working with Change Manager With Change Manager, a tool in AWS Systems Manager, users across your organization or in a single
systems-manager-ug-464
systems-manager-ug.pdf
464
specified as false, to prevent users from running auto-approvable change requests. { "Version": "2012-10-17", "Statement": [ { Change Manager 1581 AWS Systems Manager User Guide "Effect": "Allow", "Action": "ssm:StartChangeRequestExecution", "Resource": "*", "Condition": { "BoolIfExists": { "ssm:AutoApprove": "false" } } } ] } For information about specifying inline policies, see Inline policies and Adding and removing IAM identity permissions in the IAM User Guide. For more information about condition keys for Systems Manager policies, see Condition keys for Systems Manager. Working with Change Manager With Change Manager, a tool in AWS Systems Manager, users across your organization or in a single AWS account can perform change-related tasks for which they have been granted the necessary permissions. Change Manager tasks include the following: • Create, review, and approve or reject change templates. A change template is a collection of configuration settings in Change Manager that define such things as required approvals, available runbooks, and notification options for change requests. • Create, review, and approve or reject change requests. A change request is a request in Change Manager to run an Automation runbook that updates one or more resources in your AWS or on-premises environments. A change request is created using a change template. • Specify which users in your organization or account can be made reviewers for change templates and change requests. • Edit configuration settings, such as how user identities are managed in Change Manager and which of the available best practice options are enforced in your Change Manager operations. For information about configuring these settings, see Configuring Change Manager options and best practices. Change Manager 1582 AWS Systems Manager Topics • Working with change templates • Working with change requests • Reviewing change request details, tasks, and timelines (console) • Viewing aggregated counts of change requests (command line) Working with change templates User Guide A change template is a collection of configuration settings in Change Manager that define such things as required approvals, available runbooks, and notification options for change requests. Note AWS provides a sample Hello World change template you can use to try out Change Manager, a tool in AWS Systems Manager. However, you create your own change templates to define the changes you want to allow to the resources in your organization or account. The changes that are made when a runbook workflow runs are based on the contents an Automation runbook. In each change template you create, you can include one or more Automation runbooks that the user making a change request can choose from to run during the update. You can also create change templates that allow requesters to choose any available Automation runbook for the change request. To create a change template, you can use the Builder option in the Create template console page to build a change template. Alternatively, using the Editor option, you can manually author JSON or YAML content with the configuration you want for your runbook workflow. You can also use a command line tool to create a change template, with JSON content for the change template stored in an external file. Topics • Try out the AWS managed Hello World change template • Creating change templates • Reviewing and approving or rejecting change templates • Deleting change templates Change Manager 1583 AWS Systems Manager User Guide Try out the AWS managed Hello World change template You can use the sample change template AWS-HelloWorldChangeTemplate, which uses the sample Automation runbook AWS-HelloWorld, to test the review and approval process after you have finished setting up Change Manager, a tool in AWS Systems Manager. This template is designed for testing or verifying your configured permissions, approver assignments, and approval process. Approval to use this change template in your organization or account has already been provided by AWS. Any change request based on this change template, however, must still be approved by reviewers in your organization or account. Rather than make changes to a resource, the result of the runbook workflow associated with this template is to print a message in the output of an Automation step. Before you begin Before you begin, ensure you have completed the following tasks: • If you're using AWS Organizations to manage change across an organization, complete the organization setup tasks described in Setting up Change Manager for an organization (management account). • Configure Change Manager for your delegated administrator account or single account, as described in Configuring Change Manager options and best practices. Note If you turned on the best practice option Require monitors for all templates in your Change Manager settings, turn it off temporarily while you test the Hello World change template. To try out the AWS managed Hello World change template 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Change Manager. 3. Choose Create request.
systems-manager-ug-465
systems-manager-ug.pdf
465
the organization setup tasks described in Setting up Change Manager for an organization (management account). • Configure Change Manager for your delegated administrator account or single account, as described in Configuring Change Manager options and best practices. Note If you turned on the best practice option Require monitors for all templates in your Change Manager settings, turn it off temporarily while you test the Hello World change template. To try out the AWS managed Hello World change template 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Change Manager. 3. Choose Create request. 4. Choose the change template named AWS-HelloWorldChangeTemplate, and then choose Next. Change Manager 1584 AWS Systems Manager User Guide 5. For Name, enter a name for the change request that makes its purpose easy to identify, such as MyChangeRequestTest. 6. For the remainder of the steps to create your change request, see Creating change requests. Next steps For information about approving change requests, see Reviewing and approving or rejecting change requests. To view the status and results of your change request, choose the name of your change request on the Requests tab in Change Manager. Creating change templates A change template is a collection of configuration settings in Change Manager that define such things as required approvals, available runbooks, and notification options for change requests. You can create change templates for your operations in Change Manager, a tool in AWS Systems Manager, using the console, which includes Builder and Editor options, or command line tools. Topics • About approvals in your change templates • Creating change templates using Builder • Creating change templates using Editor • Creating change templates using command line tools About approvals in your change templates For each change template that you create, you can specify up to five approval levels for change requests created from it. For each of those levels, you can designate up to five potential approvers. An approver isn't limited to a single user. You can also specify an IAM group or IAM role as an individual approver. For IAM groups and IAM roles, one or more users belonging to the group or role can provide approvals toward receiving the total number of approvals required for a change request. You can also specify more approvers than your change template requires. Change Manager supports two main approaches to approvals: per-level approvals and per-line approvals. A combination of the two types is also possible in some situations. We recommend using only per-level approvals in your Change Manager operations. Change Manager 1585 AWS Systems Manager Per-level approvals User Guide Recommended. As of January 23, 2023, Change Manager supports per-level approvals. In this model, for each approval level in your change template, you first specify how many approvals are required for that level. Then you specify at least that many approvers for the level and can specify more approvers. However, only the number of per-level approvers that you specify need to approve the change request. For example, you could specify five approvers but require three approvals. For console-view and JSON samples of this approval type, see the section called “Sample per- level approval configuration”. Per-line approvals Supported for backward compatibility. The original release of Change Manager supported only per-line approvals. In this model, every approver specified for an approval level is represented as an approval line. Each approver had to approve a change request for it to be approved at that level. Prior to January 23, 2023, this was the only supported model for approvals. Change templates created before this date continue to support per-line approvals, but we recommend using per-level approvals instead. For console-view and JSON samples of this approval type, see the section called “Sample per- line approval configuration”. Combined per-line and per-level approvals Not recommended. In the console, the Builder tab no longer supports adding per-line approvals. However, in some cases you might end up with both per-line and per-level approvals in a change template. This can occur if you update a change template that was created before January 23, 2023, or if you create or update a change template by editing its YAML content manually, For console-view and JSON samples of this approval type, see the section called “Sample combined per-level and per-line approval configuration”. Important Although it's possible to create a change template that combines per-line and per-level approvals, this configuration isn't recommended or necessary. Whichever approval type requires more approvals (per-line or per-level approvals) takes precedence. For example: Change Manager 1586 AWS Systems Manager User Guide • If a change template specifies three per-level approvals but five per-line approvals, then five approvals are required. • If a change template specifies four per-level approvals but two per-line approvals, then four approvals are required. You can create a level that includes both per-line
systems-manager-ug-466
systems-manager-ug.pdf
466
type, see the section called “Sample combined per-level and per-line approval configuration”. Important Although it's possible to create a change template that combines per-line and per-level approvals, this configuration isn't recommended or necessary. Whichever approval type requires more approvals (per-line or per-level approvals) takes precedence. For example: Change Manager 1586 AWS Systems Manager User Guide • If a change template specifies three per-level approvals but five per-line approvals, then five approvals are required. • If a change template specifies four per-level approvals but two per-line approvals, then four approvals are required. You can create a level that includes both per-line and per-level approvals by editing the YAML or JSON content manually. Then, the Builder tab displays controls for specifying the required number of approvals for both the level and for individual lines. However, new levels that you add using the console still support only per-level approval configurations. Change request notifications and rejections Amazon SNS notifications When a change request is created using your change template, notifications are sent to subscribers of the Amazon Simple Notification Service (Amazon SNS) topic that has been designated for approval notifications at that level. You can specify the notification topic in the change template or allow the user creating the change request to specify one. After the minimum number of required approvals is received at one level, notifications are sent to approvers subscribed to the Amazon SNS topic for the next level, and so on. Important Ensure that the IAM roles, groups, and users you designate together provide enough approvers to meet the required number of approvals you specify. For example, if you designate only a single IAM group as an approver that contains three users, you can't specify that five approvals are mandatory at that level, only three or less. Change request rejections No matter how many approval levels and approvers you specify, only one rejection to a change request is required to prevent the runbook workflow for that request from occurring. Change Manager 1587 AWS Systems Manager User Guide Change Manager approval type examples The following samples demonstrate the console view and JSON content for the three types of approval types in Change Manager. Topics • Sample per-level approval configuration • Sample per-line approval configuration • Sample combined per-level and per-line approval configuration Sample per-level approval configuration In the per-level approval level setup shown in the following image, three approvals are required. Those approvals can come from any combination of IAM users, groups, and roles that are specified as approvers. Specified approvers include two IAM users (John Stiles and Ana Carolina Silva), a user group that contains three members (GroupOfThree), and a user role that represents ten users (RoleOfTen). If all three users in the GroupOfThree group approve the change request, it is approved for that level. It's not necessary to receive an approval from each user, group, or role. The minimum number of approvals can come from any combination of specified approvers. We recommend per-level approvals for your Change Manager operations. Change Manager 1588 AWS Systems Manager User Guide The following sample illustrates part of the YAML code for this configuration. Note This version of the YAML code include an additional input, MinRequiredApprovals (with an initial capital M). The value for this input indicates how many approvals are required from among all available reviewers. Note also that the minRequiredApprovals (lowercase initial m) value for each approver in the Approvers list is 0 (zero). This indicates that the approver can contribute to the overall approvals but is not required to do so. schemaVersion: "0.3" emergencyChange: false autoApprovable: false mainSteps: - name: ApproveAction1 action: aws:approve timeoutSeconds: 604800 inputs: Message: Please approve this change request MinRequiredApprovals: 3 Change Manager 1589 AWS Systems Manager User Guide EnhancedApprovals: Approvers: - approver: John Stiles type: IamUser minRequiredApprovals: 0 - approver: Ana Carolina Silva type: IamUser minRequiredApprovals: 0 - approver: GroupOfThree type: IamGroup minRequiredApprovals: 0 - approver: RoleOfTen type: IamRole minRequiredApprovals: 0 templateInformation: > #### What is the purpose of this change? //truncated Sample per-line approval configuration In the approval level setup shown in the following image, four approvers are specified. These include two IAM users (John Stiles and Ana Carolina Silva), a user group that contains three members (GroupOfThree), and a user role that represents ten users (RoleOfTen). Per-line approvals are supported for backwards compatibility but not recommended. For the change request to be approved in this per-line approval configuration, it must be approved by all approver lines: John Stiles, Ana Carolina Silva, one member of the GroupOfThree group, and one member of the RoleOfTen role. The following sample illustrates part of the YAML code for this configuration. Change Manager 1590 AWS Systems Manager Note User Guide Observe that the value for each minRequiredApprovals approver is 1. This indicates that one approval is required from each approver. schemaVersion:
systems-manager-ug-467
systems-manager-ug.pdf
467
(GroupOfThree), and a user role that represents ten users (RoleOfTen). Per-line approvals are supported for backwards compatibility but not recommended. For the change request to be approved in this per-line approval configuration, it must be approved by all approver lines: John Stiles, Ana Carolina Silva, one member of the GroupOfThree group, and one member of the RoleOfTen role. The following sample illustrates part of the YAML code for this configuration. Change Manager 1590 AWS Systems Manager Note User Guide Observe that the value for each minRequiredApprovals approver is 1. This indicates that one approval is required from each approver. schemaVersion: "0.3" emergencyChange: false autoApprovable: false mainSteps: - name: ApproveAction1 action: aws:approve timeoutSeconds: 10000 inputs: Message: Please approve this change request EnhancedApprovals: Approvers: - approver: John Stiles type: IamUser minRequiredApprovals: 1 - approver: Ana Carolina Silva type: IamUser minRequiredApprovals: 1 - approver: GroupOfThree type: IamGroup minRequiredApprovals: 1 - approver: RoleOfTen type: IamRole minRequiredApprovals: 1 executableRunBooks: - name: AWS-HelloWorld version: $DEFAULT templateInformation: > #### What is the purpose of this change? //truncated Sample combined per-level and per-line approval configuration In the combined per-level and per-line approval setup shown in the following image, three approvals are specified for the level, but four approvals are specified for the line-item approvals. Whichever approval type requires more approvals takes precedence over the other, so four Change Manager 1591 AWS Systems Manager User Guide approvals are required by this configuration. Combined per-level and per-line approval are not recommended. schemaVersion: "0.3" emergencyChange: false autoApprovable: false mainSteps: - name: ApproveAction1 action: aws:approve timeoutSeconds: 604800 inputs: Message: Please approve this change request MinRequiredApprovals: 3 EnhancedApprovals: Approvers: - approver: John Stiles type: IamUser minRequiredApprovals: 1 - approver: Ana Carolina Silva type: IamUser minRequiredApprovals: 1 - approver: GroupOfThree type: IamGroup minRequiredApprovals: 1 - approver: RoleOfTen type: IamRole minRequiredApprovals: 1 templateInformation: > Change Manager 1592 AWS Systems Manager User Guide #### What is the purpose of this change? //truncated Topics • Creating change templates using Builder • Creating change templates using Editor • Creating change templates using command line tools Creating change templates using Builder Using the Builder for change templates in Change Manager, a tool in AWS Systems Manager, you can configure the runbook workflow defined in your change template without having to use JSON or YAML syntax. After you specify your options, the system converts your input into the YAML format that Systems Manager can use to run runbook workflows. To create a change template using Builder 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Change Manager. 3. Choose Create template. 4. For Name, enter a name for the template that makes its purpose easy to identify, such as UpdateEC2LinuxAMI. 5. In the Change template details section, do the following: • For Description, provide a brief explanation of how and when the change template you're creating is to be used. This description helps users who create change requests determine whether they're using the correct change template. It helps those who review change requests understand whether the request should be approved. • For Change template type, specify whether you're creating a standard change template or an emergency change template. An emergency change template is used for situations when a change must be made even if changes are otherwise blocked by an event in the calendar in use by AWS Systems Manager Change Calendar. Change requests created from an emergency change template must still Change Manager 1593 AWS Systems Manager User Guide be approved by its designated approvers, but the requested changes can still run even when the calendar is blocked. • For Runbook options, specify the runbooks that users can choose from when creating a change request. You can add a single runbook or multiple runbooks. Alternatively, you can allow requesters to specify which runbook to use. In any of these cases, only one runbook can be included in the change request. • For Runbook, select the names of the runbooks and the versions of those runbooks that users can choose from for their change requests. No matter how many runbooks you add to the change template, only one can be selected per change request. You don't specify a runbook if you chose Any runbook can be used earlier. Tip Select a runbook and runbook version, and then choose View to examine the contents of the runbook in the Systems Manager Documents interface. 6. In the Template information section, use Markdown to enter information for users who create change requests from this change template. We have provided a set of questions that you can include for users who create change requests, or you can add other information and questions instead. Note Markdown is a markup language that allows you to add wiki-style descriptions to documents and individual steps within the document. For more information
systems-manager-ug-468
systems-manager-ug.pdf
468
runbook can be used earlier. Tip Select a runbook and runbook version, and then choose View to examine the contents of the runbook in the Systems Manager Documents interface. 6. In the Template information section, use Markdown to enter information for users who create change requests from this change template. We have provided a set of questions that you can include for users who create change requests, or you can add other information and questions instead. Note Markdown is a markup language that allows you to add wiki-style descriptions to documents and individual steps within the document. For more information about using Markdown, see Using Markdown in AWS. We recommend providing questions for users to answer about their change requests to help approvers decide whether or not to grant each change request, such as listing any manual steps required to run as part of the change and a rollback plan. Tip Toggle between Hide preview and Show preview to see what your content looks like as you compose. Change Manager 1594 AWS Systems Manager User Guide 7. In the Change request approvals section, do the following: • (Optional) If you want to allow change requests that are created from this change template to run automatically, without review by any approvers (with the exception of change freeze events), select Enable auto-approval. Note Enabling auto-approvals in a change template provides users with the option of bypassing reviewers. They can still choose to specify reviewers when creating a change request. Therefore, you must still specify reviewer options in the change template. Important If you enable auto-approval for a change template, users can submit change requests using that template that do not require review by reviewers before they run (with the exception of change freeze event approvers). If you want to restrict a particular user, group, or IAM role from submitting auto-approval requests, you can use a condition in an IAM policy for this purpose. For more information, see Controlling access to auto-approval runbook workflows. • For Number of approvals required at this level, choose the number of approvals that change requests created from this change template must receive for this level. • To add mandatory first-level approvers, choose Add approver, and then choose from the following: • Template specified approvers – Choose one or more users, groups, or AWS Identity and Access Management (IAM) roles from your account to approve change requests created from this change template. Any change requests that are created using this template must be reviewed and approved by each approver you specify. • Request specified approvers – The user who makes the change request specifies reviewers at the time they make the request and can choose from a list of users in your account. The number you enter in the Required column determines how many reviewers must be specified by a change request that uses this change template. Change Manager 1595 AWS Systems Manager User Guide Important Prior to January 23, 2023, the Builder tab supported specifying per-line approvals only. New change templates and new levels you add to existing change templates using the Builder tab support per-level approvals only. We recommend using only per-level approvals in your Change Manager operations. For more information, see About approvals in your change templates. • For SNS topic to notify approvers, do the following: 1. Choose one of the following to specify the Amazon Simple Notification Service (Amazon SNS) topic in your account to use for sending notifications to approvers that a change request is ready for their review: • Enter an SNS Amazon Resource Name (ARN) – For Topic ARN, enter the ARN of an existing Amazon SNS topic. This topic can be in any of your organization's accounts. • Select an existing SNS topic – For Target notification topic, select the ARN of an existing Amazon SNS topic in your current AWS account. (This option isn't available if you haven't yet created any Amazon SNS topics in your current AWS account and AWS Region.) • Specify SNS topic when the change request is created – The user who creates a change request can specify the Amazon SNS topic to use for notifications. Note The Amazon SNS topic you select must be configured to specify the notifications it sends and the subscribers they're sent to. Its access policy must also grant permissions to Systems Manager so Change Manager can send notifications. For information, see Configuring Amazon SNS topics for Change Manager notifications. 2. Choose Add notification. 8. (Optional) To add an additional level of approvers, choose Add approval level and choose between template-specified approvers and request-specified approvers for this level. Then choose an SNS topic to notify this level of approvers. After all approvals have been received by first-level approvers, second-level approvers are notified, and so on. Change Manager 1596 AWS
systems-manager-ug-469
systems-manager-ug.pdf
469
be configured to specify the notifications it sends and the subscribers they're sent to. Its access policy must also grant permissions to Systems Manager so Change Manager can send notifications. For information, see Configuring Amazon SNS topics for Change Manager notifications. 2. Choose Add notification. 8. (Optional) To add an additional level of approvers, choose Add approval level and choose between template-specified approvers and request-specified approvers for this level. Then choose an SNS topic to notify this level of approvers. After all approvals have been received by first-level approvers, second-level approvers are notified, and so on. Change Manager 1596 AWS Systems Manager User Guide You can add a maximum of five levels of approvers in each template. You might, for example, require approvals from users in technical roles for the first level, then managerial approval for the second level. 9. In the Monitoring section, for CloudWatch alarm to monitor, enter the name of an Amazon CloudWatch alarm in the current account to monitor the progress of runbook workflows that are based on this template. Tip To create a new alarm, or to review the settings of an alarm you want to specify, choose Open the Amazon CloudWatch console. For information about working with CloudWatch alarms, see Using CloudWatch Alarms in the Amazon CloudWatch User Guide. 10. In the Notifications section, do the following: 1. Choose one of the following to specify the Amazon SNS topic in your account to use for sending notifications about change requests that are created using this change template: • Enter an SNS Amazon Resource Name (ARN) – For Topic ARN, enter the ARN of an existing Amazon SNS topic. This topic can be in any of your organization's accounts. • Select an existing SNS topic – For Target notification topic, select the ARN of an existing Amazon SNS topic in your current AWS account. (This option isn't available if you haven't yet created any Amazon SNS topics in your current AWS account and AWS Region.) Note The Amazon SNS topic you select must be configured to specify the notifications it sends and the subscribers they're sent to. Its access policy must also grant permissions to Systems Manager so Change Manager can send notifications. For information, see Configuring Amazon SNS topics for Change Manager notifications. 2. Choose Add notification. 11. (Optional) In the Tags section, apply one or more tag key name/value pairs to the change template. Tags are optional metadata that you assign to a resource. By using tags, you can categorize a resource in different ways, such as by purpose, owner, or environment. For example, you might Change Manager 1597 AWS Systems Manager User Guide want to tag a change template to identify the type of change it makes and the environment it runs in. In this case, you could specify the following key name/value pairs: • Key=TaskType,Value=InstanceRepair • Key=Environment,Value=Production 12. Choose Save and preview. 13. Review the details of the change template you're creating. If you want to make change to the change template before submitting it for review, choose Actions, Edit. If you're satisfied with the contents of the change template, choose Submit for review. The users in your organization or account who have been specified as template reviewers on the Settings tab in Change Manager are notified that a new change template is pending their review. If an Amazon SNS topic has been specified for change templates, notifications are sent when the change template is rejected or approved. If you don't receive notifications related to this change template, you can return to Change Manager later to check on its status. Creating change templates using Editor Use the steps in this topic to configure a change template in Change Manager, a tool in AWS Systems Manager, by entering JSON or YAML instead of using the console controls. To create a change template using Editor 1. In the navigation pane, choose Change Manager. 2. Choose Create template. 3. For Name, enter a name for the template that makes its purpose easy to identify, such as RestartEC2LinuxInstance. 4. Above Change template details, choose Editor. 5. In the Document editor section, choose Edit, and then enter the JSON or YAML content for your change template. The following is an example. Change Manager 1598 AWS Systems Manager Note User Guide The parameter minRequiredApprovals is used to specify how many reviewers at a specified level must approve a change request that is created using this template. This example demonstrates two levels of approvals. You can specify up to five levels of approvals, but only one level is required. In the first level, the specific user "John-Doe" must approve each change request. After that, any three members of the IAM role Admin must approve the change request. For more information about approvals for change templates, see About approvals
systems-manager-ug-470
systems-manager-ug.pdf
470
The following is an example. Change Manager 1598 AWS Systems Manager Note User Guide The parameter minRequiredApprovals is used to specify how many reviewers at a specified level must approve a change request that is created using this template. This example demonstrates two levels of approvals. You can specify up to five levels of approvals, but only one level is required. In the first level, the specific user "John-Doe" must approve each change request. After that, any three members of the IAM role Admin must approve the change request. For more information about approvals for change templates, see About approvals in your change templates. YAML description: >- This change template demonstrates the feature set available for creating change templates for Change Manager. This template starts a Runbook workflow for the Automation runbook called AWS-HelloWorld. templateInformation: > ### Document Name: HelloWorldChangeTemplate ## What does this document do? This change template demonstrates the feature set available for creating change templates for Change Manager. This template starts a Runbook workflow for the Automation runbook called AWS-HelloWorld. ## Input Parameters * ApproverSnsTopicArn: (Required) Amazon Simple Notification Service ARN for approvers. * Approver: (Required) The name of the approver to send this request to. * ApproverType: (Required) The type of reviewer. * Allowed Values: IamUser, IamGroup, IamRole, SSOGroup, SSOUser ## Output Parameters This document has no outputs Change Manager 1599 AWS Systems Manager User Guide schemaVersion: '0.3' parameters: ApproverSnsTopicArn: type: String description: Amazon Simple Notification Service ARN for approvers. Approver: type: String description: IAM approver ApproverType: type: String description: >- Approver types for the request. Allowed values include IamUser, IamGroup, IamRole, SSOGroup, and SSOUser. executableRunBooks: - name: AWS-HelloWorld version: '1' emergencyChange: false autoApprovable: false mainSteps: - name: ApproveAction1 action: 'aws:approve' timeoutSeconds: 3600 inputs: Message: >- A sample change request has been submitted for your review in Change Manager. You can approve or reject this request. EnhancedApprovals: NotificationArn: '{{ ApproverSnsTopicArn }}' Approvers: - approver: John-Doe type: IamUser minRequiredApprovals: 1 - name: ApproveAction2 action: 'aws:approve' timeoutSeconds: 3600 inputs: Message: >- A sample change request has been submitted for your review in Change Manager. You can approve or reject this request. EnhancedApprovals: NotificationArn: '{{ ApproverSnsTopicArn }}' Approvers: - approver: Admin type: IamRole Change Manager 1600 AWS Systems Manager User Guide minRequiredApprovals: 3 JSON { "description": "This change template demonstrates the feature set available for creating change templates for Change Manager. This template starts a Runbook workflow for the Automation runbook called AWS-HelloWorld", "templateInformation": "### Document Name: HelloWorldChangeTemplate\n\n ## What does this document do?\n This change template demonstrates the feature set available for creating change templates for Change Manager. This template starts a Runbook workflow for the Automation runbook called AWS-HelloWorld.\n\n ## Input Parameters\n* ApproverSnsTopicArn: (Required) Amazon Simple Notification Service ARN for approvers.\n * Approver: (Required) The name of the approver to send this request to.\n * ApproverType: (Required) The type of reviewer. * Allowed Values: IamUser, IamGroup, IamRole, SSOGroup, SSOUser\n\n ## Output Parameters\nThis document has no outputs\n", "schemaVersion": "0.3", "parameters": { "ApproverSnsTopicArn": { "type": "String", "description": "Amazon Simple Notification Service ARN for approvers." }, "Approver": { "type": "String", "description": "IAM approver" }, "ApproverType": { "type": "String", "description": "Approver types for the request. Allowed values include IamUser, IamGroup, IamRole, SSOGroup, and SSOUser." } }, "executableRunBooks": [ { "name": "AWS-HelloWorld", "version": "1" } ], Change Manager 1601 AWS Systems Manager User Guide "emergencyChange": false, "autoApprovable": false, "mainSteps": [ { "name": "ApproveAction1", "action": "aws:approve", "timeoutSeconds": 3600, "inputs": { "Message": "A sample change request has been submitted for your review in Change Manager. You can approve or reject this request.", "EnhancedApprovals": { "NotificationArn": "{{ ApproverSnsTopicArn }}", "Approvers": [ { "approver": "John-Doe", "type": "IamUser", "minRequiredApprovals": 1 } ] } } }, { "name": "ApproveAction2", "action": "aws:approve", "timeoutSeconds": 3600, "inputs": { "Message": "A sample change request has been submitted for your review in Change Manager. You can approve or reject this request.", "EnhancedApprovals": { "NotificationArn": "{{ ApproverSnsTopicArn }}", "Approvers": [ { "approver": "Admin", "type": "IamRole", "minRequiredApprovals": 3 } ] } } } ] } Change Manager 1602 AWS Systems Manager 6. Choose Save and preview. 7. Review the details of the change template you're creating. User Guide If you want to make change to the change template before submitting it for review, choose Actions, Edit. If you're satisfied with the contents of the change template, choose Submit for review. The users in your organization or account who have been specified as template reviewers on the Settings tab in Change Manager are notified that a new change template is pending their review. If an Amazon Simple Notification Service (Amazon SNS) topic has been specified for change templates, notifications are sent when the change template is rejected or approved. If you don't receive notifications related to this change template, you can return to Change Manager later to check on its status. Creating change templates using command
systems-manager-ug-471
systems-manager-ug.pdf
471
Edit. If you're satisfied with the contents of the change template, choose Submit for review. The users in your organization or account who have been specified as template reviewers on the Settings tab in Change Manager are notified that a new change template is pending their review. If an Amazon Simple Notification Service (Amazon SNS) topic has been specified for change templates, notifications are sent when the change template is rejected or approved. If you don't receive notifications related to this change template, you can return to Change Manager later to check on its status. Creating change templates using command line tools The following procedures describe how to use the AWS Command Line Interface (AWS CLI) (on Linux, macOS, or Windows) or AWS Tools for Windows PowerShell to create a change request in Change Manager, a tool in AWS Systems Manager. To create a change template 1. Install and configure the AWS CLI or the AWS Tools for PowerShell, if you haven't already. For information, see Installing or updating the latest version of the AWS CLI and Installing the AWS Tools for PowerShell. 2. Create a JSON file on your local machine with a name such as MyChangeTemplate.json, and then paste the content for your change template into it. Note Change templates use a version of schema 0.3 that doesn't include all the same support as for Automation runbooks. The following is an example. Change Manager 1603 AWS Systems Manager Note User Guide The parameter minRequiredApprovals is used to specify how many reviewers at a specified level must approve a change request that is created using this template. This example demonstrates two levels of approvals. You can specify up to five levels of approvals, but only one level is required. In the first level, the specific user "John-Doe" must approve each change request. After that, any three members of the IAM role Admin must approve the change request. For more information about approvals for change templates, see About approvals in your change templates. { "description": "This change template demonstrates the feature set available for creating change templates for Change Manager. This template starts a Runbook workflow for the Automation runbook called AWS-HelloWorld", "templateInformation": "### Document Name: HelloWorldChangeTemplate\n\n ## What does this document do?\n This change template demonstrates the feature set available for creating change templates for Change Manager. This template starts a Runbook workflow for the Automation runbook called AWS- HelloWorld.\n\n ## Input Parameters\n* ApproverSnsTopicArn: (Required) Amazon Simple Notification Service ARN for approvers.\n * Approver: (Required) The name of the approver to send this request to.\n * ApproverType: (Required) The type of reviewer. * Allowed Values: IamUser, IamGroup, IamRole, SSOGroup, SSOUser\n\n ## Output Parameters\nThis document has no outputs\n", "schemaVersion": "0.3", "parameters": { "ApproverSnsTopicArn": { "type": "String", "description": "Amazon Simple Notification Service ARN for approvers." }, "Approver": { "type": "String", "description": "IAM approver" }, "ApproverType": { Change Manager 1604 AWS Systems Manager User Guide "type": "String", "description": "Approver types for the request. Allowed values include IamUser, IamGroup, IamRole, SSOGroup, and SSOUser." } }, "executableRunBooks": [ { "name": "AWS-HelloWorld", "version": "1" } ], "emergencyChange": false, "autoApprovable": false, "mainSteps": [ { "name": "ApproveAction1", "action": "aws:approve", "timeoutSeconds": 3600, "inputs": { "Message": "A sample change request has been submitted for your review in Change Manager. You can approve or reject this request.", "EnhancedApprovals": { "NotificationArn": "{{ ApproverSnsTopicArn }}", "Approvers": [ { "approver": "John-Doe", "type": "IamUser", "minRequiredApprovals": 1 } ] } } }, { "name": "ApproveAction2", "action": "aws:approve", "timeoutSeconds": 3600, "inputs": { "Message": "A sample change request has been submitted for your review in Change Manager. You can approve or reject this request.", "EnhancedApprovals": { "NotificationArn": "{{ ApproverSnsTopicArn }}", "Approvers": [ { Change Manager 1605 AWS Systems Manager User Guide "approver": "Admin", "type": "IamRole", "minRequiredApprovals": 3 } ] } } } ] } 3. Run the following command to create the change template. Linux & macOS aws ssm create-document \ --name MyChangeTemplate \ --document-format JSON \ --document-type Automation.ChangeTemplate \ --content file://MyChangeTemplate.json \ --tags Key=tag-key,Value=tag-value Windows aws ssm create-document ^ --name MyChangeTemplate ^ --document-format JSON ^ --document-type Automation.ChangeTemplate ^ --content file://MyChangeTemplate.json ^ --tags Key=tag-key,Value=tag-value PowerShell $json = Get-Content -Path "C:\path\to\file\MyChangeTemplate.json" | Out-String New-SSMDocument ` -Content $json ` -Name "MyChangeTemplate" ` -DocumentType "Automation.ChangeTemplate" ` -Tags "Key=tag-key,Value=tag-value" For information about other options you can specify, see create-document. Change Manager 1606 AWS Systems Manager User Guide The system returns information like the following. { "DocumentDescription":{ "CreatedDate":1.585061751738E9, "DefaultVersion":"1", "Description":"Use this template to update an EC2 Linux AMI. Requires one approver specified in the template and an approver specified in the request.", "DocumentFormat":"JSON", "DocumentType":"Automation", "DocumentVersion":"1", "Hash":"0d3d879b3ca072e03c12638d0255ebd004d2c65bd318f8354fcde820dEXAMPLE", "HashType":"Sha256", "LatestVersion":"1", "Name":"MyChangeTemplate", "Owner":"123456789012", "Parameters":[ { "DefaultValue":"", "Description":"Level one approvers", "Name":"LevelOneApprovers", "Type":"String" }, { "DefaultValue":"", "Description":"Level one approver type", "Name":"LevelOneApproverType", "Type":"String" }, "cloudWatchMonitors": { "monitors": [ "my-cloudwatch-alarm" ] } ], "PlatformTypes":[ "Windows", "Linux" ], "SchemaVersion":"0.3", "Status":"Creating", "Tags":[ Change Manager 1607 AWS Systems Manager User Guide ]
systems-manager-ug-472
systems-manager-ug.pdf
472
about other options you can specify, see create-document. Change Manager 1606 AWS Systems Manager User Guide The system returns information like the following. { "DocumentDescription":{ "CreatedDate":1.585061751738E9, "DefaultVersion":"1", "Description":"Use this template to update an EC2 Linux AMI. Requires one approver specified in the template and an approver specified in the request.", "DocumentFormat":"JSON", "DocumentType":"Automation", "DocumentVersion":"1", "Hash":"0d3d879b3ca072e03c12638d0255ebd004d2c65bd318f8354fcde820dEXAMPLE", "HashType":"Sha256", "LatestVersion":"1", "Name":"MyChangeTemplate", "Owner":"123456789012", "Parameters":[ { "DefaultValue":"", "Description":"Level one approvers", "Name":"LevelOneApprovers", "Type":"String" }, { "DefaultValue":"", "Description":"Level one approver type", "Name":"LevelOneApproverType", "Type":"String" }, "cloudWatchMonitors": { "monitors": [ "my-cloudwatch-alarm" ] } ], "PlatformTypes":[ "Windows", "Linux" ], "SchemaVersion":"0.3", "Status":"Creating", "Tags":[ Change Manager 1607 AWS Systems Manager User Guide ] } } The users in your organization or account who have been specified as template reviewers on the Settings tab in Change Manager are notified that a new change template is pending their review. If an Amazon Simple Notification Service (Amazon SNS) topic has been specified for change templates, notifications are sent when the change template is rejected or approved. If you don't receive notifications related to this change template, you can return to Change Manager later to check on its status. Reviewing and approving or rejecting change templates If you're specified as a reviewer for change templates in Change Manager, a tool in AWS Systems Manager, you're notified when a new change template, or new version of a change template, is awaiting your review. An Amazon Simple Notification Service (Amazon SNS) topic sends the notifications. Note This functionality depends on whether your account has been configured to use an Amazon SNS topic to send change template review notifications. For information about specifying a template reviewer notification topic, see Task 1: Configuring Change Manager user identity management and template reviewers. To review the change template, follow the link in your notification, sign in to the AWS Management Console, and follow the steps in this procedure. To review and approve or reject a change template 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- 2. 3. manager/. In the navigation pane, choose Change Manager. In the Change templates section at the bottom of the Overview tab, choose the number in Pending review. Change Manager 1608 AWS Systems Manager User Guide 4. 5. In the Change templates list, locate and choose the name of change template to review. In the summary page, review the proposed content of the change template and do one of the following: • To approve the change template, which allows it to be used in change requests, choose Approve. • To reject the change template, which prevents it from being used in change requests, choose Reject. Deleting change templates This topic describes how to delete templates that you have created in Change Manager, a tool in Systems Manager. If you are using Change Manager for an organization, this procedure is performed in your delegated administrator account. 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Change Manager. 3. Choose the Templates tab. 4. Choose the name of the template to delete. 5. Choose Actions, Delete template. 6. In the confirmation dialog, enter the word DELETE, and then choose Delete. Working with change requests A change request is a request in Change Manager to run an Automation runbook that updates one or more resources in your AWS or on-premises environments. A change request is created using a change template. When you create a change request in Change Manager, a tool in AWS Systems Manager, one or more approvers in your organization or account must review and approve the request. Without the required approvals, the runbook workflow, which makes the changes you request, isn't permitted to run. Topics • Creating change requests Change Manager 1609 AWS Systems Manager User Guide • Reviewing and approving or rejecting change requests Creating change requests When you create a change request in Change Manager, a tool in AWS Systems Manager, the change template you select typically does the following: • Designates approvers for the change request or specifies how many approvals are required • Specifies the Amazon Simple Notification Service (Amazon SNS) topic to use to notify approvers about your change request • Specifies an Amazon CloudWatch alarm to monitor the runbook workflow for the change request • Identifies which Automation runbooks you can choose from to make the requested change In some cases, a change template might be configured so you specify your own Automation runbook to use, and to specify who should review and approve the request. Important If you use Change Manager across an organization, we recommend always making changes from the delegated administrator account. Although you can make changes from other accounts in the organization, those changes won't be reported in or viewable from the delegated administrator account. Topics • About change request approvals • Creating change requests (console) • Creating change requests
systems-manager-ug-473
systems-manager-ug.pdf
473
• Identifies which Automation runbooks you can choose from to make the requested change In some cases, a change template might be configured so you specify your own Automation runbook to use, and to specify who should review and approve the request. Important If you use Change Manager across an organization, we recommend always making changes from the delegated administrator account. Although you can make changes from other accounts in the organization, those changes won't be reported in or viewable from the delegated administrator account. Topics • About change request approvals • Creating change requests (console) • Creating change requests (AWS CLI) About change request approvals Depending on the requirements specified in a change template, change requests that you create from it can require approvals from up to five levels before the runbook workflow for the request can occur. For each of those levels, the template creator could specify up to five potential approvers. An approver isn't limited to a single user. An approver in this sense can also be an IAM group or IAM role. For IAM groups and IAM roles, one or more users belonging to the group or Change Manager 1610 AWS Systems Manager User Guide role can provide approvals toward receiving the total number of approvals required for a change request. Template creators can also specify more approvers than the change template requires. Original approval workflows and updated and/or approvals Using change templates created before January 23, 2023, an approval must be received from each specified approver for the change request to be approved at that level. For example, in the approval level setup shown in the following image, four approvers are specified. Specified approvers include two users (John Stiles and Ana Carolina Silva), a user group that contains three members (GroupOfThree), and a user role that represents ten users (RoleOfTen). For the change request to be approved at this level, it must be approved by John Stiles, Ana Carolina Silva, one member of the GroupOfThree group, and one member of the RoleOfTen role. Using change templates created on or after January 23, 2023, for each approval level, template creators can specify an overall total number of required approvals. Those approvals can come from any combination of users, groups, and roles that have been specified as approvers. A change template could require only one approval for a level but specify, for example, two individual users, two groups, and one role as potential approvers. For example, in the approval level area shown in the following image, three approvals are required. The template-specified approvers include two users (John Stiles and Ana Carolina Silva), a user group that contains three members (GroupOfThree), and a user role that represents ten users (RoleOfTen). Change Manager 1611 AWS Systems Manager User Guide If all three users in the GroupOfThree group approve your change request, it is approved for that level. It's not necessary to receive an approval from each user, group, or role. The minimum number of approvals can come from any combination of potential approvers. When your change request is created, notifications are sent to subscribers of the Amazon SNS topic that has been specified for approval notifications at that level. The change template creator might have specified the notification topic that must be used or allowed you to specify one. After the minimum number of required approvals is received at one level, notifications are sent to approvers that are subscribed to the Amazon SNS topic for the next level, and so on. No matter how many approval levels and approvers are specified, only one rejection to a change request is required to prevent the runbook workflow for that request from occurring. Creating change requests (console) The following procedure describes how to create a change request by using the Systems Manager console. Change Manager 1612 AWS Systems Manager User Guide To create a change request (console) 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Change Manager. 3. Choose Create request. 4. Search for and select a change template that you want to use for this change request. 5. Choose Next. 6. For Name, enter a name for the change request that makes its purpose easy to identify, such as UpdateEC2LinuxAMI-us-east-2. 7. For Runbook, select the runbook you want to use to make your requested change. Note If the option to select a runbook isn't available, the change template author has specified which runbook must be used. 8. For Change request information, use Markdown to provide additional information about the change request to help reviewers decide whether to approve or reject the change request. The author of the template you're using might have provided instructions or questions for you to answer. Note Markdown is a markup language that allows you to add wiki-style descriptions
systems-manager-ug-474
systems-manager-ug.pdf
474
purpose easy to identify, such as UpdateEC2LinuxAMI-us-east-2. 7. For Runbook, select the runbook you want to use to make your requested change. Note If the option to select a runbook isn't available, the change template author has specified which runbook must be used. 8. For Change request information, use Markdown to provide additional information about the change request to help reviewers decide whether to approve or reject the change request. The author of the template you're using might have provided instructions or questions for you to answer. Note Markdown is a markup language that allows you to add wiki-style descriptions to documents and individual steps within the document. For more information about using Markdown, see Using Markdown in AWS. 9. In the Workflow start time section, choose one of the following: • Run the operation at a scheduled time – For Requested start time, enter the date and time you propose for running the runbook workflow for this request. For Estimated end time, enter the date and time that you expect the runbook workflow to complete. (This time is an estimate only that you're providing for reviewers.) Change Manager 1613 AWS Systems Manager Tip User Guide Choose View Change Calendar to check for any blocking events for the time you specify. • Run the operation as soon as possible after approval – If the change request is approved, the runbook workflow runs as soon as there is a non-restricted period when changes can be made. 10. In the Change request approvals section, do the following: 1. If Approval type options are presented, choose one of the following: • Automatic approval – The change template you selected is configured to allow change requests to run automatically without review by any approvers. Continue to Step 11. Note The permissions specified in the IAM policies that govern your use of Systems Manager must not restrict you from submitting auto-approval change requests in order for them to run automatically. • Specify approvers – You must add one or more users, groups, or IAM roles to review and approve this change request. Note You can choose to specify reviewers even if the permissions specified in the IAM policies that govern your use of Systems Manager allow you to run auto-approval change requests. 2. Choose Add approver, and then select one or more users, groups, or AWS Identity and Access Management (IAM) roles from the lists of available reviewers. Note One or more approvers might already be specified. This means that mandatory approvers are already specified in the change template you have selected. These approvers can't be removed from the request. If the Add approver button isn't Change Manager 1614 AWS Systems Manager User Guide available, the template you have chosen doesn't allow additional reviewers to be added to requests. For more information about approvals for change requests, see About change request approvals. 3. Under SNS topic to notify approvers, choose one of the following to specify the Amazon SNS topic in your account to use for sending notifications to the approvers you are adding to this change request. Note If the option to specify an Amazon SNS topic isn't available, the change template you selected already specifies the Amazon SNS topic to use. • Enter an SNS Amazon Resource Name (ARN) – For Topic ARN, enter the ARN of an existing Amazon SNS topic. This topic can be in any of your organization's accounts. • Select an existing SNS topic – For Target notification topic, select the ARN of an existing Amazon SNS topic in your current account. (This option isn't available if you haven't yet created any Amazon SNS topics in your current AWS account and AWS Region.) Note The Amazon SNS topic you select must be configured to specify the notifications it sends and the subscribers they're sent to. Its access policy must also grant permissions to Systems Manager so Change Manager can send notifications. For information, see Configuring Amazon SNS topics for Change Manager notifications. 4. Choose Add notification. 11. Choose Next. 12. For IAM role, select an IAM role in your current account that has the permissions needed to run the runbooks that are specified for this change request. This role is also referred to as the service role, or assume role, for Automation. For more information about this role, see Setting up Automation. 13. In the Deployment location section, choose one of the following: Change Manager 1615 AWS Systems Manager Note User Guide If you're using Change Manager with a single AWS account only and not with an organization set up in AWS Organizations, you don't need to specify a deployment location. • Apply change to this account – The runbook workflow runs in the current account only. For an organization, this means the delegated administrator account. • Apply change
systems-manager-ug-475
systems-manager-ug.pdf
475
is also referred to as the service role, or assume role, for Automation. For more information about this role, see Setting up Automation. 13. In the Deployment location section, choose one of the following: Change Manager 1615 AWS Systems Manager Note User Guide If you're using Change Manager with a single AWS account only and not with an organization set up in AWS Organizations, you don't need to specify a deployment location. • Apply change to this account – The runbook workflow runs in the current account only. For an organization, this means the delegated administrator account. • Apply change to multiple organizational units (OUs) – Do the following: 1. For Accounts and organizational units (OUs), enter the ID of a member account in your organization, in the format 123456789012, or the ID of an organizational unit, in the format o-o96EXAMPLE. 2. (Optional) For Execution role name, enter the name of the IAM role in the target account or OU that has the permissions needed to run the runbooks that are specified for this change request. All accounts in any OU you specify should use the same name for this role. 3. (Optional) Choose Add another target location for each additional account or OU you want to specify and repeat steps a and b. 4. For Target AWS Region, select the Region to make the change in, such as Ohio (us- east-2) for the US East (Ohio) Region. 5. Expand Rate control. For Concurrency, enter a number, then from the list select whether this represents the number or percentage of accounts the runbook workflow can run in at the same time. For Error threshold, enter a number, then from the list select whether this represents the number or percentage of accounts where runbook workflow can fail before the operation is stopped. 14. In the Deployment targets section, do the following: 1. Choose one of the following: • Single resource – The change is to be made for just one resource. For example, a single node or a single Amazon Machine Image (AMI), depending on the operation defined in the runbooks for this change request. Change Manager 1616 AWS Systems Manager User Guide • Multiple resources – For Parameter, select from the available parameters from the runbooks for this change request. This selection reflects the type of resource being updated. For example, if the runbook for this change request is AWS-RetartEC2Instance, you might choose InstanceId, and then define which instances are updated by selecting from the following: • Specify tags – Enter a key-value pair that all resources to be updated are tagged with. • Choose a resource group – Choose the name of the resource group that all resources to be updated belong to. • Specify parameter values – Identify the resources to update in the Runbook parameters section. • Target all instances – Make the change on all managed nodes in the target locations. 2. If you chose Multiple resources, expand Rate control. For Concurrency, enter a number, then from the list select whether this represents the number or percentage of targets the runbook workflow can update at the same time. For Error threshold, enter a number, then from the list select whether this represents the number or percentage of targets where the update can fail before the operation is stopped. 15. If you chose Specify parameter values to update multiple resources in the previous step: In the Runbook parameters section, specify values for the required input parameters. The parameter values you must supply are based on the contents of the Automation runbooks associated with the change template you chose. For example, if the change template uses the AWS-RetartEC2Instance runbook, then you must enter one or more instance IDs for the InstanceId parameter. Alternatively, choose Show interactive instance picker and select available instances one by one. 16. Choose Next. 17. In the Review and submit page, double-check the resources and options you have specified for this change request. Choose the Edit button for any section you want to make changes to. When you're satisfied with the change request details, choose Submit for approval. Change Manager 1617 AWS Systems Manager User Guide If an Amazon SNS topic has been specified in the change template you chose for the request, notifications are sent when the request is rejected or approved. If you don't receive notifications for the request, you can return to Change Manager to check the status of your request. Creating change requests (AWS CLI) You can create a change request using the AWS Command Line Interface (AWS CLI) by specifying options and parameters for the change request in a JSON file and using the --cli-input-json option to include it in your command. To create a change request (AWS CLI) 1. Install and configure the AWS CLI or the AWS
systems-manager-ug-476
systems-manager-ug.pdf
476
in the change template you chose for the request, notifications are sent when the request is rejected or approved. If you don't receive notifications for the request, you can return to Change Manager to check the status of your request. Creating change requests (AWS CLI) You can create a change request using the AWS Command Line Interface (AWS CLI) by specifying options and parameters for the change request in a JSON file and using the --cli-input-json option to include it in your command. To create a change request (AWS CLI) 1. Install and configure the AWS CLI or the AWS Tools for PowerShell, if you haven't already. For information, see Installing or updating the latest version of the AWS CLI and Installing the AWS Tools for PowerShell. 2. Create a JSON file on your local machine with a name such as MyChangeRequest.json and paste the following content into it. Replace placeholders with values for your change request. Note This sample JSON creates a change request using the AWS- HelloWorldChangeTemplate change template and AWS-HelloWorld runbook. To help you adapt this sample for your own change requests, see StartChangeRequestExecution in the AWS Systems Manager API Reference for information about all available parameters For more information about approvals for change requests, see About change request approvals. { "ChangeRequestName": "MyChangeRequest", "DocumentName": "AWS-HelloWorldChangeTemplate", "DocumentVersion": "$DEFAULT", "ScheduledTime": "2021-12-30T03:00:00", "ScheduledEndTime": "2021-12-30T03:05:00", "Tags": [ { Change Manager 1618 AWS Systems Manager User Guide "Key": "Purpose", "Value": "Testing" } ], "Parameters": { "Approver": [ "JohnDoe" ], "ApproverType": [ "IamUser" ], "ApproverSnsTopicArn": [ "arn:aws:sns:us-east-2:123456789012:MyNotificationTopic" ] }, "Runbooks": [ { "DocumentName": "AWS-HelloWorld", "DocumentVersion": "1", "MaxConcurrency": "1", "MaxErrors": "1", "Parameters": { "AutomationAssumeRole": [ "arn:aws:iam::123456789012:role/MyChangeManagerAssumeRole" ] } } ], "ChangeDetails": "### Document Name: HelloWorldChangeTemplate\n\n## What does this document do?\nThis change template demonstrates the feature set available for creating change templates for Change Manager. This template starts a Runbook workflow for the Automation document called AWS-HelloWorld.\n\n## Input Parameters \n* ApproverSnsTopicArn: (Required) Amazon Simple Notification Service ARN for approvers.\n* Approver: (Required) The name of the approver to send this request to.\n* ApproverType: (Required) The type of reviewer.\n * Allowed Values: IamUser, IamGroup, IamRole, SSOGroup, SSOUser\n\n## Output Parameters\nThis document has no outputs \n" } 3. In the directory where you created the JSON file, run the following command. aws ssm start-change-request-execution --cli-input-json file://MyChangeRequest.json Change Manager 1619 AWS Systems Manager User Guide The system returns information like the following. { "AutomationExecutionId": "b3c1357a-5756-4839-8617-2d2a4EXAMPLE" } Reviewing and approving or rejecting change requests If you're specified as a reviewer for a change request in Change Manager, a tool in AWS Systems Manager, you're notified through an Amazon Simple Notification Service (Amazon SNS) topic when a new change request is awaiting your review. Note This functionality depends on whether an Amazon SNS was specified in the change template for sending review notifications. For information, see Configuring Amazon SNS topics for Change Manager notifications. To review the change request, you can follow the link in your notification, or sign in to the AWS Management Console directly and follow the steps in this procedure. Note If an Amazon SNS topic is assigned for reviewers in a change template, notifications are sent to the topic's subscribers when the change request changes status. For more information about approvals for change requests, see About change request approvals. Reviewing and approving or rejecting change requests (console) The following procedures describe how to use the Systems Manager console to review and approve or reject change requests. Change Manager 1620 AWS Systems Manager User Guide To review and approve or reject a single change request 1. Open the link in the email notification you received and sign in to the AWS Management Console, which directs you to the change request for your review. 2. In the summary page, review the proposed content of the change request. To approve the change request, choose Approve. In the dialog box, provide any comments you want to add for this approval, and then choose Approve. The runbook workflow represented by this request starts to run either when scheduled, or as soon as changes aren't blocked by any restrictions. -or- To reject the change request, choose Reject. In the dialog box, provide any comments you want to add for this rejection, and then choose Reject. To review and approve or reject change requests in bulk 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Change Manager. 3. Choose the Approvals tab. 4. (Optional) Review the details of requests pending your approval by choosing the name of each request, and then return to the Approvals tab. 5. Select the check box of each change request that you want to approve. -or- Select the check box of each change request that you want to reject. 6. In the dialog box, provide any comments you want to add for this
systems-manager-ug-477
systems-manager-ug.pdf
477
Reject. To review and approve or reject change requests in bulk 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Change Manager. 3. Choose the Approvals tab. 4. (Optional) Review the details of requests pending your approval by choosing the name of each request, and then return to the Approvals tab. 5. Select the check box of each change request that you want to approve. -or- Select the check box of each change request that you want to reject. 6. In the dialog box, provide any comments you want to add for this approval or rejection. 7. Depending on whether you're approving or rejecting the selected change requests, choose Approve or Reject. Reviewing and approving or rejecting a change request (command line) The following procedure describes how to use the AWS Command Line Interface (AWS CLI) (on Linux, macOS, or Windows) to review and approve or reject a change request. Change Manager 1621 AWS Systems Manager User Guide To review and approve or reject a change request 1. Install and configure the AWS Command Line Interface (AWS CLI), if you haven't already. For information, see Installing or updating the latest version of the AWS CLI. 2. Create a JSON file on your local machine that specifies the parameters for your AWS CLI call. { "OpsItemFilters": [ { "Key": "OpsItemType", "Values": ["/aws/changerequest"], "Operator": "Equal" } ], "MaxResults": number } You can filter the results for a specific approver by specifying the approver's Amazon Resource Name (ARN) in the JSON file. Here is an example. { "OpsItemFilters": [ { "Key": "OpsItemType", "Values": ["/aws/changerequest"], "Operator": "Equal" }, { "Key": "ChangeRequestByApproverArn", "Values": ["arn:aws:iam::account-id:user/user-name"], "Operator": "Equal" } ], "MaxResults": number } 3. Run the following command to view the maximum number of change requests you specified in the JSON file. Change Manager 1622 AWS Systems Manager Linux & macOS User Guide aws ssm describe-ops-items \ --cli-input-json file://filename.json Windows aws ssm describe-ops-items ^ --cli-input-json file://filename.json 4. Run the following command to approve or reject a change request. Linux & macOS aws ssm send-automation-signal \ --automation-execution-id ID \ --signal-type Approve_or_Reject \ --payload Comment="message" Windows aws ssm send-automation-signal ^ --automation-execution-id ID ^ --signal-type Approve_or_Reject ^ --payload Comment="message" If an Amazon SNS topic has been specified in the change template you chose for the request, notifications are sent when the request is rejected or approved. If you don't receive notifications for the request, you can return to Change Manager to check the status of your request. For information about other options when using this command, see send-automation- signal in the AWS Systems Manager section of the AWS CLI Command Reference. Reviewing change request details, tasks, and timelines (console) You can view information about a change request, including requests for which changes have already been processed, in the dashboard of Change Manager, a tool in AWS Systems Manager. These details include a link to the Automation operation that runs the runbooks that make the Change Manager 1623 AWS Systems Manager User Guide change. An Automation execution ID is generated when the request is created, but the process doesn't run until all approvals have been given and no restrictions are in place to block the change. To review change request details, tasks, and timelines 1. In the navigation pane, choose Change Manager. 2. Choose the Requests tab. 3. In the Change requests section, search for the change request you want to review. You can use the Create date range options to limit results to a specific time period. You can filter requests by the following properties: • Status • Request ID • Approver • Requester For example, to view details about all change requests that have completed successfully in the past 24 hours, do the following: 1. For Create date range, choose 1d. 2. In the search box, select Status, CompletedWithSuccess. 3. In the results, choose the name of the successfully completed change request to review results for. 4. View information about the change request on the following tabs: • Request details – View basic details about the change request, including the requester, the change template, and the Automation runbooks selected for the change. You can also follow a link to the Automation operation details and view information about any runbook parameters specified in the request, Amazon CloudWatch alarms assigned to the change request, and approvals and comments provided for the request. • Task – View information about the task in the change, including task status for completed change requests, the targeted resources, the steps in the associated Automation runbooks, and concurrency and error threshold details. Change Manager 1624 AWS Systems Manager User Guide • Timeline – View a summary of all events associated with the change request, listed by date and time. The summary indicates when the change request was created, actions by
systems-manager-ug-478
systems-manager-ug.pdf
478
details and view information about any runbook parameters specified in the request, Amazon CloudWatch alarms assigned to the change request, and approvals and comments provided for the request. • Task – View information about the task in the change, including task status for completed change requests, the targeted resources, the steps in the associated Automation runbooks, and concurrency and error threshold details. Change Manager 1624 AWS Systems Manager User Guide • Timeline – View a summary of all events associated with the change request, listed by date and time. The summary indicates when the change request was created, actions by assigned approvers, a note of when approved change requests are scheduled to run, runbook workflow details, and status changes for the overall change process and each step in the runbook. • Associated events – View auditable details about change requests that are recorded in AWS CloudTrail Lake. Details include which API actions were run, the request parameters included for those actions, the user account that ran the action, the resources updated during the process, and more. When you enable CloudTrail Lake event tracking, CloudTrail Lake creates an event data store for events related to your change requests. The event details are available for the account or organization where the change request ran. You can turn on CloudTrail Lake event tracking from any change request in your account or organization. For information about enabling CloudTrail Lake integration and creating an event data store, see Monitoring your change request events. Note There is a charge to use CloudTrail Lake. For details, see AWS CloudTrail pricing. Viewing aggregated counts of change requests (command line) You can view aggregated counts of change requests in Change Manager, a tool in AWS Systems Manager, by using the GetOpsSummary API operation. This API operation can return counts for a single AWS account in a single AWS Region or for multiple accounts and multiple Regions. Note If you want to view aggregated counts of change requests for multiple AWS accounts and multiple AWS Regions, you must set up and configure a resource data sync. For more information, see Creating a resource data sync for Inventory. The following procedure describes how to use the AWS Command Line Interface (AWS CLI) (on Linux, macOS, or Windows) to view aggregated counts of change requests. Change Manager 1625 AWS Systems Manager User Guide To view aggregated counts of change requests 1. Install and configure the AWS Command Line Interface (AWS CLI), if you haven't already. For information, see Installing or updating the latest version of the AWS CLI. 2. Run one of the following commands. Single account and Region This command returns a count of all change requests for the AWS account and AWS Region for which your AWS CLI session is configured. Linux & macOS aws ssm get-ops-summary \ --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal \ --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem Windows aws ssm get-ops-summary ^ --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal ^ --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem The call returns information like the following. { "Entities": [ { "Data": { "AWS:OpsItem": { "Content": [ { "Count": "38", "Status": "Open" } ] } } } ] Change Manager 1626 AWS Systems Manager } Multiple accounts and/or Regions User Guide This command returns a count of all change requests for the AWS accounts and AWS Regions specified in the resource data sync. Linux & macOS aws ssm get-ops-summary \ --sync-name resource_data_sync_name \ --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/ changerequests",Type=Equal \ --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem Windows aws ssm get-ops-summary ^ --sync-name resource_data_sync_name ^ --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/ changerequests",Type=Equal ^ --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem The call returns information like the following. { "Entities": [ { "Data": { "AWS:OpsItem": { "Content": [ { "Count": "43", "Status": "Open" }, { "Count": "2", "Status": "Resolved" } ] } Change Manager 1627 AWS Systems Manager User Guide } } ] } Multiple accounts and a specific Region This command returns a count of all change requests for the AWS accounts specified in the resource data sync. However, it only returns data from the Region specified in the command. Linux & macOS aws ssm get-ops-summary \ --sync-name resource_data_sync_name \ --filters Key=AWS:OpsItem.SourceRegion,Values='Region',Type=Equal Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal \ --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem Windows aws ssm get-ops-summary ^ --sync-name resource_data_sync_name ^ --filters Key=AWS:OpsItem.SourceRegion,Values='Region',Type=Equal Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal ^ --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem Multiple accounts and Regions with output grouped by Region This command returns a count of all change requests for the AWS accounts and AWS Regions specified in the resource data sync. The output displays count information per Region. Linux & macOS aws ssm get-ops-summary \ --sync-name resource_data_sync_name \ --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/ changerequests",Type=Equal \ --aggregators '[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"Status","Aggregators": [{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceRegion"}]}]' Change Manager 1628 AWS Systems Manager Windows User Guide aws ssm get-ops-summary ^ --sync-name resource_data_sync_name ^ --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/ changerequests",Type=Equal ^ --aggregators '[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"Status","Aggregators": [{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceRegion"}]}]' The call returns information like the following. { "Entities": [ { "Data": { "AWS:OpsItem": { "Content": [ { "Count": "38", "SourceRegion": "us-east-1", "Status": "Open" }, { "Count": "4", "SourceRegion": "us-east-2", "Status": "Open" }, { "Count": "1",
systems-manager-ug-479
systems-manager-ug.pdf
479
of all change requests for the AWS accounts and AWS Regions specified in the resource data sync. The output displays count information per Region. Linux & macOS aws ssm get-ops-summary \ --sync-name resource_data_sync_name \ --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/ changerequests",Type=Equal \ --aggregators '[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"Status","Aggregators": [{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceRegion"}]}]' Change Manager 1628 AWS Systems Manager Windows User Guide aws ssm get-ops-summary ^ --sync-name resource_data_sync_name ^ --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/ changerequests",Type=Equal ^ --aggregators '[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"Status","Aggregators": [{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceRegion"}]}]' The call returns information like the following. { "Entities": [ { "Data": { "AWS:OpsItem": { "Content": [ { "Count": "38", "SourceRegion": "us-east-1", "Status": "Open" }, { "Count": "4", "SourceRegion": "us-east-2", "Status": "Open" }, { "Count": "1", "SourceRegion": "us-west-1", "Status": "Open" }, { "Count": "2", "SourceRegion": "us-east-2", "Status": "Resolved" } ] } } Change Manager 1629 AWS Systems Manager } ] } User Guide Multiple accounts and Regions with output grouped by accounts and Regions This command returns a count of all change requests for the AWS accounts and AWS Regions specified in the resource data sync. The output groups the count information by accounts and Regions. Linux & macOS aws ssm get-ops-summary \ --sync-name resource_data_sync_name \ --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/ changerequests",Type=Equal \ --aggregators '[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"Status","Aggregators": [{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceAccountId","Aggregators": [{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceRegion"}]}]}]' Windows aws ssm get-ops-summary ^ --sync-name resource_data_sync_name ^ --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/ changerequests",Type=Equal ^ --aggregators '[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"Status","Aggregators": [{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceAccountId","Aggregators": [{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceRegion"}]}]}]' The call returns information like the following. { "Entities": [ { "Data": { "AWS:OpsItem": { "Content": [ Change Manager 1630 AWS Systems Manager User Guide { "Count": "38", "SourceAccountId": "123456789012", "SourceRegion": "us-east-1", "Status": "Open" }, { "Count": "4", "SourceAccountId": "111122223333", "SourceRegion": "us-east-2", "Status": "Open" }, { "Count": "1", "SourceAccountId": "111122223333", "SourceRegion": "us-west-1", "Status": "Open" }, { "Count": "2", "SourceAccountId": "444455556666", "SourceRegion": "us-east-2", "Status": "Resolved" }, { "Count": "1", "SourceAccountId": "222222222222", "SourceRegion": "us-east-1", "Status": "Open" } ] } } } ] } Auditing and logging Change Manager activity You can audit activity in Change Manager, a tool in AWS Systems Manager, by using Amazon CloudWatch and AWS CloudTrail alarms. Change Manager 1631 AWS Systems Manager User Guide For more information about auditing and logging options for Systems Manager, see Logging and monitoring in AWS Systems Manager. Audit Change Manager activity using CloudWatch alarms You can configure and assign a CloudWatch alarm to a change template. If any conditions defined in the alarm are met, the actions specified for the alarm are taken. In the alarm configuration, you can specify an Amazon Simple Notification Service (Amazon SNS) topic to notify when an alarm condition is met. For information about creating a Change Manager template, see Working with change templates. For information about creating CloudWatch alarms, see Using CloudWatch Alarms in the Amazon CloudWatch User Guide. Audit Change Manager activity using CloudTrail CloudTrail captures API calls made in the Systems Manager console, the AWS Command Line Interface (AWS CLI), and the Systems Manager SDK. You can view the information in the CloudTrail console or in an Amazon Simple Storage Service (Amazon S3) bucket, where it's stored. One bucket is used for all CloudTrail logs for your account. Logs of Change Manager actions show change template document creation, change template and change request approvals and rejections, activity generated by Automation runbooks, and more. For more information about viewing and using CloudTrail logs of Systems Manager activity, see Logging AWS Systems Manager API calls with AWS CloudTrail. Troubleshooting Change Manager Use the following information to help you troubleshoot problems with Change Manager, a tool in AWS Systems Manager. Topics • “Group {GUID} not found” error during change request approvals when using Active Directory (groups Change Manager 1632 AWS Systems Manager User Guide “Group {GUID} not found” error during change request approvals when using Active Directory (groups Problem: When AWS IAM Identity Center (IAM Identity Center) is used for user identity management, a member of an Active Directory group who is granted approval permissions in Change Manager receives a “not authorized” or “group not found” error. • Solution: When you select Active Directory groups in IAM Identity Center for access to the AWS Management Console, the system schedules a periodic synchronization that copies information from those Active Directory groups into IAM Identity Center. This process must complete before users authorized through Active Directory group membership can successfully approve a request. For more information, see Connect to your Microsoft AD directory in the AWS IAM Identity Center User Guide. AWS Systems Manager Documents An AWS Systems Manager document (SSM document) defines the actions that Systems Manager performs on your managed instances. Systems Manager includes more than 100 pre-configured documents that you can use by specifying parameters at runtime. You can find pre-configured documents in the Systems Manager Documents console by choosing the Owned by Amazon tab, or by specifying Amazon for the Owner filter when calling the ListDocuments API operation. Documents use JavaScript Object Notation (JSON) or YAML, and they include steps and parameters that you specify. To get started with SSM documents,
systems-manager-ug-480
systems-manager-ug.pdf
480
AWS IAM Identity Center User Guide. AWS Systems Manager Documents An AWS Systems Manager document (SSM document) defines the actions that Systems Manager performs on your managed instances. Systems Manager includes more than 100 pre-configured documents that you can use by specifying parameters at runtime. You can find pre-configured documents in the Systems Manager Documents console by choosing the Owned by Amazon tab, or by specifying Amazon for the Owner filter when calling the ListDocuments API operation. Documents use JavaScript Object Notation (JSON) or YAML, and they include steps and parameters that you specify. To get started with SSM documents, open the Systems Manager console. In the navigation pane, choose Documents. Important In Systems Manager, an Amazon-owned SSM document is a document created and managed by Amazon Web Services itself. Amazon-owned documents include a prefix like AWS-* in the document name. The owner of the document is considered to be Amazon, not a specific user account within AWS. These documents are publicly available for all to use. How can the Documents tool benefit my organization? Documents, a tool in AWS Systems Manager, offers these benefits: • Document categories Documents 1633 AWS Systems Manager User Guide To help you find the documents you need, choose a category depending on the type of document you're searching for. To broaden your search, you can choose multiple categories of the same document type. Choosing categories of different document types is not supported. Categories are only supported for documents owned by Amazon. • Document versions You can create and save different versions of documents. You can then specify a default version for each document. The default version of a document can be updated to a newer version or reverted to an older version of the document. When you change the content of a document, Systems Manager automatically increments the version of the document. You can retrieve or use any version of a document by specifying the document version in the console, AWS Command Line Interface (AWS CLI) commands, or API calls. • Customize documents for your needs If you want to customize the steps and actions in a document, you can create your own. The system stores the document with your AWS account in the AWS Region you create it in. For more information about how to create an SSM document, see Creating SSM document content. • Tag documents You can tag your documents to help you quickly identify one or more documents based on the tags you've assigned to them. For example, you can tag documents for specific environments, departments, users, groups, or periods. You can also restrict access to documents by creating an AWS Identity and Access Management (IAM) policy that specifies the tags that a user or group can access. • Share documents You can make your documents public or share them with specific AWS accounts in the same AWS Region. Sharing documents between accounts can be useful if, for example, you want all of the Amazon Elastic Compute Cloud (Amazon EC2) instances that you supply to customers or employees to have the same configuration. In addition to keeping applications or patches on the instances up to date, you might want to restrict customer instances from certain activities. Or you might want to ensure that the instances used by employee accounts throughout your organization are granted access to specific internal resources. For more information, see Sharing SSM documents. Documents 1634 AWS Systems Manager User Guide Who should use Documents? • Any AWS customer who wants to use Systems Manager tools to improve their operational efficiency at scale, reduce errors associated with manual intervention, and reduce time to resolution of common issues. • Infrastructure experts who want to automate deployment and configuration tasks. • Administrators who want to reliably resolve common issues, improve troubleshooting efficiency, and reduce repetitive operations. • Users who want to automate a task they normally perform manually. What are the types of SSM documents? The following table describes the different types of SSM documents and their uses. Type Use with Details ApplicationConfiguration AWS AppConfig ApplicationConfigurationSch ema AWS AppConfig, a tool in AWS Systems Manager, enables you to create, manage, and quickly deploy application configurations. You can store configuration data in an SSM document by creating a document that uses the Applicati onConfiguration document type. For more information, see Freeform configurations in the AWS AppConfig User Guide. If you create a configuration in an SSM document, then you must specify a correspon ding JSON Schema. The schema uses the Applicati Documents 1635 AWS Systems Manager User Guide Type Use with Details Automation runbook Automation State Manager Maintenance Windows onConfigurationSch ema document type and, like a set of rules, defines the allowable properties for each application configuration setting. For more information, see About validators in the AWS AppConfig User Guide. Use
systems-manager-ug-481
systems-manager-ug.pdf
481
in an SSM document by creating a document that uses the Applicati onConfiguration document type. For more information, see Freeform configurations in the AWS AppConfig User Guide. If you create a configuration in an SSM document, then you must specify a correspon ding JSON Schema. The schema uses the Applicati Documents 1635 AWS Systems Manager User Guide Type Use with Details Automation runbook Automation State Manager Maintenance Windows onConfigurationSch ema document type and, like a set of rules, defines the allowable properties for each application configuration setting. For more information, see About validators in the AWS AppConfig User Guide. Use Automation runbooks when performing common maintenance and deploymen t tasks such as creating or updating an Amazon Machine Image (AMI). State Manager uses Automation runbooks to apply a configuration. These actions can be run on one or more targets at any point during the lifecycle of an instance. Maintenan ce Windows uses Automatio n runbooks to perform common maintenance and deployment tasks based on the specified schedule. All Automation runbooks that are supported for Linux-bas ed operating systems are also supported on EC2 instances for macOS. Documents 1636 AWS Systems Manager User Guide Type Use with Details Change Calendar document Change Calendar Change Calendar, a tool in AWS Systems Manager, uses the ChangeCalendar document type. A Change Calendar document stores a calendar entry and associate d events that can allow or prevent Automation actions from changing your environment. In Change Calendar, a document stores iCalendar 2.0 data in plaintext format. Change Calendar isn't supported on EC2 instances for macOS. Documents 1637 AWS Systems Manager User Guide Type Use with Details AWS CloudFormation template AWS CloudFormation AWS CloudFormation templates describe the resources that you want to provision in your CloudForm ation stacks. By storing CloudFormation templates as Systems Manager documents, you can benefit from Systems Manager document features. These include creating and comparing multiple versions of your template, and sharing your template with other accounts in the same AWS Region. You can create and edit CloudFormation templates and stacks by using Applicati on Manager, a tool in Systems Manager. For more informati on, see Working with AWS CloudFormation templates and stacks in Application Manager. Documents 1638 AWS Systems Manager User Guide Type Use with Details Command document Run Command State Manager Maintenance Windows Run Command, a tool in AWS Systems Manager, uses Command documents to run commands. State Manager, a tool in AWS Systems Manager, uses command documents to apply a configuration. These actions can be run on one or more targets at any point during the lifecycle of an instance. Maintenance Windows, a tool in AWS Systems Manager, uses Command documents to apply a configuration based on the specified schedule. Most Command documents are supported on all Linux and Windows Server operating systems supported by Systems Manager. The following Command documents are supported on EC2 instances for macOS: • AWS-ConfigureAWSPa ckage • AWS-RunPatchBaseli ne • AWS-RunPatchBaseli neAssociation • AWS-RunShellScript Documents 1639 AWS Systems Manager Type AWS Config conformance pack template Use with AWS Config Package document Distributor User Guide Details AWS Config conformance pack templates are YAML formatted documents used to create conformance packs that contains the list of AWS Config managed or custom rules and remediation actions. For more information, see Conformance Packs. In Distributor, a tool in AWS Systems Manager, a package is represented by an SSM document. A package document includes attached ZIP archive files that contain software or assets to install on managed instances. Creating a package in Distributor creates the package document. Distributor isn't supported on Oracle Linux and macOS managed instances. Documents 1640 AWS Systems Manager User Guide Type Use with Details Policy document State Manager Inventory, a tool in AWS Systems Manager, uses the AWS-GatherSoftware Inventory Policy document with a State Manager association to collect inventory data from managed instances. When creating your own SSM documents, Automation runbooks and Command documents are the preferred method for enforcing a policy on a managed instance. Systems Manager Inventory and the AWS-Gathe rSoftwareInventory Policy document are supported on all operating systems supported by Systems Manager. Post-incident analysis template Incident Manager post-inci dent analysis Incident Manager uses the post-incident analysis template to create an analysis based on AWS operations management best practices. Use the template to create an analysis that your team can use to identify improvements to your incident response. Documents 1641 AWS Systems Manager User Guide Type Use with Details Session document Session Manager Session Manager, a tool in AWS Systems Manager, uses Session documents to determine which type of session to start, such as a port forwarding session, a session to run an interacti ve command, or a session to create an SSH tunnel. Session documents are supported on all Linux and Windows Server operating systems supported by Systems Manager. The following Command documents
systems-manager-ug-482
systems-manager-ug.pdf
482
AWS operations management best practices. Use the template to create an analysis that your team can use to identify improvements to your incident response. Documents 1641 AWS Systems Manager User Guide Type Use with Details Session document Session Manager Session Manager, a tool in AWS Systems Manager, uses Session documents to determine which type of session to start, such as a port forwarding session, a session to run an interacti ve command, or a session to create an SSH tunnel. Session documents are supported on all Linux and Windows Server operating systems supported by Systems Manager. The following Command documents are supported on EC2 instances for macOS: • AWS-PasswordReset • AWS-StartInteracti veCommand • AWS-StartPortForwa rdingSession • AWS-StartPortForwa rdingSessionToSock et • AWS-StartSSHSession SSM document quotas For information about SSM document quotas, see Systems Manager service quotas in the Amazon Web Services General Reference. Documents 1642 AWS Systems Manager Topics • Document components • Creating SSM document content • Working with documents Document components User Guide This section includes information about the components that make up SSM documents. Contents • Schemas, features, and examples • Data elements and parameters • Command document plugin reference Schemas, features, and examples AWS Systems Manager (SSM) documents use the following schema versions. • Documents of type Command can use schema version 1.2, 2.0, and 2.2. If you use schema 1.2 documents, we recommend that you create documents that use schema version 2.2. • Documents of type Policy must use schema version 2.0 or later. • Documents of type Automation must use schema version 0.3. • Documents of type Session must use schema version 1.0. • You can create documents in JSON or YAML. For more information about Session document schema, see Session document schema. By using the latest schema version for Command and Policy documents, you can take advantage of the following features. Documents 1643 AWS Systems Manager User Guide Schema version 2.2 document features Feature Document editing Automatic versioning Default version Sequencing Cross-platform support Details Documents can now be updated. With version 1.2, any update to a document required that you save it with a different name. Any update to a document creates a new version. This isn't a schema version, but a version of the document. If you have multiple versions of a document, you can specify which version is the default document. Plugins or steps in a document run in the order that you specified. Cross-platform support allows you to specify different operating systems for different plugins within the same SSM document. Cross-platform support uses the precondit ion parameter within a step. Note You must keep AWS Systems Manager SSM Agent on your instances updated with the latest version to use new Systems Manager features and SSM document features. For more information, see Updating the SSM Agent using Run Command. The following table lists the differences between major schema versions. Version 1.2 Version 2.2 (latest version) Details runtimeConfig mainSteps In version 2.2, the mainSteps section replaces Documents 1644 AWS Systems Manager User Guide Version 1.2 Version 2.2 (latest version) Details runtimeConfig . The mainSteps section allows Systems Manager to run steps in sequence. In version 2.2, the inputs section replaces the properties section. The inputs section accepts parameters for steps. In version 2.2, the inputs section takes the runComman d parameter instead of the commands parameter. In version 2.2, Action replaces ID. This is just a name change. In version 2.2, name is any user-defined name for a step. properties inputs commands runCommand id action not applicable name Using the precondition parameter With schema version 2.2 or later, you can use the precondition parameter to specify the target operating system for each plugin or to validate input parameters you've defined in your SSM document. The precondition parameter supports referencing your SSM document's input parameters, and platformType using values of Linux, MacOS, and Windows. Only the StringEquals operator is supported. For documents that use schema version 2.2 or later, if precondition isn't specified, each plugin is either run or skipped based on the plugin’s compatibility with the operating system. Plugin compatibility with the operating system is evaluated before the precondition. For documents that use schema 2.0 or earlier, incompatible plugins throw an error. Documents 1645 AWS Systems Manager User Guide For example, in a schema version 2.2 document, if precondition isn't specified and the aws:runShellScript plugin is listed, then the step runs on Linux instances, but the system skips it on Windows Server instances because the aws:runShellScript isn't compatible with Windows Server instances. However, for a schema version 2.0 document, if you specify the aws:runShellScript plugin, and then run the document on a Windows Server instances, the execution fails. You can see an example of the precondition parameter in an SSM document later in this section. Schema version 2.2 Top-level elements The following example
systems-manager-ug-483
systems-manager-ug.pdf
483
1645 AWS Systems Manager User Guide For example, in a schema version 2.2 document, if precondition isn't specified and the aws:runShellScript plugin is listed, then the step runs on Linux instances, but the system skips it on Windows Server instances because the aws:runShellScript isn't compatible with Windows Server instances. However, for a schema version 2.0 document, if you specify the aws:runShellScript plugin, and then run the document on a Windows Server instances, the execution fails. You can see an example of the precondition parameter in an SSM document later in this section. Schema version 2.2 Top-level elements The following example shows the top-level elements of an SSM document using schema version 2.2. YAML --- schemaVersion: "2.2" description: A description of the document. parameters: parameter 1: property 1: "value" property 2: "value" parameter 2: property 1: "value" property 2: "value" mainSteps: - action: Plugin name name: A name for the step. inputs: input 1: "value" input 2: "value" input 3: "{{ parameter 1 }}" JSON { "schemaVersion": "2.2", "description": "A description of the document.", "parameters": { "parameter 1": { Documents 1646 AWS Systems Manager User Guide "property 1": "value", "property 2": "value" }, "parameter 2":{ "property 1": "value", "property 2": "value" } }, "mainSteps": [ { "action": "Plugin name", "name": "A name for the step.", "inputs": { "input 1": "value", "input 2": "value", "input 3": "{{ parameter 1 }}" } } ] } Schema version 2.2 example The following example uses the aws:runPowerShellScript plugin to run a PowerShell command on the target instances. YAML --- schemaVersion: "2.2" description: "Example document" parameters: Message: type: "String" description: "Example parameter" default: "Hello World" allowedValues: - "Hello World" mainSteps: - action: "aws:runPowerShellScript" name: "example" inputs: Documents 1647 AWS Systems Manager User Guide timeoutSeconds: '60' runCommand: - "Write-Output {{Message}}" JSON { "schemaVersion": "2.2", "description": "Example document", "parameters": { "Message": { "type": "String", "description": "Example parameter", "default": "Hello World", "allowedValues": ["Hello World"] } }, "mainSteps": [ { "action": "aws:runPowerShellScript", "name": "example", "inputs": { "timeoutSeconds": "60", "runCommand": [ "Write-Output {{Message}}" ] } } ] } Schema version 2.2 precondition parameter examples Schema version 2.2 provides cross-platform support. This means that within a single SSM document you can specify different operating systems for different plugins. Cross-platform support uses the precondition parameter within a step, as shown in the following example. You can also use the precondition parameter to validate input parameters you've defined in your SSM document. You can see this in the second of the following examples. Documents 1648 User Guide AWS Systems Manager YAML --- schemaVersion: '2.2' description: cross-platform sample mainSteps: - action: aws:runPowerShellScript name: PatchWindows precondition: StringEquals: - platformType - Windows inputs: runCommand: - cmds - action: aws:runShellScript name: PatchLinux precondition: StringEquals: - platformType - Linux inputs: runCommand: - cmds JSON { "schemaVersion": "2.2", "description": "cross-platform sample", "mainSteps": [ { "action": "aws:runPowerShellScript", "name": "PatchWindows", "precondition": { "StringEquals": [ "platformType", "Windows" ] }, "inputs": { "runCommand": [ "cmds" Documents 1649 AWS Systems Manager ] } }, { "action": "aws:runShellScript", User Guide "name": "PatchLinux", "precondition": { "StringEquals": [ "platformType", "Linux" ] }, "inputs": { "runCommand": [ "cmds" ] } } ] } YAML --- schemaVersion: '2.2' parameters: action: type: String allowedValues: - Install - Uninstall confirmed: type: String allowedValues: - True - False mainSteps: - action: aws:runShellScript name: InstallAwsCLI precondition: StringEquals: - "{{ action }}" Documents 1650 User Guide AWS Systems Manager - "Install" inputs: runCommand: - sudo apt install aws-cli - action: aws:runShellScript name: UninstallAwsCLI precondition: StringEquals: - "{{ action }} {{ confirmed }}" - "Uninstall True" inputs: runCommand: - sudo apt remove aws-cli JSON { "schemaVersion": "2.2", "parameters": { "action": { "type": "String", "allowedValues": [ "Install", "Uninstall" ] }, "confirmed": { "type": "String", "allowedValues": [ true, false ] } }, "mainSteps": [ { "action": "aws:runShellScript", "name": "InstallAwsCLI", "precondition": { "StringEquals": [ "{{ action }}", "Install" ] Documents 1651 User Guide AWS Systems Manager }, "inputs": { "runCommand": [ "sudo apt install aws-cli" ] } }, { "action": "aws:runShellScript", "name": "UninstallAwsCLI", "precondition": { "StringEquals": [ "{{ action }} {{ confirmed }}", "Uninstall True" ] }, "inputs": { "runCommand": [ "sudo apt remove aws-cli" ] } } ] } Schema version 2.2 State Manager example You can use the following SSM document with State Manager, a tool in Systems Manager, to download and install the ClamAV antivirus software. State Manager enforces a specific configuration, which means that each time the State Manager association is run, the system checks to see if the ClamAV software is installed. If not, State Manager reruns this document. YAML --- schemaVersion: '2.2' description: State Manager Bootstrap Example parameters: {} mainSteps: - action: aws:runShellScript name: configureServer inputs: Documents 1652 AWS Systems Manager runCommand: - sudo yum install -y httpd24 - sudo yum --enablerepo=epel install -y clamav User Guide JSON { "schemaVersion": "2.2", "description": "State Manager Bootstrap Example", "parameters": {}, "mainSteps": [ { "action": "aws:runShellScript",
systems-manager-ug-484
systems-manager-ug.pdf
484
Systems Manager, to download and install the ClamAV antivirus software. State Manager enforces a specific configuration, which means that each time the State Manager association is run, the system checks to see if the ClamAV software is installed. If not, State Manager reruns this document. YAML --- schemaVersion: '2.2' description: State Manager Bootstrap Example parameters: {} mainSteps: - action: aws:runShellScript name: configureServer inputs: Documents 1652 AWS Systems Manager runCommand: - sudo yum install -y httpd24 - sudo yum --enablerepo=epel install -y clamav User Guide JSON { "schemaVersion": "2.2", "description": "State Manager Bootstrap Example", "parameters": {}, "mainSteps": [ { "action": "aws:runShellScript", "name": "configureServer", "inputs": { "runCommand": [ "sudo yum install -y httpd24", "sudo yum --enablerepo=epel install -y clamav" ] } } ] } Schema version 2.2 Inventory example You can use the following SSM document with State Manager to collect inventory metadata about your instances. YAML --- schemaVersion: '2.2' description: Software Inventory Policy Document. parameters: applications: type: String default: Enabled description: "(Optional) Collect data for installed applications." allowedValues: - Enabled - Disabled Documents 1653 AWS Systems Manager User Guide awsComponents: type: String default: Enabled description: "(Optional) Collect data for AWS Components like amazon-ssm-agent." allowedValues: - Enabled - Disabled networkConfig: type: String default: Enabled description: "(Optional) Collect data for Network configurations." allowedValues: - Enabled - Disabled windowsUpdates: type: String default: Enabled description: "(Optional) Collect data for all Windows Updates." allowedValues: - Enabled - Disabled instanceDetailedInformation: type: String default: Enabled description: "(Optional) Collect additional information about the instance, including the CPU model, speed, and the number of cores, to name a few." allowedValues: - Enabled - Disabled customInventory: type: String default: Enabled description: "(Optional) Collect data for custom inventory." allowedValues: - Enabled - Disabled mainSteps: - action: aws:softwareInventory name: collectSoftwareInventoryItems inputs: applications: "{{ applications }}" awsComponents: "{{ awsComponents }}" networkConfig: "{{ networkConfig }}" Documents 1654 AWS Systems Manager User Guide windowsUpdates: "{{ windowsUpdates }}" instanceDetailedInformation: "{{ instanceDetailedInformation }}" customInventory: "{{ customInventory }}" JSON { "schemaVersion": "2.2", "description": "Software Inventory Policy Document.", "parameters": { "applications": { "type": "String", "default": "Enabled", "description": "(Optional) Collect data for installed applications.", "allowedValues": [ "Enabled", "Disabled" ] }, "awsComponents": { "type": "String", "default": "Enabled", "description": "(Optional) Collect data for AWS Components like amazon-ssm- agent.", "allowedValues": [ "Enabled", "Disabled" ] }, "networkConfig": { "type": "String", "default": "Enabled", "description": "(Optional) Collect data for Network configurations.", "allowedValues": [ "Enabled", "Disabled" ] }, "windowsUpdates": { "type": "String", "default": "Enabled", "description": "(Optional) Collect data for all Windows Updates.", "allowedValues": [ Documents 1655 AWS Systems Manager User Guide "Enabled", "Disabled" ] }, "instanceDetailedInformation": { "type": "String", "default": "Enabled", "description": "(Optional) Collect additional information about the instance, including\nthe CPU model, speed, and the number of cores, to name a few.", "allowedValues": [ "Enabled", "Disabled" ] }, "customInventory": { "type": "String", "default": "Enabled", "description": "(Optional) Collect data for custom inventory.", "allowedValues": [ "Enabled", "Disabled" ] } }, "mainSteps": [ { "action": "aws:softwareInventory", "name": "collectSoftwareInventoryItems", "inputs": { "applications": "{{ applications }}", "awsComponents": "{{ awsComponents }}", "networkConfig": "{{ networkConfig }}", "windowsUpdates": "{{ windowsUpdates }}", "instanceDetailedInformation": "{{ instanceDetailedInformation }}", "customInventory": "{{ customInventory }}" } } ] } Schema version 2.2 AWS-ConfigureAWSPackage example Documents 1656 AWS Systems Manager User Guide The following example shows the AWS-ConfigureAWSPackage document. The mainSteps section includes the aws:configurePackage plugin in the action step. Note On Linux operating systems, only the AmazonCloudWatchAgent and AWSSupport- EC2Rescue packages are supported. YAML --- schemaVersion: '2.2' description: 'Install or uninstall the latest version or specified version of an AWS package. Available packages include the following: AWSPVDriver, AwsEnaNetworkDriver, AwsVssComponents, and AmazonCloudWatchAgent, and AWSSupport-EC2Rescue.' parameters: action: description: "(Required) Specify whether or not to install or uninstall the package." type: String allowedValues: - Install - Uninstall name: description: "(Required) The package to install/uninstall." type: String allowedPattern: "^arn:[a-z0-9][-.a-z0-9]{0,62}:[a-z0-9][-.a-z0-9]{0,62}:([a- z0-9][-.a-z0-9]{0,62})?:([a-z0-9][-.a-z0-9]{0,62})?:package\\/[a-zA-Z][a-zA-Z0-9\\- _]{0,39}$|^[a-zA-Z][a-zA-Z0-9\\-_]{0,39}$" version: type: String description: "(Optional) A specific version of the package to install or uninstall." mainSteps: - action: aws:configurePackage name: configurePackage inputs: name: "{{ name }}" action: "{{ action }}" version: "{{ version }}" Documents 1657 AWS Systems Manager JSON { User Guide "schemaVersion": "2.2", "description": "Install or uninstall the latest version or specified version of an AWS package. Available packages include the following: AWSPVDriver, AwsEnaNetworkDriver, AwsVssComponents, and AmazonCloudWatchAgent, and AWSSupport- EC2Rescue.", "parameters": { "action": { "description":"(Required) Specify whether or not to install or uninstall the package.", "type":"String", "allowedValues":[ "Install", "Uninstall" ] }, "name": { "description": "(Required) The package to install/uninstall.", "type": "String", "allowedPattern": "^arn:[a-z0-9][-.a-z0-9]{0,62}:[a-z0-9][-.a-z0-9]{0,62}: ([a-z0-9][-.a-z0-9]{0,62})?:([a-z0-9][-.a-z0-9]{0,62})?:package\\/[a-zA-Z][a-zA- Z0-9\\-_]{0,39}$|^[a-zA-Z][a-zA-Z0-9\\-_]{0,39}$" }, "version": { "type": "String", "description": "(Optional) A specific version of the package to install or uninstall." } }, "mainSteps":[ { "action": "aws:configurePackage", "name": "configurePackage", "inputs": { "name": "{{ name }}", "action": "{{ action }}", "version": "{{ version }}" } } ] } Documents 1658 AWS Systems Manager Schema version 1.2 User Guide The following example shows the top-level elements of a schema version 1.2 document. { "schemaVersion":"1.2", "description":"A description of the SSM document.", "parameters":{ "parameter 1":{ "one
systems-manager-ug-485
systems-manager-ug.pdf
485
the package.", "type":"String", "allowedValues":[ "Install", "Uninstall" ] }, "name": { "description": "(Required) The package to install/uninstall.", "type": "String", "allowedPattern": "^arn:[a-z0-9][-.a-z0-9]{0,62}:[a-z0-9][-.a-z0-9]{0,62}: ([a-z0-9][-.a-z0-9]{0,62})?:([a-z0-9][-.a-z0-9]{0,62})?:package\\/[a-zA-Z][a-zA- Z0-9\\-_]{0,39}$|^[a-zA-Z][a-zA-Z0-9\\-_]{0,39}$" }, "version": { "type": "String", "description": "(Optional) A specific version of the package to install or uninstall." } }, "mainSteps":[ { "action": "aws:configurePackage", "name": "configurePackage", "inputs": { "name": "{{ name }}", "action": "{{ action }}", "version": "{{ version }}" } } ] } Documents 1658 AWS Systems Manager Schema version 1.2 User Guide The following example shows the top-level elements of a schema version 1.2 document. { "schemaVersion":"1.2", "description":"A description of the SSM document.", "parameters":{ "parameter 1":{ "one or more parameter properties" }, "parameter 2":{ "one or more parameter properties" }, "parameter 3":{ "one or more parameter properties" } }, "runtimeConfig":{ "plugin 1":{ "properties":[ { "one or more plugin properties" } ] } } } Schema version 1.2 aws:runShellScript example The following example shows the AWS-RunShellScript SSM document. The runtimeConfig section includes the aws:runShellScript plugin. { "schemaVersion":"1.2", "description":"Run a shell script or specify the commands to run.", "parameters":{ "commands":{ "type":"StringList", "description":"(Required) Specify a shell script or a command to run.", "minItems":1, "displayType":"textarea" Documents 1659 AWS Systems Manager }, "workingDirectory":{ "type":"String", "default":"", "description":"(Optional) The path to the working directory on your User Guide instance.", "maxChars":4096 }, "executionTimeout":{ "type":"String", "default":"3600", "description":"(Optional) The time in seconds for a command to complete before it is considered to have failed. Default is 3600 (1 hour). Maximum is 172800 (48 hours).", "allowedPattern":"([1-9][0-9]{0,3})|(1[0-9]{1,4})|(2[0-7][0-9]{1,3})| (28[0-7][0-9]{1,2})|(28800)" } }, "runtimeConfig":{ "aws:runShellScript":{ "properties":[ { "id":"0.aws:runShellScript", "runCommand":"{{ commands }}", "workingDirectory":"{{ workingDirectory }}", "timeoutSeconds":"{{ executionTimeout }}" } ] } } } Schema version 0.3 Top-level elements The following example shows the top-level elements of a schema version 0.3 Automation runbook in JSON format. { "description": "document-description", "schemaVersion": "0.3", "assumeRole": "{{assumeRole}}", "parameters": { Documents 1660 User Guide AWS Systems Manager "parameter1": { "type": "String", "description": "parameter-1-description", "default": "" }, "parameter2": { "type": "String", "description": "parameter-2-description", "default": "" } }, "variables": { "variable1": { "type": "StringMap", "description": "variable-1-description", "default": {} }, "variable2": { "type": "String", "description": "variable-2-description", "default": "default-value" } }, "mainSteps": [ { "name": "myStepName", "action": "action-name", "maxAttempts": 1, "inputs": { "Handler": "python-only-handler-name", "Runtime": "runtime-name", "Attachment": "script-or-zip-name" }, "outputs": { "Name": "output-name", "Selector": "selector.value", "Type": "data-type" } } ], "files": { "script-or-zip-name": { "checksums": { "sha256": "checksum" Documents 1661 AWS Systems Manager }, "size": 1234 } } } YAML Automation runbook example User Guide The following sample shows the contents of an Automation runbook, in YAML format. This working example of version 0.3 of the document schema also demonstrates the use of Markdown to format document descriptions. description: >- ##Title: LaunchInstanceAndCheckState ----- **Purpose**: This Automation runbook first launches an 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 | (Optional) 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 }} schemaVersion: '0.3' assumeRole: 'arn:aws:iam::111122223333::role/AutomationServiceRole' parameters: imageId: type: String default: '{{ ssm:/aws/service/ami-amazon-linux-latest/amzn-ami-hvm-x86_64-gp2 }}' Documents 1662 AWS Systems Manager description: >- User Guide (Optional) The AMI ID to use for launching the instance. The default value uses the latest released Amazon Linux AMI ID. tagValue: type: String default: ' LaunchedBySsmAutomation' description: >- (Optional) The tag value to add to the instance. The default value is LaunchedBySsmAutomation. instanceType: type: String default: t2.micro description: >- (Optional) The instance type to use for the instance. The default value is t2.micro. mainSteps: - name: LaunchEc2Instance action: 'aws:executeScript' outputs: - Name: payload Selector: $.Payload Type: StringMap inputs: Runtime: python3.8 Handler: launch_instance Script: '' InputPayload: image_id: '{{ imageId }}' tag_value: '{{ tagValue }}' instance_type: '{{ instanceType }}' Attachment: launch.py description: >- **About This Step** This step first launches an EC2 instance using the ```aws:executeScript``` action and the provided python script. - name: WaitForInstanceStatusOk action: 'aws:executeScript' inputs: Runtime: python3.8 Handler: poll_instance Script: |- def poll_instance(events, context): Documents 1663 AWS Systems Manager import boto3 import time ec2 = boto3.client('ec2') instance_id = events['InstanceId'] User Guide 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} InputPayload: '{{ LaunchEc2Instance.payload }}' description: >- **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. files:
systems-manager-ug-486
systems-manager-ug.pdf
486
Manager import boto3 import time ec2 = boto3.client('ec2') instance_id = events['InstanceId'] User Guide 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} InputPayload: '{{ LaunchEc2Instance.payload }}' description: >- **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. files: launch.py: checksums: sha256: 18871b1311b295c43d0f...[truncated]...772da97b67e99d84d342ef4aEXAMPLE Documents 1664 AWS Systems Manager Data elements and parameters User Guide This topic describes the data elements used in SSM documents. The schema version used to create a document defines the syntax and data elements that the document accepts. We recommend that you use schema version 2.2 or later for Command documents. Automation runbooks use schema version 0.3. Additionally, Automation runbooks support the use of Markdown, a markup language, which allows you to add wiki-style descriptions to documents and individual steps within the document. For more information about using Markdown, see Using Markdown in the Console in the AWS Management Console Getting Started Guide. The following section describes the data elements that you can include in a SSM document. Top-level data elements schemaVersion The schema version to use. Type: Version Required: Yes description Information you provide to describe the purpose of the document. You can also use this field to specify whether a parameter requires a value for a document to run, or if providing a value for the parameter is optional. Required and optional parameters can be seen in the examples throughout this topic. Type: String Required: No parameters A structure that defines the parameters the document accepts. For parameters that you use often, we recommend that you store those parameters in Parameter Store, a tool in AWS Systems Manager. Then, you can define parameters in your document that reference Parameter Store parameters as their default value. To reference a Parameter Store parameter, use the following syntax. Documents 1665 AWS Systems Manager User Guide {{ssm:parameter-name}} You can use a parameter that references a Parameter Store parameter the same way as any other document parameters. In the following example, the default value for the commands parameter is the Parameter Store parameter myShellCommands. By specifying the commands parameter as a runCommand string, the document runs the commands stored in the myShellCommands parameter. YAML --- schemaVersion: '2.2' description: runShellScript with command strings stored as Parameter Store parameter parameters: commands: type: StringList description: "(Required) The commands to run on the instance." default: ["{{ ssm:myShellCommands }}"] mainSteps: - action: aws:runShellScript name: runShellScriptDefaultParams inputs: runCommand:"{{ commands }}" JSON { "schemaVersion": "2.2", "description": "runShellScript with command strings stored as Parameter Store parameter", "parameters": { "commands": { "type": "StringList", "description": "(Required) The commands to run on the instance.", "default": ["{{ ssm:myShellCommands }}"] } }, "mainSteps": [ { "action": "aws:runShellScript", "name": "runShellScriptDefaultParams", Documents 1666 AWS Systems Manager User Guide "inputs": { "runCommand": [ "{{ commands }}" ] } } ] } Note You can reference String and StringList Parameter Store parameters in the parameters section of your document. You can't reference SecureString Parameter Store parameters. For more information about Parameter Store, see AWS Systems Manager Parameter Store. Type: Structure The parameters structure accepts the following fields and values: • type: (Required) Allowed values include the following: String, StringList, Integer Boolean, MapList, and StringMap. To view examples of each type, see SSM document parameter type examples in the next section. Note Command type documents only support the String and StringList parameter types. • description: (Optional) A description of the parameter. • default: (Optional) The default value of the parameter or a reference to a parameter in Parameter Store. • allowedValues: (Optional) An array of values allowed for the parameter. Defining allowed values for the parameter validates the user input. If a user inputs a value that isn't allowed, the execution fails to start. YAML DirectoryType: Documents 1667 AWS Systems Manager type: String description: "(Required) The directory type to launch." default: AwsMad User Guide allowedValues: - AdConnector - AwsMad - SimpleAd JSON "DirectoryType": { "type": "String", "description": "(Required) The directory type to launch.", "default": "AwsMad", "allowedValues": [ "AdConnector", "AwsMad", "SimpleAd" ] } • allowedPattern: (Optional) A regular expression that validates whether the user input matches the defined pattern for the parameter. If the user input doesn't match the allowed pattern, the execution fails to start. Note Systems Manager performs two validations for allowedPattern. The first validation is performed using the Java regex library at the API level when you use a document. The second validation is performed on SSM Agent by using the GO regexp library before processing the document. YAML InstanceId: type: String description: "(Required)
systems-manager-ug-487
systems-manager-ug.pdf
487
"description": "(Required) The directory type to launch.", "default": "AwsMad", "allowedValues": [ "AdConnector", "AwsMad", "SimpleAd" ] } • allowedPattern: (Optional) A regular expression that validates whether the user input matches the defined pattern for the parameter. If the user input doesn't match the allowed pattern, the execution fails to start. Note Systems Manager performs two validations for allowedPattern. The first validation is performed using the Java regex library at the API level when you use a document. The second validation is performed on SSM Agent by using the GO regexp library before processing the document. YAML InstanceId: type: String description: "(Required) The instance ID to target." allowedPattern: "^i-[a-z0-9]{8,17}$" default: '' Documents 1668 AWS Systems Manager JSON User Guide "InstanceId": { "type": "String", "description": "(Required) The instance ID to target.", "allowedPattern": "^i-[a-z0-9]{8,17}$", "default": "" } • displayType: (Optional) Used to display either a textfield or a textarea in the AWS Management Console. textfield is a single-line text box. textarea is a multi-line text area. • minItems: (Optional) The minimum number of items allowed. • maxItems: (Optional) The maximum number of items allowed. • minChars: (Optional) The minimum number of parameter characters allowed. • maxChars: (Optional) The maximum number of parameter characters allowed. Required: No variables (Schema version 0.3 only) Values you can reference or update throughout the steps in an Automation runbook. Variables are similar to parameters, but differ in a very important way. Parameter values are static in the context of a runbook, but the values of variables can be changed in the context of the runbook. When updating the value of a variable, the data type must match the defined data type. For information about updating variables values in an automation, see aws:updateVariable – Updates a value for a runbook variable Type: Boolean | Integer | MapList | String | StringList | StringMap Required: No YAML variables: payload: type: StringMap default: "{}" Documents 1669 User Guide AWS Systems Manager JSON { "variables": [ "payload": { "type": "StringMap", "default": "{}" } ] } runtimeConfig (Schema version 1.2 only) The configuration for the instance as applied by one or more Systems Manager plugins. Plugins aren't guaranteed to run in sequence. Type: Dictionary<string,PluginConfiguration> Required: No mainSteps (Schema version 0.3, 2.0, and 2.2 only) An object that can include multiple steps (plugins). Plugins are defined within steps. Steps run in sequential order as listed in the document. Type: Dictionary<string,PluginConfiguration> Required: Yes outputs (Schema version 0.3 only) Data generated by the execution of this document that can be used in other processes. For example, if your document creates a new AMI, you might specify "CreateImage.ImageId" as the output value, and then use this output to create new instances in a subsequent automation execution. For more information about outputs, see Using action outputs as inputs. Type: Dictionary<string,OutputConfiguration> Required: No files (Schema version 0.3 only) The script files (and their checksums) attached to the document and run during an automation execution. Applies only to documents that include the Documents 1670 AWS Systems Manager User Guide aws:executeScript action and for which attachments have been specified in one or more steps. To learn about the runtimes supported by Automation runbooks, see aws:executeScript – Run a script. For more information about including scripts in Automation runbooks, see Using scripts in runbooks and Visual design experience for Automation runbooks. When creating an Automation runbook with attachments, you must also specify attachment files using the --attachments option (for AWS CLI) or Attachments (for API and SDK). You can specify the file location for SSM documents and files stored in Amazon Simple Storage Service (Amazon S3) buckets. For more information, see Attachments in the AWS Systems Manager API Reference. YAML --- files: launch.py: checksums: sha256: 18871b1311b295c43d0f... [truncated]...772da97b67e99d84d342ef4aEXAMPLE JSON "files": { "launch.py": { "checksums": { "sha256": "18871b1311b295c43d0f... [truncated]...772da97b67e99d84d342ef4aEXAMPLE" } } } Type: Dictionary<string,FilesConfiguration> Required: No SSM document parameter type examples Parameter types in SSM documents are static. This means the parameter type can't be changed after it's defined. When using parameters with SSM document plugins, the type of a parameter Documents 1671 AWS Systems Manager User Guide can't be dynamically changed within a plugin's input. For example, you can't reference an Integer parameter within the runCommand input of the aws:runShellScript plugin because this input accepts a string or list of strings. To use a parameter for a plugin input, the parameter type must match the accepted type. For example, you must specify a Boolean type parameter for the allowDowngrade input of the aws:updateSsmAgent plugin. If your parameter type doesn't match the input type for a plugin, the SSM document fails to validate and the system doesn't create the document. This is also true when using parameters downstream within inputs for other plugins or AWS Systems Manager Automation actions. For example, you can't reference a StringList parameter within the documentParameters input of the aws:runDocument plugin.