id
stringlengths 8
78
| source
stringclasses 743
values | chunk_id
int64 1
5.05k
| text
stringlengths 593
49.7k
|
---|---|---|---|
systems-manager-ug-288
|
systems-manager-ug.pdf
| 288 |
recorded at the INFO level. Data flow (packets and acknowledgement) entries are recorded at the DEBUG level. 4. Change other configuration options you want to modify. Options you can change include: • Debug level: You can change the debug level from formatid="fmtinfo" to formatid="fmtdebug". • Log file options: You can make changes to the log file options, including where the logs are stored, with the exception of the log file names. Important Don't change the file names or logging won't work correctly. <rollingfile type="size" filename="C:\Program Files\Amazon\SessionManagerPlugin \Logs\session-manager-plugin.log" maxsize="30000000" maxrolls="5"/> <filter levels="error,critical" formatid="fmterror"> <rollingfile type="size" filename="C:\Program Files\Amazon\SessionManagerPlugin \Logs\errors.log" maxsize="10000000" maxrolls="5"/> 5. Save the file. Enable logging for the Session Manager plugin (Linux and macOS) 1. Locate the seelog.xml.template file for the plugin. Session Manager 928 AWS Systems Manager User Guide The default location is /usr/local/sessionmanagerplugin/seelog.xml.template. 2. Change the name of the file to seelog.xml. 3. Open the file and change minlevel="off" to minlevel="info" or minlevel="debug". Note By default, log entries about opening data channels and reconnecting sessions are recorded at the INFO level. Data flow (packets and acknowledgement) entries are recorded at the DEBUG level. 4. Change other configuration options you want to modify. Options you can change include: • Debug level: You can change the debug level from formatid="fmtinfo" to outputs formatid="fmtdebug" • Log file options: You can make changes to the log file options, including where the logs are stored, with the exception of the log file names. Important Don't change the file names or logging won't work correctly. <rollingfile type="size" filename="/usr/local/sessionmanagerplugin/logs/session- manager-plugin.log" maxsize="30000000" maxrolls="5"/> <filter levels="error,critical" formatid="fmterror"> <rollingfile type="size" filename="/usr/local/sessionmanagerplugin/logs/ errors.log" maxsize="10000000" maxrolls="5"/> Important If you use the specified default directory for storing logs, you must either run session commands using sudo or give the directory where the plugin is installed full read and write permissions. To bypass these restrictions, change the location where logs are stored. 5. Save the file. Session Manager 929 AWS Systems Manager Start a session User Guide You can use the AWS Systems Manager console, the Amazon Elastic Compute Cloud (Amazon EC2) console, the AWS Command Line Interface (AWS CLI), or SSH to start a session. Topics • Starting a session (Systems Manager console) • Starting a session (Amazon EC2 console) • Starting a session (AWS CLI) • Starting a session (SSH) • Starting a session (port forwarding) • Starting a session (port forwarding to remote host) • Starting a session (interactive and noninteractive commands) Starting a session (Systems Manager console) You can use the AWS Systems Manager console to start a session with a managed node in your account. Note Before you start a session, make sure that you have completed the setup steps for Session Manager. For information, see Setting up Session Manager. To start a session (Systems Manager console) 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Session Manager. 3. Choose Start session. 4. 5. (Optional) Enter a session description in the Reason for session field. For Target instances, choose the option button to the left of the managed node that you want to connect to. Session Manager 930 AWS Systems Manager User Guide If the node that you want isn't in the list, or if you select a node and receive a configuration error, see Managed node not available or not configured for Session Manager for troubleshooting steps. 6. Choose Start session to launch the session immediately. -or- Choose Next for session options. 7. (Optional) For Session document, select the document that you want to run when the session starts. If your document supports runtime parameters, you can enter one or more comma- separated values in each parameter field. 8. Choose Next. 9. Choose Start session. After the connection is made, you can run bash commands (Linux and macOS) or PowerShell commands (Windows) as you would through any other connection type. Important If you want to allow users to specify a document when starting sessions in the Session Manager console, note the following: • You must grant users the ssm:GetDocument and ssm:ListDocuments permissions in their IAM policy. For more information, see Grant access to custom Session documents in the console. • The console only supports Session documents that have the sessionType defined as Standard_Stream. For more information, see Session document schema. Starting a session (Amazon EC2 console) You can use the Amazon Elastic Compute Cloud (Amazon EC2) console to start a session with an instance in your account. Session Manager 931 AWS Systems Manager Note User Guide If you receive an error that you aren't authorized to perform one or more Systems Manager actions (ssm:command-name, then you must contact your administrator for assistance. Your administrator is the person that provided you with your sign-in credentials. Ask that person to update your policies to allow you to start sessions from the Amazon
|
systems-manager-ug-289
|
systems-manager-ug.pdf
| 289 |
defined as Standard_Stream. For more information, see Session document schema. Starting a session (Amazon EC2 console) You can use the Amazon Elastic Compute Cloud (Amazon EC2) console to start a session with an instance in your account. Session Manager 931 AWS Systems Manager Note User Guide If you receive an error that you aren't authorized to perform one or more Systems Manager actions (ssm:command-name, then you must contact your administrator for assistance. Your administrator is the person that provided you with your sign-in credentials. Ask that person to update your policies to allow you to start sessions from the Amazon EC2 console. If you're an administrator, see Sample IAM policies for Session Manager for more information. To start a session (Amazon EC2 console) 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. 3. 4. In the navigation pane, choose Instances. Select the instance and choose Connect. For Connection method, choose Session Manager. 5. Choose Connect. After the connection is made, you can run bash commands (Linux and macOS) or PowerShell commands (Windows) as you would through any other connection type. Starting a session (AWS CLI) 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. Before you start a session, make sure that you have completed the setup steps for Session Manager. For information, see Setting up Session Manager. To use the AWS CLI to run session commands, the Session Manager plugin must also be installed on your local machine. For information, see Install the Session Manager plugin for the AWS CLI. To start a session using the AWS CLI, run the following command replacing instance-id with your own information. aws ssm start-session \ --target instance-id Session Manager 932 AWS Systems Manager User Guide For information about other options you can use with the start-session command, see start- session in the AWS Systems Manager section of the AWS CLI Command Reference. Starting a session (SSH) To start a Session Manager SSH session, version 2.3.672.0 or later of SSM Agent must be installed on the managed node. SSH connection requirements Take note of the following requirements and limitations for session connections using SSH: • Your target managed node must be configured to support SSH connections. For more information, see (Optional) Allow and control permissions for SSH connections through Session Manager. • You must connect using the managed node account associated with the Privacy Enhanced Mail (PEM) certificate, not the ssm-user account that is used for other types of session connections. For example, on EC2 instances for Linux and macOS, the default user is ec2-user. For information about identifying the default user for each instance type, see Get Information About Your Instance in the Amazon EC2 User Guide. • Logging isn't available for Session Manager sessions that connect through port forwarding or SSH. This is because SSH encrypts all session data, and Session Manager only serves as a tunnel for SSH connections. Note Before you start a session, make sure that you have completed the setup steps for Session Manager. For information, see Setting up Session Manager. To start a session using SSH, run the following command. Replace each example resource placeholder with your own information. ssh -i /path/my-key-pair.pem username@instance-id Session Manager 933 AWS Systems Manager Tip User Guide When you start a session using SSH, you can copy local files to the target managed node using the following command format. scp -i /path/my-key-pair.pem /path/ExampleFile.txt username@instance-id:~ For information about other options you can use with the start-session command, see start- session in the AWS Systems Manager section of the AWS CLI Command Reference. Starting a session (port forwarding) To start a Session Manager port forwarding session, version 2.3.672.0 or later of SSM Agent must be installed on the managed node. Note Before you start a session, make sure that you have completed the setup steps for Session Manager. For information, see Setting up Session Manager. To use the AWS CLI to run session commands, you must install the Session Manager plugin on your local machine. For information, see Install the Session Manager plugin for the AWS CLI. Depending on your operating system and command line tool, the placement of quotation marks can differ and escape characters might be required. To start a port forwarding session, run the following command from the CLI. Replace each example resource placeholder with your own information. Linux & macOS aws ssm start-session \ --target instance-id \ --document-name AWS-StartPortForwardingSession \ --parameters '{"portNumber":["80"], "localPortNumber":["56789"]}' Session Manager 934 AWS Systems Manager Windows User Guide aws ssm start-session ^ --target instance-id ^ --document-name AWS-StartPortForwardingSession ^ --parameters portNumber="3389",localPortNumber="56789" portNumber is the remote port on the managed node where you want the session traffic to be redirected. For example, you might specify port 3389 for connecting
|
systems-manager-ug-290
|
systems-manager-ug.pdf
| 290 |
tool, the placement of quotation marks can differ and escape characters might be required. To start a port forwarding session, run the following command from the CLI. Replace each example resource placeholder with your own information. Linux & macOS aws ssm start-session \ --target instance-id \ --document-name AWS-StartPortForwardingSession \ --parameters '{"portNumber":["80"], "localPortNumber":["56789"]}' Session Manager 934 AWS Systems Manager Windows User Guide aws ssm start-session ^ --target instance-id ^ --document-name AWS-StartPortForwardingSession ^ --parameters portNumber="3389",localPortNumber="56789" portNumber is the remote port on the managed node where you want the session traffic to be redirected. For example, you might specify port 3389 for connecting to a Windows node using the Remote Desktop Protocol (RDP). If you don't specify the portNumber parameter, Session Manager uses 80 as the default value. localPortNumber is the port on your local computer where traffic starts, such as 56789. This value is what you enter when connecting to a managed node using a client. For example, localhost:56789. For information about other options you can use with the start-session command, see start- session in the AWS Systems Manager section of the AWS CLI Command Reference. For more information about port forwarding sessions, see Port Forwarding Using AWS Systems Manager Session Manager in the AWS News Blog. Starting a session (port forwarding to remote host) To start a Session Manager port forwarding session to a remote host, version 3.1.1374.0 or later of SSM Agent must be installed on the managed node. The remote host isn't required to be managed by Systems Manager. Note Before you start a session, make sure that you have completed the setup steps for Session Manager. For information, see Setting up Session Manager. To use the AWS CLI to run session commands, you must install the Session Manager plugin on your local machine. For information, see Install the Session Manager plugin for the AWS CLI. Depending on your operating system and command line tool, the placement of quotation marks can differ and escape characters might be required. Session Manager 935 AWS Systems Manager User Guide To start a port forwarding session, run the following command from the AWS CLI. Replace each example resource placeholder with your own information. Linux & macOS aws ssm start-session \ --target instance-id \ --document-name AWS-StartPortForwardingSessionToRemoteHost \ --parameters '{"host":["mydb.example.us-east-2.rds.amazonaws.com"],"portNumber": ["3306"], "localPortNumber":["3306"]}' Windows aws ssm start-session ^ --target instance-id ^ --document-name AWS-StartPortForwardingSessionToRemoteHost ^ --parameters host="mydb.example.us- east-2.rds.amazonaws.com",portNumber="3306",localPortNumber="3306" The host value represents the hostname or IP address of the remote host that you want to connect to. General connectivity and name resolution requirements between the managed node and the remote host still apply. portNumber is the remote port on the managed node where you want the session traffic to be redirected. For example, you might specify port 3389 for connecting to a Windows node using the Remote Desktop Protocol (RDP). If you don't specify the portNumber parameter, Session Manager uses 80 as the default value. localPortNumber is the port on your local computer where traffic starts, such as 56789. This value is what you enter when connecting to a managed node using a client. For example, localhost:56789. For information about other options you can use with the start-session command, see start- session in the AWS Systems Manager section of the AWS CLI Command Reference. Starting a session with an Amazon ECS task Session Manager supports starting a port forwarding session with a task inside an Amazon Elastic Container Service (Amazon ECS) cluster. To do so, you must update the task role in IAM to include the following permissions: Session Manager 936 AWS Systems Manager User Guide { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ssmmessages:CreateControlChannel", "ssmmessages:CreateDataChannel", "ssmmessages:OpenControlChannel", "ssmmessages:OpenDataChannel" ], "Resource": "*" } ] } To start a port forwarding session with an Amazon ECS task, run the following command from the AWS CLI. Replace each example resource placeholder with your own information. Note Remove the < and > symbols from the target parameter. These symbols are provided for reader clarification only. Linux & macOS aws ssm start-session \ --target ecs:<ECS_cluster_name>_<ECS_container_ID>_<container_runtime_ID> \ --document-name AWS-StartPortForwardingSessionToRemoteHost \ --parameters '{"host":["URL"],"portNumber":["port_number"], "localPortNumber": ["port_number"]}' Windows aws ssm start-session ^ --target ecs:<ECS_cluster_name>_<ECS_container_ID>_<container_runtime_ID> ^ --document-name AWS-StartPortForwardingSessionToRemoteHost ^ --parameters host="URL",portNumber="port_number",localPortNumber="port_number" Session Manager 937 AWS Systems Manager User Guide Starting a session (interactive and noninteractive commands) Before you start a session, make sure that you have completed the setup steps for Session Manager. For information, see Setting up Session Manager. To use the AWS CLI to run session commands, the Session Manager plugin must also be installed on your local machine. For information, see Install the Session Manager plugin for the AWS CLI. To start an interactive command session, run the following command. Replace each example resource placeholder with your own information. Linux & macOS aws ssm start-session \ --target instance-id \ --document-name CustomCommandSessionDocument \ --parameters '{"logpath":["/var/log/amazon/ssm/amazon-ssm-agent.log"]}' Windows aws ssm start-session ^ --target instance-id ^
|
systems-manager-ug-291
|
systems-manager-ug.pdf
| 291 |
commands) Before you start a session, make sure that you have completed the setup steps for Session Manager. For information, see Setting up Session Manager. To use the AWS CLI to run session commands, the Session Manager plugin must also be installed on your local machine. For information, see Install the Session Manager plugin for the AWS CLI. To start an interactive command session, run the following command. Replace each example resource placeholder with your own information. Linux & macOS aws ssm start-session \ --target instance-id \ --document-name CustomCommandSessionDocument \ --parameters '{"logpath":["/var/log/amazon/ssm/amazon-ssm-agent.log"]}' Windows aws ssm start-session ^ --target instance-id ^ --document-name CustomCommandSessionDocument ^ --parameters logpath="/var/log/amazon/ssm/amazon-ssm-agent.log" For information about other options you can use with the start-session command, see start- session in the AWS Systems Manager section of the AWS CLI Command Reference. More info • Use port forwarding in AWS Systems Manager Session Manager to connect to remote hosts • Amazon EC2 instance port forwarding with AWS Systems Manager • Manage AWS Managed Microsoft AD resources with Session Manager port forwarding • Port Forwarding Using AWS Systems Manager Session Manager on the AWS News Blog. End a session You can end a session that you started in your account using the AWS Systems Manager console or the AWS Command Line Interface (AWS CLI). When you choose the Terminate button for a session in the console or call the TerminateSession API action by using the AWS CLI, Session Manager Session Manager 938 AWS Systems Manager User Guide permanently ends the session and closes the data connection between the Session Manager client and SSM Agent on the managed node. You can't resume a terminated session. If there is no user activity in an open session for 20 minutes, the idle state triggers a timeout. Session Manager doesn't call TerminateSession, but it does close the underlying channel. You can't resume a session closed because of idle timeout. We recommend always explicitly terminating a session by using the terminate-session command, when using the AWS CLI, or the Terminate button when using the console. (Terminate buttons are located on both the session window and main Session Manager console page.) If you only close a browser or command window, the session remains listed as Active in the console for 30 days. When you don't explicitly terminate a session, or when a session times out, any processes that were running on the managed node at the time will continue to run. Topics • Ending a session (console) • Ending a session (AWS CLI) Ending a session (console) You can use the AWS Systems Manager console to end a session in your account. To end a session (console) 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. In the navigation pane, choose Session Manager. For Sessions, choose the option button to the left of the session you want to end. 2. 3. 4. Choose Terminate. Ending a session (AWS CLI) To end a session using the AWS CLI, run the following command. Replace session-id with your own information. aws ssm terminate-session \ --session-id session-id Session Manager 939 AWS Systems Manager User Guide For more information about the terminate-session command, see terminate-session in the AWS Systems Manager section of the AWS CLI Command Reference. View session history You can use the AWS Systems Manager console or the AWS Command Line Interface (AWS CLI) to view information about sessions in your account. In the console, you can view session details such as the following: • The ID of the session • Which user connected to a managed node through a session • The ID of the managed node • When the session began and ended • The status of the session • The location specified for storing session logs (if turned on) Using the AWS CLI, you can view a list of sessions in your account, but not the additional details that are available in the console. For information about logging session history information, see Enabling and disabling session logging. Topics • Viewing session history (console) • Viewing session history (AWS CLI) Viewing session history (console) You can use the AWS Systems Manager console to view details about the sessions in your account. To view session history (console) 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Session Manager. 3. Choose the Session history tab. -or- Session Manager 940 AWS Systems Manager User Guide If the Session Manager home page opens first, choose Configure Preferences and then choose the Session history tab. Viewing session history (AWS CLI) To view a list of sessions in your account using the AWS CLI, run the following command. aws ssm describe-sessions \ --state History Note This command returns only results for connections to targets initiated using Session Manager. It doesn't list connections made through other means,
|
systems-manager-ug-292
|
systems-manager-ug.pdf
| 292 |
Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Session Manager. 3. Choose the Session history tab. -or- Session Manager 940 AWS Systems Manager User Guide If the Session Manager home page opens first, choose Configure Preferences and then choose the Session history tab. Viewing session history (AWS CLI) To view a list of sessions in your account using the AWS CLI, run the following command. aws ssm describe-sessions \ --state History Note This command returns only results for connections to targets initiated using Session Manager. It doesn't list connections made through other means, such as Remote Desktop Protocol (RDP) or the Secure Shell Protocol (SSH). For information about other options you can use with the describe-sessions command, see describe-sessions in the AWS Systems Manager section of the AWS CLI Command Reference. Logging session activity In addition to providing information about current and completed sessions in the Systems Manager console, Session Manager provides you with the ability to log session activity in your AWS account using AWS CloudTrail. CloudTrail captures session API calls through the Systems Manager console, the AWS Command Line Interface (AWS CLI), and the Systems Manager SDK. You can view the information on the CloudTrail console or store it in a specified Amazon Simple Storage Service (Amazon S3) bucket. One Amazon S3 bucket is used for all CloudTrail logs for your account. For more information, see Logging AWS Systems Manager API calls with AWS CloudTrail. Note For recurring, historical, analytical analysis of your log files, consider querying CloudTrail logs using CloudTrail Lake or a table you maintain. For more information, see Querying AWS CloudTrail logs in the AWS CloudTrail User Guide. Session Manager 941 AWS Systems Manager User Guide Monitoring session activity using Amazon EventBridge (console) With EventBridge, you can set up rules to detect when changes happen to AWS resources. You can create a rule to detect when a user in your organization starts or ends a session, and then, for example, receive a notification through Amazon SNS about the event. EventBridge support for Session Manager relies on records of API operations that were recorded by CloudTrail. (You can use CloudTrail integration with EventBridge to respond to most AWS Systems Manager events.) Actions that take place within a session, such as an exit command, that don't make an API call aren't detected by EventBridge. The following steps outline how to initiate notifications through Amazon Simple Notification Service (Amazon SNS) when a Session Manager API event occurs, such as StartSession. To monitor session activity using Amazon EventBridge (console) 1. Create an Amazon SNS topic to use for sending notifications when the Session Manager event occurs that you want to track. For more information, see Create a Topic in the Amazon Simple Notification Service Developer Guide. 2. Create an EventBridge rule to invoke the Amazon SNS target for the type of Session Manager event you want to track. For information about how to create the rule, see Creating Amazon EventBridge rules that react to events in the Amazon EventBridge User Guide. As you follow the steps to create the rule, make the following selections: • For AWS service, choose Systems Manager. • For Event type, choose AWS API Call through CloudTrail. • Choose Specific operation(s), and then enter the Session Manager command or commands (one at a time) you want to receive notifications for. You can choose StartSession, ResumeSession, and TerminateSession. (EventBridge doesn't support Get*, List*, and Describe* commands.) • For Select a target, choose SNS topic. For Topic, choose the name of the Amazon SNS topic you created in Step 1. Session Manager 942 AWS Systems Manager User Guide For more information, see the Amazon EventBridge User Guide and the Amazon Simple Notification Service Getting Started Guide. Enabling and disabling session logging Session logging records information about current and completed sessions in the Systems Manager console. You can also log details about commands run during sessions in your AWS account. Session logging enables you to do the following: • Create and store session logs for archival purposes. • Generate a report showing details of every connection made to your managed nodes using Session Manager over the past 30 days. • Generate notifications for session logging in your AWS account, such as Amazon Simple Notification Service (Amazon SNS) notifications. • Automatically initiate another action on an AWS resource as the result of actions performed during a session, such as running an AWS Lambda function, starting an AWS CodePipeline pipeline, or running an AWS Systems Manager Run Command document. Important Note the following requirements and limitations for Session Manager: • Session Manager logs the commands you enter and their output during a session depending on your session preferences. To prevent sensitive data, such as passwords, from being viewed in your session logs we
|
systems-manager-ug-293
|
systems-manager-ug.pdf
| 293 |
notifications for session logging in your AWS account, such as Amazon Simple Notification Service (Amazon SNS) notifications. • Automatically initiate another action on an AWS resource as the result of actions performed during a session, such as running an AWS Lambda function, starting an AWS CodePipeline pipeline, or running an AWS Systems Manager Run Command document. Important Note the following requirements and limitations for Session Manager: • Session Manager logs the commands you enter and their output during a session depending on your session preferences. To prevent sensitive data, such as passwords, from being viewed in your session logs we recommend using the following commands when entering sensitive data during a session. Linux & macOS stty -echo; read passwd; stty echo; Windows $Passwd = Read-Host -AsSecureString • If you're using Windows Server 2012 or earlier, the data in your logs might not be formatted optimally. We recommend using Windows Server 2012 R2 and later for optimal log formats. Session Manager 943 AWS Systems Manager User Guide • If you're using Linux or macOS managed nodes, ensure that the screen utility is installed. If it isn't, your log data might be truncated. On Amazon Linux 1, Amazon Linux 2, AL2023 and Ubuntu Server, the screen utility is installed by default. To install screen manually, depending on your version of Linux, run either sudo yum install screen or sudo apt-get install screen. • Logging isn't available for Session Manager sessions that connect through port forwarding or SSH. This is because SSH encrypts all session data, and Session Manager only serves as a tunnel for SSH connections. For more information about the permissions required to use Amazon S3 or Amazon CloudWatch Logs for logging session data, see Creating an IAM role with permissions for Session Manager and Amazon S3 and CloudWatch Logs (console). Refer to the following topics for more information about logging options for Session Manager. Topics • Streaming session data using Amazon CloudWatch Logs (console) • Logging session data using Amazon S3 (console) • Logging session data using Amazon CloudWatch Logs (console) • Configuring session logging to disk • Adjusting how long the Session Manager temporary log file is stored on disk • Disabling Session Manager logging in CloudWatch Logs and Amazon S3 Streaming session data using Amazon CloudWatch Logs (console) You can send a continual stream of session data logs to Amazon CloudWatch Logs. Essential details, such as the commands a user has run in a session, the ID of the user who ran the commands, and timestamps for when the session data is streamed to CloudWatch Logs, are included when streaming session data. When streaming session data, the logs are JSON-formatted to help you integrate with your existing logging solutions. Streaming session data isn't supported for interactive commands. Session Manager 944 AWS Systems Manager Note User Guide To stream session data from Windows Server managed nodes, you must have PowerShell 5.1 or later installed. By default, Windows Server 2016 and later have the required PowerShell version installed. However, Windows Server 2012 and 2012 R2 don't have the required PowerShell version installed by default. If you haven't already updated PowerShell on your Windows Server 2012 or 2012 R2 managed nodes, you can do so using Run Command. For information about updating PowerShell using Run Command, see Updating PowerShell using Run Command. Important If you have the PowerShell Transcription policy setting configured on your Windows Server managed nodes, you won't be able to stream session data. To stream session data using Amazon CloudWatch Logs (console) 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Session Manager. 3. Choose the Preferences tab, and then choose Edit. 4. Select the check box next to Enable under CloudWatch logging. 5. Choose the Stream session logs option. 6. (Recommended) Select the check box next to Allow only encrypted CloudWatch log groups. With this option turned on, log data is encrypted using the server-side encryption key specified for the log group. If you don't want to encrypt the log data that is sent to CloudWatch Logs, clear the check box. You must also clear the check box if encryption isn't allowed on the log group. 7. For CloudWatch logs, to specify the existing CloudWatch Logs log group in your AWS account to upload session logs to, select one of the following: • Enter the name of a log group in the text box that has already been created in your account to store session log data. Session Manager 945 AWS Systems Manager User Guide • Browse log groups: Select a log group that has already been created in your account to store session log data. 8. Choose Save. Logging session data using Amazon S3 (console) You can choose to store session log data in a specified Amazon Simple Storage
|
systems-manager-ug-294
|
systems-manager-ug.pdf
| 294 |
to specify the existing CloudWatch Logs log group in your AWS account to upload session logs to, select one of the following: • Enter the name of a log group in the text box that has already been created in your account to store session log data. Session Manager 945 AWS Systems Manager User Guide • Browse log groups: Select a log group that has already been created in your account to store session log data. 8. Choose Save. Logging session data using Amazon S3 (console) You can choose to store session log data in a specified Amazon Simple Storage Service (Amazon S3) bucket for debugging and troubleshooting purposes. The default option is for logs to be sent to an encrypted Amazon S3 bucket. Encryption is performed using the key specified for the bucket, either an AWS KMS key or an Amazon S3 Server-Side Encryption (SSE) key (AES-256). Important When you use virtual hosted–style buckets with Secure Sockets Layer (SSL), the SSL wildcard certificate only matches buckets that don't contain periods. To work around this, use HTTP or write your own certificate verification logic. We recommend that you don't use periods (".") in bucket names when using virtual hosted–style buckets. Amazon S3 bucket encryption In order to send logs to your Amazon S3 bucket with encryption, encryption must be allowed on the bucket. For more information about Amazon S3 bucket encryption, see Amazon S3 Default Encryption for S3 Buckets. Customer managed key If you're using a KMS key that you manage yourself to encrypt your bucket, then the IAM instance profile attached to your instances must have explicit permissions to read the key. If you use an AWS managed key, the instance doesn't require this explicit permission. For more information about providing the instance profile with access to use the key, see Allows Key Users to Use the key in the AWS Key Management Service Developer Guide. Follow these steps to configure Session Manager to store session logs in an Amazon S3 bucket. Session Manager 946 AWS Systems Manager Note User Guide You can also use the AWS CLI to specify or change the Amazon S3 bucket that session data is sent to. For information, see Update Session Manager preferences (command line). To log session data using Amazon S3 (console) 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Session Manager. 3. Choose the Preferences tab, and then choose Edit. 4. 5. Select the check box next to Enable under S3 logging. (Recommended) Select the check box next to Allow only encrypted S3 buckets. With this option turned on, log data is encrypted using the server-side encryption key specified for the bucket. If you don't want to encrypt the log data that is sent to Amazon S3, clear the check box. You must also clear the check box if encryption isn't allowed on the S3 bucket. 6. For S3 bucket name, select one of the following: Note We recommend that you don't use periods (".") in bucket names when using virtual hosted–style buckets. For more information about Amazon S3 bucket-naming conventions, see Bucket Restrictions and Limitations in the Amazon Simple Storage Service User Guide. • Choose a bucket name from the list: Select an Amazon S3 bucket that has already been created in your account to store session log data. • Enter a bucket name in the text box: Enter the name of an Amazon S3 bucket that has already been created in your account to store session log data. 7. (Optional) For S3 key prefix, enter the name of an existing or new folder to store logs in the selected bucket. 8. Choose Save. Session Manager 947 AWS Systems Manager User Guide For more information about working with Amazon S3 and Amazon S3 buckets, see the Amazon Simple Storage Service User Guide and the Amazon Simple Storage Service User Guide. Logging session data using Amazon CloudWatch Logs (console) With Amazon CloudWatch Logs, you can monitor, store, and access log files from various AWS services. You can send session log data to a CloudWatch Logs log group for debugging and troubleshooting purposes. The default option is for log data to be sent with encryption using your KMS key, but you can send the data to your log group with or without encryption. Follow these steps to configure AWS Systems Manager Session Manager to send session log data to a CloudWatch Logs log group at the end of your sessions. Note You can also use the AWS CLI to specify or change the CloudWatch Logs log group that session data is sent to. For information, see Update Session Manager preferences (command line). To log session data using Amazon CloudWatch Logs (console) 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the
|
systems-manager-ug-295
|
systems-manager-ug.pdf
| 295 |
encryption using your KMS key, but you can send the data to your log group with or without encryption. Follow these steps to configure AWS Systems Manager Session Manager to send session log data to a CloudWatch Logs log group at the end of your sessions. Note You can also use the AWS CLI to specify or change the CloudWatch Logs log group that session data is sent to. For information, see Update Session Manager preferences (command line). To log session data using Amazon CloudWatch Logs (console) 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Session Manager. 3. Choose the Preferences tab, and then choose Edit. 4. Select the check box next to Enable under CloudWatch logging. 5. Choose the Upload session logs option. 6. (Recommended) Select the check box next to Allow only encrypted CloudWatch log groups. With this option turned on, log data is encrypted using the server-side encryption key specified for the log group. If you don't want to encrypt the log data that is sent to CloudWatch Logs, clear the check box. You must also clear the check box if encryption isn't allowed on the log group. 7. For CloudWatch logs, to specify the existing CloudWatch Logs log group in your AWS account to upload session logs to, select one of the following: • Choose a log group from the list: Select a log group that has already been created in your account to store session log data. Session Manager 948 AWS Systems Manager User Guide • Enter a log group name in the text box: Enter the name of a log group that has already been created in your account to store session log data. 8. Choose Save. For more information about working with CloudWatch Logs, see the Amazon CloudWatch Logs User Guide. Configuring session logging to disk After you enable Session Manager logging to CloudWatch or Amazon S3, all commands executed during a session (and the resulting output from those commands) are logged to a temporary file on the disk of the target instance. The temporary file is named ipcTempFile.log. The ipcTempFile.log is controlled by the SessionLogsDestination parameter in the SSM Agent configuration file. This parameter accepts the following values: • disk: If you specify this parameter and session logging to CloudWatch or Amazon S3 are enabled, SSM Agent creates the ipcTempFile.log temporary log file and logs session commands and output to disk. Session Manager uploads this log to either CloudWatch or S3 during or after the session, depending on the logging configuration. The log is then deleted according to the duration specified for the SSM Agent SessionLogsRetentionDurationHours configuration parameter. If you specify this parameter and session logging to CloudWatch and Amazon S3 are disabled, SSM Agent still logs command history and output in the ipcTempFile.log file. The file will be deleted according to the duration specified for the SSM Agent SessionLogsRetentionDurationHours configuration parameter. • none: If you specify this parameter and session logging to CloudWatch or Amazon S3 are enabled, logging to disk works exactly as it does as if you'd specified the disk parameter. SSM Agent requires the temporary file when session logging to CloudWatch or Amazon S3 are enabled. If you specify this parameter and session logging to CloudWatch or Amazon S3 are disabled, SSM Agent doesn't create the ipcTempFile.log file. Use the following procedure to enable or disable creating the ipcTempFile.log temporary log file to disk when a session is stared. Session Manager 949 AWS Systems Manager User Guide To enable or disable creating the Session Manager temporary log file to disk 1. Either install SSM Agent on your instance or upgrade to version 3.2.2086 or higher. For information about how to check the agent version number, see Checking the SSM Agent version number. For information about how to manually install the agent, locate the procedure for your operating system in the following sections: • Manually installing and uninstalling SSM Agent on EC2 instances for Linux • Manually installing and uninstalling SSM Agent on EC2 instances for macOS • Manually installing and uninstalling SSM Agent on EC2 instances for Windows Server 2. Connect to your instance and locate the amazon-ssm-agent.json file in the following location. • Linux: /etc/amazon/ssm/ • macOS: /opt/aws/ssm/ • Windows Server: C:\Program Files\Amazon\SSM If the file amazon-ssm-agent.json doesn't exist, copy the contents of the amazon-ssm- agent.json.template to a new file in the same directory. Name the new file amazon-ssm- agent.json. 3. Specify either none or disk for the SessionLogsDestination parameter. Save your changes. 4. Restart SSM Agent. If you specified disk for the SessionLogsDestination parameter, you can verify that SSM Agent creates the temporary log file by starting a new session and then locating the ipcTempFile.log in the following location: • Linux: /var/lib/amazon/ssm/target ID/session/orchestration/session ID/ Standard_Stream/ipcTempFile.log • macOS: /opt/aws/ssm/data/target
|
systems-manager-ug-296
|
systems-manager-ug.pdf
| 296 |
the following location. • Linux: /etc/amazon/ssm/ • macOS: /opt/aws/ssm/ • Windows Server: C:\Program Files\Amazon\SSM If the file amazon-ssm-agent.json doesn't exist, copy the contents of the amazon-ssm- agent.json.template to a new file in the same directory. Name the new file amazon-ssm- agent.json. 3. Specify either none or disk for the SessionLogsDestination parameter. Save your changes. 4. Restart SSM Agent. If you specified disk for the SessionLogsDestination parameter, you can verify that SSM Agent creates the temporary log file by starting a new session and then locating the ipcTempFile.log in the following location: • Linux: /var/lib/amazon/ssm/target ID/session/orchestration/session ID/ Standard_Stream/ipcTempFile.log • macOS: /opt/aws/ssm/data/target ID/session/orchestration/session ID/ Standard_Stream/ipcTempFile.log • Windows Server: C:\ProgramData\Amazon\SSM\InstanceData\target ID\session \orchestration\session ID\Standard_Stream\ipcTempFile.log Session Manager 950 AWS Systems Manager Note By default, the temporary log file is saved on the instance for 14 days. User Guide If you want to update the SessionLogsDestination parameter across multiple instances, we recommend you create an SSM Document that specifies the new configuration. You can then use Systems Manager Run Command to implement the change on your instances. For more information, see Writing your own AWS Systems Manager documents (blog) and Running commands on managed nodes. Adjusting how long the Session Manager temporary log file is stored on disk After you enable Session Manager logging to CloudWatch or Amazon S3, all commands executed during a session (and the resulting output from those commands) are logged to a temporary file on the disk of the target instance. The temporary file is named ipcTempFile.log. During a session, or after it is completed, Session Manager uploads this temporary log to either CloudWatch or S3. The temporary log is then deleted according to the duration specified for the SSM Agent SessionLogsRetentionDurationHours configuration parameter. By default, the temporary log file is saved on the instance for 14 days in the following location: • Linux: /var/lib/amazon/ssm/target ID/session/orchestration/session ID/ Standard_Stream/ipcTempFile.log • macOS: /opt/aws/ssm/data/target ID/session/orchestration/session ID/ Standard_Stream/ipcTempFile.log • Windows Server: C:\ProgramData\Amazon\SSM\InstanceData\target ID\session \orchestration\session ID\Standard_Stream\ipcTempFile.log Use the following procedure to adjust how long the Session Manager temporary log file is stored on disk. To adjust how long the ipcTempFile.log file is stored on disk 1. Connect to your instance and locate the amazon-ssm-agent.json file in the following location. • Linux: /etc/amazon/ssm/ • macOS: /opt/aws/ssm/ Session Manager 951 AWS Systems Manager User Guide • Windows Server: C:\Program Files\Amazon\SSM If the file amazon-ssm-agent.json doesn't exist, copy the contents of the amazon-ssm- agent.json.template to a new file in the same directory. Name the new file amazon-ssm- agent.json. 2. Change the value of SessionLogsRetentionDurationHours to the desired number of hours. If SessionLogsRetentionDurationHours is set to 0, the temporary log file is created during the session and deleted when the session is completed. This setting should ensure the log file doesn't persist after the session ends. 3. Save your changes. 4. Restart SSM Agent. Disabling Session Manager logging in CloudWatch Logs and Amazon S3 You can use the Systems Manager console or AWS CLI to disable session logging in your account. To disable session logging (console) 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Session Manager. 3. Choose the Preferences tab, and then choose Edit. 4. To disable CloudWatch logging, in the CloudWatch logging section, clear the Enable checkbox. 5. To disable S3 logging, in the S3 logging section, clear the Enable checkbox. 6. Choose Save. To disable session logging (AWS CLI) To disable session logging using the AWS CLI, follow the instructions in Update Session Manager preferences (command line). In your JSON file, ensure that the s3BucketName and cloudWatchLogGroupName inputs contain no values. For example: "inputs": { Session Manager 952 AWS Systems Manager User Guide "s3BucketName": "", ... "cloudWatchLogGroupName": "", ... } Alternatively, to disable logging, you can remove all S3* and cloudWatch* inputs from your JSON file. Note Depending on your configuration, after you disable CloudWatch or S3, a temporary log file might still be generated to disk by SSM Agent. For information about how to disable logging to disk, see Configuring session logging to disk. Session document schema The following information describes the schema elements of a Session document. AWS Systems Manager Session Manager uses Session documents to determine which type of session to start, such as a standard session, a port forwarding session, or a session to run an interactive command. schemaVersion The schema version of the Session document. Session documents only support version 1.0. Type: String Required: Yes description A description you specify for the Session document. For example, "Document to start port forwarding session with Session Manager". Type: String Required: No sessionType The type of session the Session document is used to establish. Session Manager 953 AWS Systems Manager Type: String Required: Yes User Guide Valid values: InteractiveCommands | NonInteractiveCommands | Port | Standard_Stream inputs The session preferences to use for sessions established using this Session document.
|
systems-manager-ug-297
|
systems-manager-ug.pdf
| 297 |
a port forwarding session, or a session to run an interactive command. schemaVersion The schema version of the Session document. Session documents only support version 1.0. Type: String Required: Yes description A description you specify for the Session document. For example, "Document to start port forwarding session with Session Manager". Type: String Required: No sessionType The type of session the Session document is used to establish. Session Manager 953 AWS Systems Manager Type: String Required: Yes User Guide Valid values: InteractiveCommands | NonInteractiveCommands | Port | Standard_Stream inputs The session preferences to use for sessions established using this Session document. This element is required for Session documents that are used to create Standard_Stream sessions. Type: StringMap Required: No s3BucketName The Amazon Simple Storage Service (Amazon S3) bucket you want to send session logs to at the end of your sessions. Type: String Required: No s3KeyPrefix The prefix to use when sending logs to the Amazon S3 bucket you specified in the s3BucketName input. For more information about using a shared prefix with objects stored in Amazon S3, see How do I use folders in an S3 bucket? in the Amazon Simple Storage Service User Guide. Type: String Required: No s3EncryptionEnabled If set to true, the Amazon S3 bucket you specified in the s3BucketName input must be encrypted. Type: Boolean Required: Yes Session Manager 954 AWS Systems Manager cloudWatchLogGroupName User Guide The name of the Amazon CloudWatch Logs (CloudWatch Logs) group you want to send session logs to at the end of your sessions. Type: String Required: No cloudWatchEncryptionEnabled If set to true, the log group you specified in the cloudWatchLogGroupName input must be encrypted. Type: Boolean Required: Yes cloudWatchStreamingEnabled If set to true, a continual stream of session data logs are sent to the log group you specified in the cloudWatchLogGroupName input. If set to false, session logs are sent to the log group you specified in the cloudWatchLogGroupName input at the end of your sessions. Type: Boolean Required: Yes kmsKeyId The ID of the AWS KMS key you want to use to further encrypt data between your local client machines and the Amazon Elastic Compute Cloud (Amazon EC2) managed nodes you connect to. Type: String Required: No runAsEnabled If set to true, you must specify a user account that exists on the managed nodes you will be connecting to in the runAsDefaultUser input. Otherwise, sessions will fail to start. By default, sessions are started using the ssm-user account created by the AWS Systems Manager SSM Agent. The Run As feature is only supported for connecting to Linux and macOS managed nodes. Session Manager 955 AWS Systems Manager Type: Boolean Required: Yes runAsDefaultUser User Guide The name of the user account to start sessions with on Linux and macOS managed nodes when the runAsEnabled input is set to true. The user account you specify for this input must exist on the managed nodes you will be connecting to; otherwise, sessions will fail to start. Type: String Required: No idleSessionTimeout The amount of time of inactivity you want to allow before a session ends. This input is measured in minutes. Type: String Valid values: 1-60 Required: No maxSessionDuration The maximum amount of time you want to allow before a session ends. This input is measured in minutes. Type: String Valid values: 1-1440 Required: No shellProfile The preferences you specify per operating system to apply within sessions such as shell preferences, environment variables, working directories, and running multiple commands when a session is started. Type: StringMap Session Manager 956 AWS Systems Manager Required: No windows User Guide The shell preferences, environment variables, working directories, and commands you specify for sessions on Windows Server managed nodes. Type: String Required: No linux The shell preferences, environment variables, working directories, and commands you specify for sessions on Linux and macOS managed nodes. Type: String Required: No parameters An object that defines the parameters the document accepts. For more information about defining document parameters, see parameters in the Top-level data elements. For parameters that you reference often, we recommend that you store those parameters in Systems Manager Parameter Store and then reference them. You can reference String and StringList Parameter Store parameters in this section of a document. You can't reference SecureString Parameter Store parameters in this section of a document. You can reference a Parameter Store parameter using the following format. {{ssm:parameter-name}} For more information about Parameter Store, see AWS Systems Manager Parameter Store. Type: StringMap Required: No properties An object whose values you specify that are used in the StartSession API operation. For Session documents that are used for InteractiveCommands sessions, the properties object includes the commands to run on the operating systems you specify. You can also Session Manager 957 AWS Systems Manager User Guide determine whether commands are run as root using
|
systems-manager-ug-298
|
systems-manager-ug.pdf
| 298 |
a document. You can't reference SecureString Parameter Store parameters in this section of a document. You can reference a Parameter Store parameter using the following format. {{ssm:parameter-name}} For more information about Parameter Store, see AWS Systems Manager Parameter Store. Type: StringMap Required: No properties An object whose values you specify that are used in the StartSession API operation. For Session documents that are used for InteractiveCommands sessions, the properties object includes the commands to run on the operating systems you specify. You can also Session Manager 957 AWS Systems Manager User Guide determine whether commands are run as root using the runAsElevated boolean property. For more information, see Restrict access to commands in a session. For Session documents that are used for Port sessions, the properties object contains the port number where traffic should be redirected to. For an example, see the Port type Session document example later in this topic. Type: StringMap Required: No Standard_Stream type Session document example YAML --- schemaVersion: '1.0' description: Document to hold regional settings for Session Manager sessionType: Standard_Stream inputs: s3BucketName: '' s3KeyPrefix: '' s3EncryptionEnabled: true cloudWatchLogGroupName: '' cloudWatchEncryptionEnabled: true cloudWatchStreamingEnabled: true kmsKeyId: '' runAsEnabled: true runAsDefaultUser: '' idleSessionTimeout: '20' maxSessionDuration: '60' shellProfile: windows: '' linux: '' JSON { "schemaVersion": "1.0", "description": "Document to hold regional settings for Session Manager", "sessionType": "Standard_Stream", "inputs": { Session Manager 958 AWS Systems Manager User Guide "s3BucketName": "", "s3KeyPrefix": "", "s3EncryptionEnabled": true, "cloudWatchLogGroupName": "", "cloudWatchEncryptionEnabled": true, "cloudWatchStreamingEnabled": true, "kmsKeyId": "", "runAsEnabled": true, "runAsDefaultUser": "", "idleSessionTimeout": "20", "maxSessionDuration": "60", "shellProfile": { "windows": "date", "linux": "pwd;ls" } } } InteractiveCommands type Session document example YAML --- schemaVersion: '1.0' description: Document to view a log file on a Linux instance sessionType: InteractiveCommands parameters: logpath: type: String description: The log file path to read. default: "/var/log/amazon/ssm/amazon-ssm-agent.log" allowedPattern: "^[a-zA-Z0-9-_/]+(.log)$" properties: linux: commands: "tail -f {{ logpath }}" runAsElevated: true JSON { "schemaVersion": "1.0", "description": "Document to view a log file on a Linux instance", Session Manager 959 AWS Systems Manager User Guide "sessionType": "InteractiveCommands", "parameters": { "logpath": { "type": "String", "description": "The log file path to read.", "default": "/var/log/amazon/ssm/amazon-ssm-agent.log", "allowedPattern": "^[a-zA-Z0-9-_/]+(.log)$" } }, "properties": { "linux": { "commands": "tail -f {{ logpath }}", "runAsElevated": true } } } Port type Session document example YAML --- schemaVersion: '1.0' description: Document to open given port connection over Session Manager sessionType: Port parameters: paramExample: type: string description: document parameter properties: portNumber: anyPortNumber JSON { "schemaVersion": "1.0", "description": "Document to open given port connection over Session Manager", "sessionType": "Port", "parameters": { "paramExample": { "type": "string", "description": "document parameter" Session Manager 960 AWS Systems Manager User Guide } }, "properties": { "portNumber": "anyPortNumber" } } Session document example with special characters YAML --- schemaVersion: '1.0' description: Example document with quotation marks sessionType: InteractiveCommands parameters: Test: type: String description: Test Input maxChars: 32 properties: windows: commands: | $Test = '{{ Test }}' $myVariable = \"Computer name is $env:COMPUTERNAME\" Write-Host "Test variable: $myVariable`.`nInput parameter: $Test" runAsElevated: false JSON { "schemaVersion":"1.0", "description":"Test document with quotation marks", "sessionType":"InteractiveCommands", "parameters":{ "Test":{ "type":"String", "description":"Test Input", "maxChars":32 } }, "properties":{ Session Manager 961 AWS Systems Manager User Guide "windows":{ "commands":[ "$Test = '{{ Test }}'", "$myVariable = \\\"Computer name is $env:COMPUTERNAME\\\"", "Write-Host \"Test variable: $myVariable`.`nInput parameter: $Test\"" ], "runAsElevated":false } } } Troubleshooting Session Manager Use the following information to help you troubleshoot problems with AWS Systems Manager Session Manager. Topics • AccessDeniedException when calling the TerminateSession operation • Document process failed unexpectedly: document worker timed out • Session Manager can't connect from the Amazon EC2 console • No permission to start a session • SSM Agent not online • No permission to change session preferences • Managed node not available or not configured for Session Manager • Session Manager plugin not found • Session Manager plugin not automatically added to command line path (Windows) • Session Manager plugin becomes unresponsive • TargetNotConnected • Blank screen displays after starting a session • Managed node becomes unresponsive during long running sessions • An error occurred (InvalidDocument) when calling the StartSession operation AccessDeniedException when calling the TerminateSession operation Problem: When attempting to terminate a session, Systems Manager returns the following error: Session Manager 962 AWS Systems Manager User Guide An error occurred (AccessDeniedException) when calling the TerminateSession operation: User: <user_arn> is not authorized to perform: ssm:TerminateSession on resource: <ssm_session_arn> because no identity-based policy allows the ssm:TerminateSession action. Solution A: Confirm that the latest version of the Session Manager plugin is installed on the node Enter the following command in the terminal and press Enter. session-manager-plugin --version Solution B: Install or reinstall the latest version of the plugin For more information, see Install the Session Manager plugin for the AWS CLI. Solution C: Attempt to reestablish a connection to the node Verify that the node is responding to requests. Try reestablishing the session. Or, if necessary, open the
|
systems-manager-ug-299
|
systems-manager-ug.pdf
| 299 |
operation: User: <user_arn> is not authorized to perform: ssm:TerminateSession on resource: <ssm_session_arn> because no identity-based policy allows the ssm:TerminateSession action. Solution A: Confirm that the latest version of the Session Manager plugin is installed on the node Enter the following command in the terminal and press Enter. session-manager-plugin --version Solution B: Install or reinstall the latest version of the plugin For more information, see Install the Session Manager plugin for the AWS CLI. Solution C: Attempt to reestablish a connection to the node Verify that the node is responding to requests. Try reestablishing the session. Or, if necessary, open the Amazon EC2 console and verify the status of the instance is running. Document process failed unexpectedly: document worker timed out Problem: When starting a session to a Linux host, Systems Manager returns the following error: document process failed unexpectedly: document worker timed out, check [ssm-document-worker]/[ssm-session-worker] log for crash reason If you configured SSM Agent logging, as described in Viewing SSM Agent logs, you can view more details in the debugging log. For this issue, Session Manager shows the following log entry: failed to create channel: too many open files This error typically indicates that there are too many Session Manager worker processes running and the underlying operating system reached a limit. You have two options for resolving this issue. Solution A: Increase the operating system file notification limit You can increase the limit by running the following command from a separate Linux host. This command uses Systems Manager Run Command. The specified value increases Session Manager 963 AWS Systems Manager User Guide max_user_instances to 8192. This value is considerably higher than the default value of 128, but it won't strain host resources: aws ssm send-command --document-name AWS-RunShellScript \ --instance-id i-02573cafcfEXAMPLE --parameters \ "commands=sudo sysctl fs.inotify.max_user_instances=8192" Solution B: Decrease the file notifications used by Session Manager in the target host Run the following command from a separate Linux host to list sessions running on the target host: aws ssm describe-sessions --state Active --filters key=Target,value=i-02573cafcfEXAMPLE Review the command output to identify sessions that are no longer needed. You can terminate those session by running the following command from a separate Linux host: aws ssm terminate-session —session-id session ID Optionally, once there are no more sessions running on the remote server, you can free additional resources by running the following command from a separate Linux host. This command terminates all Session Manager processes running on the remote host, and consequently all sessions to the remote host. Before you run this command, verify there are no ongoing sessions you would like to keep: aws ssm send-command --document-name AWS-RunShellScript \ --instance-id i-02573cafcfEXAMPLE --parameters \ '{"commands":["sudo kill $(ps aux | grep ssm-session-worker | grep -v grep | awk '"'"'{print $2}'"'"')"]}' Session Manager can't connect from the Amazon EC2 console Problem: After creating a new instance, the Connect button > Session Manager tab in the Amazon Elastic Compute Cloud (Amazon EC2) console doesn't give you the option to connect. Solution A: Create an instance profile: If you haven't already done so (as instructed by the information on the Session Manager tab in the EC2 console), create an AWS Identity and Access Management (IAM) instance profile by using Quick Setup. Quick Setup is a tool in AWS Systems Manager. Session Manager 964 AWS Systems Manager User Guide Session Manager requires an IAM instance profile to connect to your instance. You can create an instance profile and assign it to your instance by creating a host management configuration with Quick Setup. A host management configuration creates an instance profile with the required permissions and assigns it to your instance. A host management configuration also enables other Systems Manager tools and creates IAM roles for running those tools. There is no charge to use Quick Setup or the tools enabled by the host management configuration. Open Quick Setup and create a host management configuration. Important After you create the host management configuration, Amazon EC2 can take several minutes to register the change and refresh the Session Manager tab. If the tab doesn't show you a Connect button after two minutes, reboot your instance. After it reboots, if you still don't see the option to connect, open Quick Setup and verify you have only one host management configuration. If there are two, delete the older configuration and wait a few minutes. If you still can't connect after creating a host management configuration, or if you receive an error, including an error about SSM Agent, see one of the following solutions: • Solution B: No error, but still can't connect • Solution C: Error about missing SSM Agent Solution B: No error, but still can't connect If you created the host management configuration, waited several minutes before trying to connect, and still can't connect, then you might need to manually apply the
|
systems-manager-ug-300
|
systems-manager-ug.pdf
| 300 |
you have only one host management configuration. If there are two, delete the older configuration and wait a few minutes. If you still can't connect after creating a host management configuration, or if you receive an error, including an error about SSM Agent, see one of the following solutions: • Solution B: No error, but still can't connect • Solution C: Error about missing SSM Agent Solution B: No error, but still can't connect If you created the host management configuration, waited several minutes before trying to connect, and still can't connect, then you might need to manually apply the host management configuration to your instance. Use the following procedure to update a Quick Setup host management configuration and apply changes to an instance. To update a host management configuration using Quick Setup 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. In the navigation pane, choose Quick Setup. In the Configurations list, choose the Host Management configuration you created. 2. 3. Session Manager 965 AWS Systems Manager User Guide 4. Choose Actions, and then choose Edit configuration. 5. Near the bottom of the Targets section, under Choose how you want to target instances, choose Manual. 6. In the Instances section, choose the instance you created. 7. Choose Update. Wait a few minutes for EC2 to refresh the Session Manager tab. If you still can't connect or if you receive an error, review the remaining solutions for this issue. Solution C: Error about missing SSM Agent If you weren't able to create a host management configuration by using Quick Setup, or if you received an error about SSM Agent not being installed, you may need to manually install SSM Agent on your instance. SSM Agent is Amazon software that enables Systems Manager to connect to your instance by using Session Manager. SSM Agent is installed by default on most Amazon Machine Images (AMIs). If your instance was created from a non-standard AMI or an older AMI, you might have to manually install the agent. For the procedure to install SSM Agent, see the following topic that corresponds to your instance operating system. • Windows Server • macOS • AlmaLinux • Amazon Linux 1 • Amazon Linux 2 and AL2023 • CentOS • CentOS Stream • Debian Server • Oracle Linux • Red Hat Enterprise Linux • Rocky Linux • SUSE Linux Enterprise Server • Ubuntu Server For issues with SSM Agent, see Troubleshooting SSM Agent. Session Manager 966 AWS Systems Manager No permission to start a session User Guide Problem: You try to start a session, but the system tells you that you don't have the necessary permissions. • Solution: A system administrator hasn't granted you AWS Identity and Access Management (IAM) policy permissions for starting Session Manager sessions. For information, see Control user session access to instances. SSM Agent not online Problem: You see a message on the Amazon EC2 instance Session Manager tab that states: "SSM Agent is not online. The SSM Agent was unable to connect to a Systems Manager endpoint to register itself with the service." Solution: SSM Agent is Amazon software that runs on Amazon EC2 instances so that Session Manager can connect to them. If you see this error, SSM Agent is unable to establish a connection with the Systems Manager endpoint. Possible sources of the problem could be firewall restrictions, routing problems, or lack of internet connectivity. To resolve this issue, investigate network connectivity problems. For more information, see Troubleshooting SSM Agent and Troubleshooting managed node availability. For information about Systems Manager endpoints, see AWS Systems Manager endpoints and quotas in the AWS General Reference. No permission to change session preferences Problem: You try to update global session preferences for your organization, but the system tells you that you don't have the necessary permissions. • Solution: A system administrator hasn't granted you IAM policy permissions for setting Session Manager preferences. For information, see Grant or deny a user permissions to update Session Manager preferences. Managed node not available or not configured for Session Manager Problem 1: You want to start a session on the Start a session console page, but a managed node isn't in the list. • Solution A: The managed node you want to connect to might not have been configured for AWS Systems Manager. For more information, see Setting up Systems Manager unified console for an organization. Session Manager 967 AWS Systems Manager Note User Guide If AWS Systems Manager SSM Agent is already running on a managed node when you attach the IAM instance profile, you might need to restart the agent before the instance is listed on the Start a session console page. • Solution B: The proxy configuration you applied to the SSM Agent on your managed node might be incorrect. If the proxy configuration is
|
systems-manager-ug-301
|
systems-manager-ug.pdf
| 301 |
node you want to connect to might not have been configured for AWS Systems Manager. For more information, see Setting up Systems Manager unified console for an organization. Session Manager 967 AWS Systems Manager Note User Guide If AWS Systems Manager SSM Agent is already running on a managed node when you attach the IAM instance profile, you might need to restart the agent before the instance is listed on the Start a session console page. • Solution B: The proxy configuration you applied to the SSM Agent on your managed node might be incorrect. If the proxy configuration is incorrect, the managed node won't be able to reach the needed service endpoints, or the node might report as a different operating system to Systems Manager. For more information, see Configuring SSM Agent to use a proxy on Linux nodes and Configure SSM Agent to use a proxy for Windows Server instances. Problem 2: A managed node you want to connect is in the list on the Start a session console page, but the page reports that "The instance you selected isn't configured to use Session Manager." • Solution A: The managed node has been configured for use with the Systems Manager service, but the IAM instance profile attached to the node might not include permissions for the Session Manager tool. For information, see Verify or Create an IAM Instance Profile with Session Manager Permissions. • Solution B: The managed node isn't running a version of SSM Agent that supports Session Manager. Update SSM Agent on the node to version 2.3.68.0 or later. Update SSM Agent manually on a managed node by following the steps in Manually installing and uninstalling SSM Agent on EC2 instances for Windows Server, Manually installing and uninstalling SSM Agent on EC2 instances for Linux, or Manually installing and uninstalling SSM Agent on EC2 instances for macOS, depending on the operating system. Alternatively, use the Run Command document AWS-UpdateSSMAgent to update the agent version on one or more managed nodes at a time. For information, see Updating the SSM Agent using Run Command. Tip To always keep your agent up to date, we recommend updating SSM Agent to the latest version on an automated schedule that you define using either of the following methods: • Run AWS-UpdateSSMAgent as part of a State Manager association. For information, see Walkthrough: Automatically update SSM Agent with the AWS CLI. Session Manager 968 AWS Systems Manager User Guide • Run AWS-UpdateSSMAgent as part of a maintenance window. For information about working with maintenance windows, see Create and manage maintenance windows using the console and Tutorial: Create and configure a maintenance window using the AWS CLI. • Solution C: The managed node can't reach the requisite service endpoints. You can improve the security posture of your managed nodes by using interface endpoints powered by AWS PrivateLink to connect to Systems Manager endpoints. The alternative to using interface endpoints is to allow outbound internet access on your managed nodes. For more information, see Use PrivateLink to set up a VPC endpoint for Session Manager. • Solution D: The managed node has limited available CPU or memory resources. Although your managed node might otherwise be functional, if the node doesn't have enough available resources, you can't establish a session. For more information, see Troubleshooting an Unreachable Instance. Session Manager plugin not found To use the AWS CLI to run session commands, the Session Manager plugin must also be installed on your local machine. For information, see Install the Session Manager plugin for the AWS CLI. Session Manager plugin not automatically added to command line path (Windows) When you install the Session Manager plugin on Windows, the session-manager-plugin executable should be automatically added to your operating system's PATH environment variable. If the command failed after you ran it to check whether the Session Manager plugin installed correctly (aws ssm start-session --target instance-id), you might need to set it manually using the following procedure. To modify your PATH variable (Windows) 1. Press the Windows key and enter environment variables. 2. Choose Edit environment variables for your account. 3. Choose PATH and then choose Edit. 4. Add paths to the Variable value field, separated by semicolons, as shown in this example: C: \existing\path;C:\new\path C:\existing\path represents the value already in the field. C:\new\path represents the path you want to add, as shown in these examples. Session Manager 969 AWS Systems Manager User Guide • 64-bit machines: C:\Program Files\Amazon\SessionManagerPlugin\bin\ • 32-bit machines: C:\Program Files (x86)\Amazon\SessionManagerPlugin\bin\ 5. Choose OK twice to apply the new settings. 6. Close any running command prompts and re-open. Session Manager plugin becomes unresponsive During a port forwarding session, traffic might stop forwarding if you have antivirus software installed on your local machine. In some cases, antivirus software interferes with the Session Manager plugin causing
|
systems-manager-ug-302
|
systems-manager-ug.pdf
| 302 |
as shown in this example: C: \existing\path;C:\new\path C:\existing\path represents the value already in the field. C:\new\path represents the path you want to add, as shown in these examples. Session Manager 969 AWS Systems Manager User Guide • 64-bit machines: C:\Program Files\Amazon\SessionManagerPlugin\bin\ • 32-bit machines: C:\Program Files (x86)\Amazon\SessionManagerPlugin\bin\ 5. Choose OK twice to apply the new settings. 6. Close any running command prompts and re-open. Session Manager plugin becomes unresponsive During a port forwarding session, traffic might stop forwarding if you have antivirus software installed on your local machine. In some cases, antivirus software interferes with the Session Manager plugin causing process deadlocks. To resolve this issue, allow or exclude the Session Manager plugin from the antivirus software. For information about the default installation path for the Session Manager plugin, see Install the Session Manager plugin for the AWS CLI. TargetNotConnected Problem: You try to start a session, but the system returns the error message, "An error occurred (TargetNotConnected) when calling the StartSession operation: InstanceID isn't connected." • Solution A: This error is returned when the specified target managed node for the session isn't fully configured for use with Session Manager. For information, see Setting up Session Manager. • Solution B: This error is also returned if you attempt to start a session on a managed node that is located in a different AWS account or AWS Region. Blank screen displays after starting a session Problem: You start a session and Session Manager displays a blank screen. • Solution A: This issue can occur when the root volume on the managed node is full. Due to lack of disk space, SSM Agent on the node stops working. To resolve this issue, use Amazon CloudWatch to collect metrics and logs from the operating systems. For information, see Collect metrics, logs, and traces with the CloudWatch agent in the Amazon CloudWatch User Guide. • Solution B: A blank screen might display if you accessed the console using a link that includes a mismatched endpoint and Region pair. For example, in the following console URL, us-west-2 is the specified endpoint, but us-west-1 is the specified AWS Region. Session Manager 970 AWS Systems Manager User Guide https://us-west-2.console.aws.amazon.com/systems-manager/session-manager/sessions? region=us-west-1 • Solution C: The managed node is connecting to Systems Manager using VPC endpoints, and your Session Manager preferences write session output to an Amazon S3 bucket or Amazon CloudWatch Logs log group, but an s3 gateway endpoint or logs interface endpoint doesn't exist in the VPC. An s3 endpoint in the format com.amazonaws.region.s3 is required if your managed nodes are connecting to Systems Manager using VPC endpoints, and your Session Manager preferences write session output to an Amazon S3 bucket. Alternatively, a logs endpoint in the format com.amazonaws.region.logs is required if your managed nodes are connecting to Systems Manager using VPC endpoints, and your Session Manager preferences write session output to a CloudWatch Logs log group. For more information, see Creating VPC endpoints for Systems Manager. • Solution D: The log group or Amazon S3 bucket you specified in your session preferences has been deleted. To resolve this issue, update your session preferences with a valid log group or S3 bucket. • Solution E: The log group or Amazon S3 bucket you specified in your session preferences isn't encrypted, but you have set the cloudWatchEncryptionEnabled or s3EncryptionEnabled input to true. To resolve this issue, update your session preferences with a log group or Amazon S3 bucket that is encrypted, or set the cloudWatchEncryptionEnabled or s3EncryptionEnabled input to false. This scenario is only applicable to customers who create session preferences using command line tools. Managed node becomes unresponsive during long running sessions Problem: Your managed node becomes unresponsive or crashes during a long running session. Solution: Decrease the SSM Agent log retention duration for Session Manager. To decrease the SSM Agent log retention duration for sessions 1. Locate the amazon-ssm-agent.json.template in the /etc/amazon/ssm/ directory for Linux, or C:\Program Files\Amazon\SSM for Windows. 2. Copy the contents of the amazon-ssm-agent.json.template to a new file in the same directory named amazon-ssm-agent.json. Session Manager 971 AWS Systems Manager User Guide 3. Decrease the default value of the SessionLogsRetentionDurationHours value in the SSM property, and save the file. 4. Restart the SSM Agent. An error occurred (InvalidDocument) when calling the StartSession operation Problem: You receive the following error when starting a session by using the AWS CLI. An error occurred (InvalidDocument) when calling the StartSession operation: Document type: 'Command' is not supported. Only type: 'Session' is supported for Session Manager. Solution: The SSM document you specified for the --document-name parameter isn't a Session document. Use the following procedure to view a list of Session documents in the AWS Management Console. To view a list of Session documents 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. 3. In the navigation
|
systems-manager-ug-303
|
systems-manager-ug.pdf
| 303 |
Agent. An error occurred (InvalidDocument) when calling the StartSession operation Problem: You receive the following error when starting a session by using the AWS CLI. An error occurred (InvalidDocument) when calling the StartSession operation: Document type: 'Command' is not supported. Only type: 'Session' is supported for Session Manager. Solution: The SSM document you specified for the --document-name parameter isn't a Session document. Use the following procedure to view a list of Session documents in the AWS Management Console. To view a list of Session documents 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. 3. In the navigation pane, choose Documents. In the Categories list, choose Session documents. AWS Systems Manager State Manager State Manager, a tool in AWS Systems Manager, is a secure and scalable configuration management service that automates the process of keeping your managed nodes and other AWS resources in a state that you define. To get started with State Manager, open the Systems Manager console. In the navigation pane, choose State Manager. Note State Manager and Maintenance Windows can perform some similar types of updates on your managed nodes. Which one you choose depends on whether you need to automate system compliance or perform high-priority, time-sensitive tasks during periods you specify. For more information, see Choosing between State Manager and Maintenance Windows. State Manager 972 AWS Systems Manager User Guide How can State Manager benefit my organization? By using pre-configured Systems Manager documents (SSM documents), State Manager offers the following benefits for managing your nodes: • Bootstrap nodes with specific software at start-up. • Download and update agents on a defined schedule, including the SSM Agent. • Configure network settings. • Join nodes to a Microsoft Active Directory domain. • Run scripts on Linux, macOS, and Windows managed nodes throughout their lifecycle. To manage configuration drift across other AWS resources, you can use Automation, a tool in Systems Manager, with State Manager to perform the following types of tasks: • Attach a Systems Manager role to Amazon Elastic Compute Cloud (Amazon EC2) instances to make them managed nodes. • Enforce desired ingress and egress rules for a security group. • Create or delete Amazon DynamoDB backups. • Create or delete Amazon Elastic Block Store (Amazon EBS) snapshots. • Turn off read and write permissions on Amazon Simple Storage Service (Amazon S3) buckets. • Start, restart, or stop managed nodes and Amazon Relational Database Service (Amazon RDS) instances. • Apply patches to Linux, macOS, and Window AMIs. For information about using State Manager with Automation runbooks, see Scheduling automations with State Manager associations. Who should use State Manager? State Manager is appropriate for any AWS customer that wants to improve the management and governance of their AWS resources and reduce configuration drift. What are the features of State Manager? Key features of State Manager include the following: State Manager 973 AWS Systems Manager • State Manager associations User Guide A State Manager association is a configuration that you assign to your AWS resources. The configuration defines the state that you want to maintain on your resources. For example, an association can specify that antivirus software must be installed and running on a managed node, or that certain ports must be closed. An association specifies a schedule for when to apply the configuration and the targets for the association. For example, an association for antivirus software might run once a day on all managed nodes in an AWS account. If the software isn't installed on a node, then the association could instruct State Manager to install it. If the software is installed, but the service isn't running, then the association could instruct State Manager to start the service. • Flexible scheduling options State Manager offers the following options for scheduling when an association runs: • Immediate or delayed processing When you create an association, by default, the system immediately runs it on the specified resources. After the initial run, the association runs in intervals according to the schedule that you defined. You can instruct State Manager not to run an association immediately by using the Apply association only at the next specified Cron interval option in the console or the ApplyOnlyAtCronInterval parameter from the command line. • Cron and rate expressions When you create an association, you specify a schedule for when State Manager applies the configuration. State Manager supports most standard cron and rate expressions for scheduling when an association runs. State Manager also supports cron expressions that include a day of the week and the number sign (#) to designate the nth day of a month to run an association and the (L) sign to indicate the last X day of the month. Note State Manager doesn't currently support specifying months in cron expressions for associations. State Manager 974 AWS Systems Manager User Guide
|
systems-manager-ug-304
|
systems-manager-ug.pdf
| 304 |
• Cron and rate expressions When you create an association, you specify a schedule for when State Manager applies the configuration. State Manager supports most standard cron and rate expressions for scheduling when an association runs. State Manager also supports cron expressions that include a day of the week and the number sign (#) to designate the nth day of a month to run an association and the (L) sign to indicate the last X day of the month. Note State Manager doesn't currently support specifying months in cron expressions for associations. State Manager 974 AWS Systems Manager User Guide To further control when an association runs, for example if you want to run an association two days after patch Tuesday, you can specify an offset. An offset defines how many days to wait after the scheduled day to run an association. For information about building cron and rate expressions, see Reference: Cron and rate expressions for Systems Manager. • Multiple targeting options An association also specifies the targets for the association. State Manager supports targeting AWS resources by using tags, AWS Resource Groups, individual node IDs, or all managed nodes in the current AWS Region and AWS account. • Amazon S3 support Store the command output from association runs in an Amazon S3 bucket of your choice. For more information, see Working with associations in Systems Manager. • EventBridge support This Systems Manager tool is supported as both an event type and a target 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. Is there a charge to use State Manager? State Manager is available at no additional charge. Topics • Understanding how State Manager works • Working with associations in Systems Manager • Creating associations that run MOF files • Creating associations that run Ansible playbooks • Creating associations that run Chef recipes • Walkthrough: Automatically update SSM Agent with the AWS CLI • Walkthrough: Automatically update PV drivers on EC2 instances for Windows Server State Manager 975 AWS Systems Manager More info User Guide • Combating Configuration Drift Using Amazon EC2 Systems Manager and Windows PowerShell DSC • Configure Amazon EC2 Instances in an Auto Scaling Group Using State Manager Understanding how State Manager works State Manager, a tool in AWS Systems Manager, is a secure and scalable service that automates the process of keeping managed nodes in a hybrid and multicloud infrastructure in a state that you define. Here's how State Manager works: 1. Determine the state you want to apply to your AWS resources. Do you want to guarantee that your managed nodes are configured with specific applications, such as antivirus or malware applications? Do you want to automate the process of updating the SSM Agent or other AWS packages such as AWSPVDriver? Do you need to guarantee that specific ports are closed or open? To get started with State Manager, determine the state that you want to apply to your AWS resources. The state that you want to apply determines which SSM document you use to create a State Manager association. A State Manager association is a configuration that you assign to your AWS resources. The configuration defines the state that you want to maintain on your resources. For example, an association can specify that antivirus software must be installed and running on a managed node, or that certain ports must be closed. An association specifies a schedule for when to apply the configuration and the targets for the association. For example, an association for antivirus software might run once a day on all managed nodes in an AWS account. If the software isn't installed on a node, then the association could instruct State Manager to install it. If the software is installed, but the service isn't running, then the association could instruct State Manager to start the service. 2. Determine if a preconfigured SSM document can help you create the desired state on your AWS resources. Systems Manager includes dozens of preconfigured SSM documents that you can use to create an association. Preconfigured documents are ready to perform common tasks like installing applications, configuring Amazon CloudWatch, running AWS Systems Manager automations, State Manager 976 AWS Systems Manager User Guide running PowerShell and Shell scripts, and joining managed nodes to a directory service domain for Active Directory. You can view all SSM documents in the Systems Manager console. Choose the name of a document to learn more about each one. Here are two examples: AWS-ConfigureAWSPackage and AWS-InstallApplication. 3. Create an association. You can create an association by using the Systems Manager console, the AWS Command Line Interface (AWS CLI), AWS Tools for Windows PowerShell (Tools for Windows PowerShell), or the Systems Manager API. When you create an
|
systems-manager-ug-305
|
systems-manager-ug.pdf
| 305 |
running AWS Systems Manager automations, State Manager 976 AWS Systems Manager User Guide running PowerShell and Shell scripts, and joining managed nodes to a directory service domain for Active Directory. You can view all SSM documents in the Systems Manager console. Choose the name of a document to learn more about each one. Here are two examples: AWS-ConfigureAWSPackage and AWS-InstallApplication. 3. Create an association. You can create an association by using the Systems Manager console, the AWS Command Line Interface (AWS CLI), AWS Tools for Windows PowerShell (Tools for Windows PowerShell), or the Systems Manager API. When you create an association, you specify the following information: • A name for the association. • The parameters for the SSM document (for example, the path to the application to install or the script to run on the nodes). • Targets for the association. You can target managed nodes by specifying tags, by choosing individual node IDs, or by choosing a group in AWS Resource Groups. You can also target all managed nodes in the current AWS Region and AWS account. If your targets include more than 1,000 nodes, the system uses an hourly throttling mechanism. This means you might see inaccuracies in your status aggregation count since the aggregation process runs hourly and only when the execution status for a node changes. • A schedule for when or how often to apply the state. You can specify a cron or rate expression. For more information about creating schedules by using cron and rate expressions, see Cron and rate expressions for associations. Note State Manager doesn't currently support specifying months in cron expressions for associations. When you run the command to create the association, Systems Manager binds the information you specified (schedule, targets, SSM document, and parameters) to the targeted resources. The status of the association initially shows "Pending" as the system attempts to reach all targets and immediately apply the state specified in the association. State Manager 977 AWS Systems Manager Note User Guide If you create a new association that is scheduled to run while an earlier association is still running, the earlier association times out and the new association runs. Systems Manager reports the status of the request to create associations on the resources. You can view status details in the console or (for managed nodes) by using the DescribeInstanceAssociationsStatus API operation. If you choose to write the output of the command to Amazon Simple Storage Service (Amazon S3) when you create an association, you can also view the output in the Amazon S3 bucket you specified. For more information, see Working with associations in Systems Manager. Note API operations that are initiated by the SSM document during an association run are not logged in AWS CloudTrail. 4. Monitor and update. After you create the association, State Manager reapplies the configuration according to the schedule that you defined in the association. You can view the status of your associations on the State Manager page in the console or by directly calling the association ID generated by Systems Manager when you created the association. For more information, see Viewing association histories. You can update your association documents and reapply them as necessary. You can also create multiple versions of an association. For more information, see Editing and creating a new version of an association. Understanding when associations are applied to resources When you create an association, you specify an SSM document that defines the configuration, a list of target resources, and a schedule for applying the configuration. By default, State Manager runs the association when you create it and then according to your schedule. State Manager also attempts to run the association in the following situations: State Manager 978 AWS Systems Manager User Guide • Association edit – State Manager runs the association after a user edits and saves their changes to any of the following association fields: DOCUMENT_VERSION, PARAMETERS, SCHEDULE_EXPRESSION, OUTPUT_S3_LOCATION. • Document edit – State Manager runs the association after a user edits and saves changes to the SSM document that defines the association's configuration state. Specifically, the association runs after the following edits to the document: • A user specifies a new $DEFAULT document version and the association was created using the $DEFAULT version. • A user updates a document and the association was created using the $LATEST version. • A user deletes the document that was specified when the association was created. • Manual start – State Manager runs the association when initiated by the user from either the Systems Manager console or programmatically. • Target changes – State Manager runs the association after any of the following activity occurs on a target node: • A managed node comes online for the first time. • A managed node comes online after missing a scheduled association run. •
|
systems-manager-ug-306
|
systems-manager-ug.pdf
| 306 |
was created using the $DEFAULT version. • A user updates a document and the association was created using the $LATEST version. • A user deletes the document that was specified when the association was created. • Manual start – State Manager runs the association when initiated by the user from either the Systems Manager console or programmatically. • Target changes – State Manager runs the association after any of the following activity occurs on a target node: • A managed node comes online for the first time. • A managed node comes online after missing a scheduled association run. • A managed node comes online after being stopped for more than 30 days. Note State Manager doesn't monitor documents or packages used in associations across AWS accounts. If you update a document or package in one account, the update won't cause the association to run in the second account. You must manually run the association in the second account. Preventing associations from running when a target changes In some cases, you might not want an association to run when a target that consists of managed nodes changes, but only according to its specified schedule. State Manager 979 AWS Systems Manager Note User Guide Running an Automation runbook incurs a cost. If an association with an Automation runbook targets all instances in your account and you regularly launch a large number of instances, the runbook is run on each of the instances when it launches. This can lead to elevated automation charges. To prevent an association from running when the targets for that association change, select the Apply association only at the next specified cron interval check box. This check box is located in the Specify schedule area of the Create association and Edit association pages. This option applies to associations that incorporate either an Automation runbook or an SSM document. About target updates with Automation runbooks In order for associations that are created with Automation runbooks to be applied when new target nodes are detected, the following conditions must be true: • The association must have been created by a Quick Setup configuration. Quick Setup is a tool in AWS Systems Manager. Associations created by other processes are not currently supported. • The Automation runbook must explicitly target the resource type AWS::EC2::Instance or AWS::SSM::ManagedInstance. • The association must specify both parameters and targets. In the console, the Parameter and Targets fields are displayed when you choose a rate control execution. State Manager 980 AWS Systems Manager User Guide When you use the CreateAssociation, CreateAssociationBatch, or UpdateAssociation API actions, you can specify these values using the AutomationTargetParameterName and Targets inputs. In each of these API actions, you can also prevent the association from running each time a target changes by setting the ApplyOnlyAtCronInterval parameter to true. For information about using the console to control when associations run, including details for avoiding unexpectedly high costs for Automation executions, see Understanding when associations are applied to resources. Working with associations in Systems Manager This section describes how to create and manage State Manager associations by using the AWS Systems Manager console, the AWS Command Line Interface (AWS CLI), and AWS Tools for PowerShell. Topics • Understanding targets and rate controls in State Manager associations • Creating associations State Manager 981 AWS Systems Manager User Guide • Editing and creating a new version of an association • Deleting associations • Running Auto Scaling groups with associations • Viewing association histories • Working with associations using IAM Understanding targets and rate controls in State Manager associations This topic describes State Manager features that help you deploy an association to dozens or hundreds of nodes while controlling the number of nodes that run the association at the scheduled time. State Manager is a tool in AWS Systems Manager. Using targets When you create a State Manager association, you choose which nodes to configure with the association in the Targets section of the Systems Manager console, as shown here. If you create an association by using a command line tool such as the AWS Command Line Interface (AWS CLI), then you specify the targets parameter. Targeting nodes allows you to configure tens, hundreds, or thousands of nodes with an association without having to specify or choose individual node IDs. State Manager 982 AWS Systems Manager User Guide Each managed node can be targeted by a maximum of 20 associations. State Manager includes the following target options when creating an association. Specify tags Use this option to specify a tag key and (optionally) a tag value assigned to your nodes. When you run the request, the system locates and attempts to create the association on all nodes that match the specified tag key and value. If you specified multiple tag values, the association targets any node with at
|
systems-manager-ug-307
|
systems-manager-ug.pdf
| 307 |
with an association without having to specify or choose individual node IDs. State Manager 982 AWS Systems Manager User Guide Each managed node can be targeted by a maximum of 20 associations. State Manager includes the following target options when creating an association. Specify tags Use this option to specify a tag key and (optionally) a tag value assigned to your nodes. When you run the request, the system locates and attempts to create the association on all nodes that match the specified tag key and value. If you specified multiple tag values, the association targets any node with at least one of those tag values. When the system initially creates the association, it runs the association. After this initial run, the system runs the association according to the schedule you specified. If you create new nodes and assign the specified tag key and value to those nodes, the system automatically applies the association, runs it immediately, and then runs it according to the schedule. This applies when the association uses a Command or Policy document and doesn't apply if the association uses an Automation runbook. If you delete the specified tags from a node, the system no longer runs the association on those nodes. Note If you use Automation runbooks with State Manager and the tagging limitation prevents you from achieving a specific goal, consider using Automation runbooks with Amazon EventBridge. For more information, see Run automations based on EventBridge events. For more information about using runbooks with State Manager, see Scheduling automations with State Manager associations. As a best practice, we recommend using tags when creating associations that use a Command or Policy document. We also recommend using tags when creating associations to run Auto Scaling groups. For more information, see Running Auto Scaling groups with associations. Note Note the following information. • When creating an association in the AWS Management Console that targets nodes by using tags, you can specify only one tag key for an automation association and five tag keys for a command association. All tag keys specified in the association must be State Manager 983 AWS Systems Manager User Guide currently assigned to the node. If they aren't, State Manager fails to target the node for an association. • If you want to use the console and you want to target your nodes by using more than one tag key for an automation association and five tag keys for a command association, assign the tag keys to an AWS Resource Groups group and add the nodes to it. You can then choose the Resource Group option in the Targets list when you create the State Manager association. • You can specify a maximum of five tag keys by using the AWS CLI. If you use the AWS CLI, all tag keys specified in the create-association command must be currently assigned to the node. If they aren't, State Manager fails to target the node for an association. Choose nodes manually Use this option to manually select the nodes where you want to create the association. The Instances pane displays all Systems Manager managed nodes in the current AWS account and AWS Region. You can manually select as many nodes as you want. When the system initially creates the association, it runs the association. After this initial run, the system runs the association according to the schedule you specified. Note If a managed node you expect to see isn't listed, see Troubleshooting managed node availability for troubleshooting tips. Choose a resource group Use this option to create an association on all nodes returned by an AWS Resource Groups tag- based or AWS CloudFormation stack-based query. Below are details about targeting resource groups for an association. • If you add new nodes to a group, the system automatically maps the nodes to the association that targets the resource group. The system applies the association to the nodes when it discovers the change. After this initial run, the system runs the association according to the schedule you specified. State Manager 984 AWS Systems Manager User Guide • If you create an association that targets a resource group and the AWS::SSM::ManagedInstance resource type was specified for that group, then by design, the association runs on both Amazon Elastic Compute Cloud (Amazon EC2) instances and non-EC2 nodes in a hybrid and multicloud environment. The converse is also true. If you create an association that targets a resource group and the AWS::EC2::Instance resource type was specified for that group, then by design, the association runs on both non-EC2 nodes in a hybrid and multicloud environment and (Amazon EC2) instances. • If you create an association that targets a resource group, the resource group must not have more than five tag keys assigned to it or more than five values specified for
|
systems-manager-ug-308
|
systems-manager-ug.pdf
| 308 |
by design, the association runs on both Amazon Elastic Compute Cloud (Amazon EC2) instances and non-EC2 nodes in a hybrid and multicloud environment. The converse is also true. If you create an association that targets a resource group and the AWS::EC2::Instance resource type was specified for that group, then by design, the association runs on both non-EC2 nodes in a hybrid and multicloud environment and (Amazon EC2) instances. • If you create an association that targets a resource group, the resource group must not have more than five tag keys assigned to it or more than five values specified for any one tag key. If either of these conditions applies to the tags and keys assigned to your resource group, the association fails to run and returns an InvalidTarget error. • If you create an association that targets a resource group using tags, you can't choose the (empty value) option for the tag value. • If you delete a resource group, all instances in that group no longer run the association. As a best practice, delete associations targeting the group. • At most you can target a single resource group for an association. Multiple or nested groups aren't supported. • After you create an association, State Manager periodically updates the association with information about resources in the Resource Group. If you add new resources to a Resource Group, the schedule for when the system applies the association to the new resources depends on several factors. You can determine the status of the association in the State Manager page of the Systems Manager console. Warning An AWS Identity and Access Management (IAM) user, group, or role with permission to create an association that targets a resource group of Amazon EC2 instances automatically has root-level control of all instances in the group. Only trusted administrators should be permitted to create associations. For more information about Resource Groups, see What Is AWS Resource Groups? in the AWS Resource Groups User Guide. State Manager 985 AWS Systems Manager Choose all nodes User Guide Use this option to target all nodes in the current AWS account and AWS Region. When you run the request, the system locates and attempts to create the association on all nodes in the current AWS account and AWS Region. When the system initially creates the association, it runs the association. After this initial run, the system runs the association according to the schedule you specified. If you create new nodes, the system automatically applies the association, runs it immediately, and then runs it according to the schedule. Using rate controls You can control the execution of an association on your nodes by specifying a concurrency value and an error threshold. The concurrency value specifies how many nodes can run the association simultaneously. An error threshold specifies how many association executions can fail before Systems Manager sends a command to each node configured with that association to stop running the association. The command stops the association from running until the next scheduled execution. The concurrency and error threshold features are collectively called rate controls. Concurrency Concurrency helps to limit the impact on your nodes by allowing you to specify that only a certain number of nodes can process an association at one time. You can specify either an absolute number of nodes, for example 20, or a percentage of the target set of nodes, for example 10%. State Manager concurrency has the following restrictions and limitations: State Manager 986 AWS Systems Manager User Guide • If you choose to create an association by using targets, but you don't specify a concurrency value, then State Manager automatically enforces a maximum concurrency of 50 nodes. • If new nodes that match the target criteria come online while an association that uses concurrency is running, then the new nodes run the association if the concurrency value isn't exceeded. If the concurrency value is exceeded, then the nodes are ignored during the current association execution interval. The nodes run the association during the next scheduled interval while conforming to the concurrency requirements. • If you update an association that uses concurrency, and one or more nodes are processing that association when it's updated, then any node that is running the association is allowed to complete. Those associations that haven't started are stopped. After running associations complete, all target nodes immediately run the association again because it was updated. When the association runs again, the concurrency value is enforced. Error thresholds An error threshold specifies how many association executions are allowed to fail before Systems Manager sends a command to each node configured with that association. The command stops the association from running until the next scheduled execution. You can specify either an absolute number of errors, for example 10, or a percentage of the target
|
systems-manager-ug-309
|
systems-manager-ug.pdf
| 309 |
node that is running the association is allowed to complete. Those associations that haven't started are stopped. After running associations complete, all target nodes immediately run the association again because it was updated. When the association runs again, the concurrency value is enforced. Error thresholds An error threshold specifies how many association executions are allowed to fail before Systems Manager sends a command to each node configured with that association. The command stops the association from running until the next scheduled execution. You can specify either an absolute number of errors, for example 10, or a percentage of the target set, for example 10%. If you specify an absolute number of three errors, for example, State Manager sends the stop command when the fourth error is returned. If you specify 0, then State Manager sends the stop command after the first error result is returned. If you specify an error threshold of 10% for 50 associations, then State Manager sends the stop command when the sixth error is returned. Associations that are already running when an error threshold is reached are allowed to complete, but some of these associations might fail. To ensure that there aren't more errors than the number specified for the error threshold, set the Concurrency value to 1 so that associations proceed one at a time. State Manager error thresholds have the following restrictions and limitations: • Error thresholds are enforced for the current interval. • Information about each error, including step-level details, is recorded in the association history. • If you choose to create an association by using targets, but you don't specify an error threshold, then State Manager automatically enforces a threshold of 100% failures. State Manager 987 AWS Systems Manager Creating associations User Guide State Manager, a tool in AWS Systems Manager, helps you keep your AWS resources in a state that you define and reduce configuration drift. To do this, State Manager uses associations. An association is a configuration that you assign to your AWS resources. The configuration defines the state that you want to maintain on your resources. For example, an association can specify that antivirus software must be installed and running on a managed node, or that certain ports must be closed. An association specifies a schedule for when to apply the configuration and the targets for the association. For example, an association for antivirus software might run once a day on all managed nodes in an AWS account. If the software isn't installed on a node, then the association could instruct State Manager to install it. If the software is installed, but the service isn't running, then the association could instruct State Manager to start the service. Warning When you create an association, you can choose an AWS resource group of managed nodes as the target for the association. If an AWS Identity and Access Management (IAM) user, group, or role has permission to create an association that targets a resource group of managed nodes, then that user, group, or role automatically has root-level control of all nodes in the group. Permit only trusted administrators to create associations. Association targets and rate controls An association specifies which managed nodes, or targets, should receive the association. State Manager includes several features to help you target your managed nodes and control how the association is deployed to those targets. For more information about targets and rate controls, see Understanding targets and rate controls in State Manager associations. Tagging associations You can assign tags to an association when you create it by using a command line tool such as the AWS CLI or AWS Tools for PowerShell. Adding tags to an association by using the Systems Manager console isn't supported. Running associations State Manager 988 AWS Systems Manager User Guide By default, State Manager runs an association immediately after you create it, and then according to the schedule that you've defined. The system also runs associations according to the following rules: • State Manager attempts to run the association on all specified or targeted nodes during an interval. • If an association doesn't run during an interval (because, for example, a concurrency value limited the number of nodes that could process the association at one time), then State Manager attempts to run the association during the next interval. • State Manager runs the association after changes to the association's configuration, target nodes, documents, or parameters. For more information, see Understanding when associations are applied to resources • State Manager records history for all skipped intervals. You can view the history on the Execution History tab. Scheduling associations You can schedule associations to run at basic intervals such as every 10 hours, or you can create more advanced schedules using custom cron and rate expressions. You can also prevent associations from running when
|
systems-manager-ug-310
|
systems-manager-ug.pdf
| 310 |
association at one time), then State Manager attempts to run the association during the next interval. • State Manager runs the association after changes to the association's configuration, target nodes, documents, or parameters. For more information, see Understanding when associations are applied to resources • State Manager records history for all skipped intervals. You can view the history on the Execution History tab. Scheduling associations You can schedule associations to run at basic intervals such as every 10 hours, or you can create more advanced schedules using custom cron and rate expressions. You can also prevent associations from running when you first create them. Using cron and rate expressions to schedule association runs In addition to standard cron and rate expressions, State Manager also supports cron expressions that include a day of the week and the number sign (#) to designate the nth day of a month to run an association. Here is an example that runs a cron schedule on the third Tuesday of every month at 23:30 UTC: cron(30 23 ? * TUE#3 *) Here is an example that runs on the second Thursday of every month at midnight UTC: cron(0 0 ? * THU#2 *) State Manager also supports the (L) sign to indicate the last X day of the month. Here is an example that runs a cron schedule on the last Tuesday of every month at midnight UTC: cron(0 0 ? * 3L *) State Manager 989 AWS Systems Manager User Guide To further control when an association runs, for example if you want to run an association two days after patch Tuesday, you can specify an offset. An offset defines how many days to wait after the scheduled day to run an association. For example, if you specified a cron schedule of cron(0 0 ? * THU#2 *), you could specify the number 3 in the Schedule offset field to run the association each Sunday after the second Thursday of the month. Note To use offsets, you must either select Apply association only at the next specified Cron interval in the console or specify the ApplyOnlyAtCronInterval parameter from the command line. When either of these options are activated, State Manager doesn't run the association immediately after you create it. For more information about cron and rate expressions, see Reference: Cron and rate expressions for Systems Manager. Create an association (console) The following procedure describes how to use the Systems Manager console to create a State Manager association. Note Note the following information. • This procedure describes how to create an association that uses either a Command or a Policy document to target managed nodes. For information about creating an association that uses an Automation runbook to target nodes or other types of AWS resources, see Scheduling automations with State Manager associations. • When creating an association, you can specify a maximum of five tag keys by using the AWS Management Console. All tag keys specified for the association must be currently assigned to the node. If they aren't, State Manager fails to target the node for the association. State Manager 990 AWS Systems Manager User Guide To create a State Manager association 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose State Manager. 3. Choose Create association. 4. 5. 6. 7. In the Name field, specify a name. In the Document list, choose the option next to a document name. Note the document type. This procedure applies to Command and Policy documents. For information about creating an association that uses an Automation runbook, see Scheduling automations with State Manager associations. Important State Manager doesn't support running associations that use a new version of a document if that document is shared from another account. State Manager always runs the default version of a document if shared from another account, even though the Systems Manager console shows that a new version was processed. If you want to run an association using a new version of a document shared from another account, you must set the document version to default. For Parameters, specify the required input parameters. (Optional) Choose a CloudWatch alarm to apply to your association for monitoring. Note Note the following information about this step. • The alarms list displays a maximum of 100 alarms. If you don't see your alarm in the list, use the AWS Command Line Interface to create the association. For more information, see Create an association (command line). • To attach a CloudWatch alarm to your command, the IAM principal that creates the association must have permission for the iam:createServiceLinkedRole action. For more information about CloudWatch alarms, see Using Amazon CloudWatch alarms. State Manager 991 AWS Systems Manager User Guide • If your alarm activates, any pending command invocations or automations do not
|
systems-manager-ug-311
|
systems-manager-ug.pdf
| 311 |
Note the following information about this step. • The alarms list displays a maximum of 100 alarms. If you don't see your alarm in the list, use the AWS Command Line Interface to create the association. For more information, see Create an association (command line). • To attach a CloudWatch alarm to your command, the IAM principal that creates the association must have permission for the iam:createServiceLinkedRole action. For more information about CloudWatch alarms, see Using Amazon CloudWatch alarms. State Manager 991 AWS Systems Manager User Guide • If your alarm activates, any pending command invocations or automations do not run. 8. For Targets, choose an option. For information about using targets, see Understanding targets and rate controls in State Manager associations. Note In order for associations that are created with Automation runbooks to be applied when new target nodes are detected, certain conditions must be met. For information, see About target updates with Automation runbooks. 9. In the Specify schedule section, choose either On Schedule or No schedule. If you choose On Schedule, use the buttons provided to create a cron or rate schedule for the association. If you don't want the association to run immediately after you create it, choose Apply association only at the next specified Cron interval. 10. (Optional) In the Schedule offset field, specify a number between 1 and 6. 11. In the Advanced options section use Compliance severity to choose a severity level for the association and use Change Calendars to choose a change calendar for the association. Compliance reporting indicates whether the association state is compliant or noncompliant, along with the severity level you indicate here. For more information, see About State Manager association compliance. The change calendar determines when the association runs. If the calendar is closed, the association isn't applied. If the calendar is open, the association runs accordingly. For more information, see AWS Systems Manager Change Calendar. 12. In the Rate control section, choose options to control how the association runs on multiple nodes. For more information about using rate controls, see Understanding targets and rate controls in State Manager associations. In the Concurrency section, choose an option: • Choose targets to enter an absolute number of targets that can run the association simultaneously. • Choose percentage to enter a percentage of the target set that can run the association simultaneously. State Manager 992 AWS Systems Manager User Guide In the Error threshold section, choose an option: • Choose errors to enter an absolute number of errors that are allowed before State Manager stops running associations on additional targets. • Choose percentage to enter a percentage of errors that are allowed before State Manager stops running associations on additional targets. 13. (Optional) For Output options, to save the command output to a file, select the Enable writing output to S3 box. Enter the bucket and prefix (folder) names in the boxes. Note The S3 permissions that grant the ability to write the data to an S3 bucket are those of the instance profile assigned to the managed node, not those of the IAM user performing this task. For more information, see Configure instance permissions required for Systems Manager or Create an IAM service role for a hybrid environment. In addition, if the specified S3 bucket is in a different AWS account, verify that the instance profile or IAM service role associated with the managed node has the necessary permissions to write to that bucket. Following are the minimal permissions required to turn on Amazon S3 output for an association. You can further restrict access by attaching IAM policies to users or roles within an account. At minimum, an Amazon EC2 instance profile should have an IAM role with the AmazonSSMManagedInstanceCore managed policy and the following inline policy. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:GetObject", "s3:PutObjectAcl" ], "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*" } ] State Manager 993 AWS Systems Manager } User Guide For minimal permissions, the Amazon S3 bucket you export to must have the default settings defined by the Amazon S3 console. For more information about creating Amazon S3 buckets, see Creating a bucket in the Amazon S3 User Guide. Note API operations that are initiated by the SSM document during an association run are not logged in AWS CloudTrail. 14. Choose Create Association. Note If you delete the association you created, the association no longer runs on any targets of that association. Create an association (command line) The following procedure describes how to use the AWS CLI (on Linux or Windows) or Tools for PowerShell to create a State Manager association. This section includes several examples that show how to use targets and rate controls. Targets and rate controls allow you to assign an association to dozens or hundreds of nodes while controlling the execution of
|
systems-manager-ug-312
|
systems-manager-ug.pdf
| 312 |
the SSM document during an association run are not logged in AWS CloudTrail. 14. Choose Create Association. Note If you delete the association you created, the association no longer runs on any targets of that association. Create an association (command line) The following procedure describes how to use the AWS CLI (on Linux or Windows) or Tools for PowerShell to create a State Manager association. This section includes several examples that show how to use targets and rate controls. Targets and rate controls allow you to assign an association to dozens or hundreds of nodes while controlling the execution of those associations. For more information about targets and rate controls, see Understanding targets and rate controls in State Manager associations. Important This procedure describes how to create an association that uses either a Command or a Policy document to target managed nodes. For information about creating an association that uses an Automation runbook to target nodes or other types of AWS resources, see Scheduling automations with State Manager associations. Before you begin State Manager 994 AWS Systems Manager User Guide The targets parameter is an array of search criteria that targets nodes using a Key,Value combination that you specify. If you plan to create an association on dozens or hundreds of node by using the targets parameter, review the following targeting options before you begin the procedure. Target specific nodes by specifying IDs --targets Key=InstanceIds,Values=instance-id-1,instance-id-2,instance-id-3 --targets Key=InstanceIds,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE,i-07782c72faEXAMPLE Target instances by using tags --targets Key=tag:tag-key,Values=tag-value-1,tag-value-2,tag-value-3 --targets Key=tag:Environment,Values=Development,Test,Pre-production Target nodes by using AWS Resource Groups --targets Key=resource-groups:Name,Values=resource-group-name --targets Key=resource-groups:Name,Values=WindowsInstancesGroup Target all instances in the current AWS account and AWS Region --targets Key=InstanceIds,Values=* Note Note the following information. • State Manager doesn't support running associations that use a new version of a document if that document is shared from another account. State Manager always runs the default version of a document if shared from another account, even though the Systems Manager console shows that a new version was processed. If you want to run an State Manager 995 AWS Systems Manager User Guide association using a new version of a document shared form another account, you must set the document version to default. • You can specify a maximum of five tag keys by using the AWS CLI. If you use the AWS CLI, all tag keys specified in the create-association command must be currently assigned to the node. If they aren't, State Manager fails to target the node for an association. • When you create an association, you specify when the schedule runs. Specify the schedule by using a cron or rate expression. For more information about cron and rate expressions, see Cron and rate expressions for associations. • In order for associations that are created with Automation runbooks to be applied when new target nodes are detected, certain conditions must be met. For information, see About target updates with Automation runbooks. To create an association 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. Use the following format to create a command that creates a State Manager association. Replace each example resource placeholder with your own information. Linux & macOS aws ssm create-association \ --name document_name \ --document-version version_of_document_applied \ --instance-id instances_to_apply_association_on \ --parameters (if any) \ --targets target_options \ --schedule-expression "cron_or_rate_expression" \ --apply-only-at-cron-interval required_parameter_for_schedule_offsets \ --schedule-offset number_between_1_and_6 \ --output-location s3_bucket_to_store_output_details \ --association-name association_name \ --max-errors a_number_of_errors_or_a_percentage_of_target_set \ --max-concurrency a_number_of_instances_or_a_percentage_of_target_set \ --compliance-severity severity_level \ State Manager 996 AWS Systems Manager User Guide --calendar-names change_calendar_names \ --target-locations aws_region_or_account \ --tags "Key=tag_key,Value=tag_value" Windows aws ssm create-association ^ --name document_name ^ --document-version version_of_document_applied ^ --instance-id instances_to_apply_association_on ^ --parameters (if any) ^ --targets target_options ^ --schedule-expression "cron_or_rate_expression" ^ --apply-only-at-cron-interval required_parameter_for_schedule_offsets ^ --schedule-offset number_between_1_and_6 ^ --output-location s3_bucket_to_store_output_details ^ --association-name association_name ^ --max-errors a_number_of_errors_or_a_percentage_of_target_set ^ --max-concurrency a_number_of_instances_or_a_percentage_of_target_set ^ --compliance-severity severity_level ^ --calendar-names change_calendar_names ^ --target-locations aws_region_or_account ^ --tags "Key=tag_key,Value=tag_value" PowerShell New-SSMAssociation ` -Name document_name ` -DocumentVersion version_of_document_applied ` -InstanceId instances_to_apply_association_on ` -Parameters (if any) ` -Target target_options ` -ScheduleExpression "cron_or_rate_expression" ` -ApplyOnlyAtCronInterval required_parameter_for_schedule_offsets ` -ScheduleOffSet number_between_1_and_6 ` -OutputLocation s3_bucket_to_store_output_details ` -AssociationName association_name ` -MaxError a_number_of_errors_or_a_percentage_of_target_set -MaxConcurrency a_number_of_instances_or_a_percentage_of_target_set ` -ComplianceSeverity severity_level ` -CalendarNames change_calendar_names ` -TargetLocations aws_region_or_account ` State Manager 997 AWS Systems Manager User Guide -Tags "Key=tag_key,Value=tag_value" The following example creates an association on nodes tagged with "Environment,Linux". The association uses the AWS-UpdateSSMAgent document to update the SSM Agent on the targeted nodes at 2:00 UTC every Sunday morning. This association runs simultaneously on 10 nodes maximum at any given time. Also, this association stops running on more nodes for a particular execution interval if the error count exceeds 5. For compliance reporting, this association is assigned a severity level of Medium. Linux & macOS aws ssm create-association
|
systems-manager-ug-313
|
systems-manager-ug.pdf
| 313 |
-ComplianceSeverity severity_level ` -CalendarNames change_calendar_names ` -TargetLocations aws_region_or_account ` State Manager 997 AWS Systems Manager User Guide -Tags "Key=tag_key,Value=tag_value" The following example creates an association on nodes tagged with "Environment,Linux". The association uses the AWS-UpdateSSMAgent document to update the SSM Agent on the targeted nodes at 2:00 UTC every Sunday morning. This association runs simultaneously on 10 nodes maximum at any given time. Also, this association stops running on more nodes for a particular execution interval if the error count exceeds 5. For compliance reporting, this association is assigned a severity level of Medium. Linux & macOS aws ssm create-association \ --association-name Update_SSM_Agent_Linux \ --targets Key=tag:Environment,Values=Linux \ --name AWS-UpdateSSMAgent \ --compliance-severity "MEDIUM" \ --schedule-expression "cron(0 2 ? * SUN *)" \ --max-errors "5" \ --max-concurrency "10" Windows aws ssm create-association ^ --association-name Update_SSM_Agent_Linux ^ --targets Key=tag:Environment,Values=Linux ^ --name AWS-UpdateSSMAgent ^ --compliance-severity "MEDIUM" ^ --schedule-expression "cron(0 2 ? * SUN *)" ^ --max-errors "5" ^ --max-concurrency "10" PowerShell New-SSMAssociation ` -AssociationName Update_SSM_Agent_Linux ` -Name AWS-UpdateSSMAgent ` -Target @{ "Key"="tag:Environment" "Values"="Linux" } ` State Manager 998 AWS Systems Manager User Guide -ComplianceSeverity MEDIUM ` -ScheduleExpression "cron(0 2 ? * SUN *)" ` -MaxConcurrency 10 ` -MaxError 5 The following example targets node IDs by specifying a wildcard value (*). This allows Systems Manager to create an association on all nodes in the current AWS account and AWS Region. This association runs simultaneously on 10 nodes maximum at any given time. Also, this association stops running on more nodes for a particular execution interval if the error count exceeds 5. For compliance reporting, this association is assigned a severity level of Medium. This association uses a schedule offset, which means it runs two days after the specified cron schedule. It also includes the ApplyOnlyAtCronInterval parameter, which is required to use the schedule offset and which means the association won't run immediately after it is created. Linux & macOS aws ssm create-association \ --association-name Update_SSM_Agent_Linux \ --name "AWS-UpdateSSMAgent" \ --targets "Key=instanceids,Values=*" \ --compliance-severity "MEDIUM" \ --schedule-expression "cron(0 2 ? * SUN#2 *)" \ --apply-only-at-cron-interval \ --schedule-offset 2 \ --max-errors "5" \ --max-concurrency "10" \ Windows aws ssm create-association ^ --association-name Update_SSM_Agent_Linux ^ --name "AWS-UpdateSSMAgent" ^ --targets "Key=instanceids,Values=*" ^ --compliance-severity "MEDIUM" ^ --schedule-expression "cron(0 2 ? * SUN#2 *)" ^ --apply-only-at-cron-interval ^ --schedule-offset 2 ^ --max-errors "5" ^ State Manager 999 AWS Systems Manager User Guide --max-concurrency "10" ^ --apply-only-at-cron-interval PowerShell New-SSMAssociation ` -AssociationName Update_SSM_Agent_All ` -Name AWS-UpdateSSMAgent ` -Target @{ "Key"="InstanceIds" "Values"="*" } ` -ScheduleExpression "cron(0 2 ? * SUN#2 *)" ` -ApplyOnlyAtCronInterval ` -ScheduleOffset 2 ` -MaxConcurrency 10 ` -MaxError 5 ` -ComplianceSeverity MEDIUM ` -ApplyOnlyAtCronInterval The following example creates an association on nodes in Resource Groups. The group is named "HR-Department". The association uses the AWS-UpdateSSMAgent document to update SSM Agent on the targeted nodes at 2:00 UTC every Sunday morning. This association runs simultaneously on 10 nodes maximum at any given time. Also, this association stops running on more nodes for a particular execution interval if the error count exceeds 5. For compliance reporting, this association is assigned a severity level of Medium. This association runs at the specified cron schedule. It doesn't run immediately after the association is created. Linux & macOS aws ssm create-association \ --association-name Update_SSM_Agent_Linux \ --targets Key=resource-groups:Name,Values=HR-Department \ --name AWS-UpdateSSMAgent \ --compliance-severity "MEDIUM" \ --schedule-expression "cron(0 2 ? * SUN *)" \ --max-errors "5" \ --max-concurrency "10" \ --apply-only-at-cron-interval State Manager 1000 AWS Systems Manager Windows User Guide aws ssm create-association ^ --association-name Update_SSM_Agent_Linux ^ --targets Key=resource-groups:Name,Values=HR-Department ^ --name AWS-UpdateSSMAgent ^ --compliance-severity "MEDIUM" ^ --schedule-expression "cron(0 2 ? * SUN *)" ^ --max-errors "5" ^ --max-concurrency "10" ^ --apply-only-at-cron-interval PowerShell New-SSMAssociation ` -AssociationName Update_SSM_Agent_Linux ` -Name AWS-UpdateSSMAgent ` -Target @{ "Key"="resource-groups:Name" "Values"="HR-Department" } ` -ScheduleExpression "cron(0 2 ? * SUN *)" ` -MaxConcurrency 10 ` -MaxError 5 ` -ComplianceSeverity MEDIUM ` -ApplyOnlyAtCronInterval The following example creates an association that runs on nodes tagged with a specific node ID. The association uses the SSM Agent document to update SSM Agent on the targeted nodes once when the change calendar is open. The association checks the calendar state when it runs. If the calendar is closed at launch time and the association is only run once, it won't run again because the association run window has passed. If the calendar is open, the association runs accordingly. State Manager 1001 AWS Systems Manager Note User Guide If you add new nodes to the tags or resource groups that an association acts on when the change calendar is closed, the association is applied to those nodes once the change calendar opens. Linux & macOS aws ssm create-association \ --association-name CalendarAssociation \ --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" \ --name AWS-UpdateSSMAgent \ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" \ --schedule-expression "rate(1day)" Windows aws ssm create-association ^ --association-name CalendarAssociation ^ --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" ^ --name AWS-UpdateSSMAgent ^ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" ^ --schedule-expression
|
systems-manager-ug-314
|
systems-manager-ug.pdf
| 314 |
run again because the association run window has passed. If the calendar is open, the association runs accordingly. State Manager 1001 AWS Systems Manager Note User Guide If you add new nodes to the tags or resource groups that an association acts on when the change calendar is closed, the association is applied to those nodes once the change calendar opens. Linux & macOS aws ssm create-association \ --association-name CalendarAssociation \ --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" \ --name AWS-UpdateSSMAgent \ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" \ --schedule-expression "rate(1day)" Windows aws ssm create-association ^ --association-name CalendarAssociation ^ --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" ^ --name AWS-UpdateSSMAgent ^ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" ^ --schedule-expression "rate(1day)" PowerShell New-SSMAssociation ` -AssociationName CalendarAssociation ` -Target @{ "Key"="tag:instanceids" "Values"="i-0cb2b964d3e14fd9f" } ` -Name AWS-UpdateSSMAgent ` -CalendarNames "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" ` -ScheduleExpression "rate(1day)" State Manager 1002 AWS Systems Manager User Guide The following example creates an association that runs on nodes tagged with a specific node ID. The association uses the SSM Agent document to update SSM Agent on the targeted nodes on the targeted nodes at 2:00 AM every Sunday. This association runs only at the specified cron schedule when the change calendar is open. When the association is created, it checks the calendar state. If the calendar is closed, the association isn't applied. When the interval to apply the association starts at 2:00 AM on Sunday, the association checks to see if the calendar is open. If the calendar is open, the association runs accordingly. Note If you add new nodes to the tags or resource groups that an association acts on when the change calendar is closed, the association is applied to those nodes once the change calendar opens. Linux & macOS aws ssm create-association \ --association-name MultiCalendarAssociation \ --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" \ --name AWS-UpdateSSMAgent \ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2" \ --schedule-expression "cron(0 2 ? * SUN *)" Windows aws ssm create-association ^ --association-name MultiCalendarAssociation ^ --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" ^ --name AWS-UpdateSSMAgent ^ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2" ^ --schedule-expression "cron(0 2 ? * SUN *)" PowerShell New-SSMAssociation ` State Manager 1003 AWS Systems Manager User Guide -AssociationName MultiCalendarAssociation ` -Name AWS-UpdateSSMAgent ` -Target @{ "Key"="tag:instanceids" "Values"="i-0cb2b964d3e14fd9f" } ` -CalendarNames "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2" ` -ScheduleExpression "cron(0 2 ? * SUN *)" Note If you delete the association you created, the association no longer runs on any targets of that association. Also, if you specified the apply-only-at-cron-interval parameter, you can reset this option. To do so, specify the no-apply-only-at-cron-interval parameter when you update the association from the command line. This parameter forces the association to run immediately after updating the association and according to the interval specified. Editing and creating a new version of an association You can edit a State Manager association to specify a new name, schedule, severity level, targets, or other values. For associations based on SSM Command-type documents, you can also choose to write the output of the command to an Amazon Simple Storage Service (Amazon S3) bucket. After you edit an association, State Manager creates a new version. You can view different versions after editing, as described in the following procedures. Note In order for associations that are created with Automation runbooks to be applied when new target nodes are detected, certain conditions must be met. For information, see About target updates with Automation runbooks. The following procedures describe how to edit and create a new version of an association using the Systems Manager console, AWS Command Line Interface (AWS CLI), and AWS Tools for PowerShell (Tools for PowerShell). State Manager 1004 AWS Systems Manager Important User Guide State Manager doesn't support running associations that use a new version of a document if that document is shared from another account. State Manager always runs the default version of a document if shared from another account, even though the Systems Manager console shows that a new version was processed. If you want to run an association using a new version of a document shared form another account, you must set the document version to default. Edit an association (console) The following procedure describes how to use the Systems Manager console to edit and create a new version of an association. Note For associations that use SSM Command documents, not Automation runbooks, this procedure requires that you have write access to an existing Amazon S3 bucket. If you haven't used Amazon S3 before, be aware that you will incur charges for using Amazon S3. For information about how to create a bucket, see Create a Bucket. To edit a State Manager association 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose State Manager. 3. Choose an existing association, and then choose Edit. 4. Reconfigure the association to meet your current requirements. For information about association options with Command and Policy documents, see Creating associations. For information about association options with Automation runbooks, see Scheduling automations with
|
systems-manager-ug-315
|
systems-manager-ug.pdf
| 315 |
Amazon S3 bucket. If you haven't used Amazon S3 before, be aware that you will incur charges for using Amazon S3. For information about how to create a bucket, see Create a Bucket. To edit a State Manager association 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose State Manager. 3. Choose an existing association, and then choose Edit. 4. Reconfigure the association to meet your current requirements. For information about association options with Command and Policy documents, see Creating associations. For information about association options with Automation runbooks, see Scheduling automations with State Manager associations. 5. Choose Save Changes. State Manager 1005 AWS Systems Manager User Guide 6. 7. (Optional) To view association information, in the Associations page, choose the name of the association you edited, and then choose the Versions tab. The system lists each version of the association you created and edited. (Optional) To view output for associations based on SSM Command documents, do the following: a. Open the Amazon S3 console at https://console.aws.amazon.com/s3/. b. Choose the name of the Amazon S3 bucket you specified for storing command output, and then choose the folder named with the ID of the node that ran the association. (If you chose to store output in a folder in the bucket, open it first.) c. Drill down several levels, through the awsrunPowerShell folder, to the stdout file. d. Choose Open or Download to view the host name. Edit an association (command line) The following procedure describes how to use the AWS CLI (on Linux or Windows) or AWS Tools for PowerShell to edit and create a new version of an association. To edit a State Manager association 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. Use the following format to create a command to edit and create a new version of an existing State Manager association. Replace each example resource placeholder with your own information. Important When you call update-association, the system drops all optional parameters from the request and overwrites the association with null values for those parameters. This is by design. You must specify all optional parameters in the call, even if you are not changing the parameters. This includes the --name parameter. Before calling this action, we recommend that you call the describe-association operation and make a note of all optional parameters required for your update-association call. State Manager 1006 AWS Systems Manager Linux & macOS User Guide aws ssm update-association \ --name document_name \ --document-version version_of_document_applied \ --instance-id instances_to_apply_association_on \ --parameters (if any) \ --targets target_options \ --schedule-expression "cron_or_rate_expression" \ --schedule-offset "number_between_1_and_6" \ --output-location s3_bucket_to_store_output_details \ --association-name association_name \ --max-errors a_number_of_errors_or_a_percentage_of_target_set \ --max-concurrency a_number_of_instances_or_a_percentage_of_target_set \ --compliance-severity severity_level \ --calendar-names change_calendar_names \ --target-locations aws_region_or_account Windows aws ssm update-association ^ --name document_name ^ --document-version version_of_document_applied ^ --instance-id instances_to_apply_association_on ^ --parameters (if any) ^ --targets target_options ^ --schedule-expression "cron_or_rate_expression" ^ --schedule-offset "number_between_1_and_6" ^ --output-location s3_bucket_to_store_output_details ^ --association-name association_name ^ --max-errors a_number_of_errors_or_a_percentage_of_target_set ^ --max-concurrency a_number_of_instances_or_a_percentage_of_target_set ^ --compliance-severity severity_level ^ --calendar-names change_calendar_names ^ --target-locations aws_region_or_account PowerShell Update-SSMAssociation ` -Name document_name ` -DocumentVersion version_of_document_applied ` State Manager 1007 AWS Systems Manager User Guide -InstanceId instances_to_apply_association_on ` -Parameters (if any) ` -Target target_options ` -ScheduleExpression "cron_or_rate_expression" ` -ScheduleOffset "number_between_1_and_6" ` -OutputLocation s3_bucket_to_store_output_details ` -AssociationName association_name ` -MaxError a_number_of_errors_or_a_percentage_of_target_set -MaxConcurrency a_number_of_instances_or_a_percentage_of_target_set ` -ComplianceSeverity severity_level ` -CalendarNames change_calendar_names ` -TargetLocations aws_region_or_account The following example updates an existing association to change the name to TestHostnameAssociation2. The new association version runs every hour and writes the output of commands to the specified Amazon S3 bucket. Linux & macOS aws ssm update-association \ --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE \ --association-name TestHostnameAssociation2 \ --parameters commands="echo Association" \ --output-location S3Location='{OutputS3Region=us- east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' \ --schedule-expression "cron(0 */1 * * ? *)" Windows aws ssm update-association ^ --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE ^ --association-name TestHostnameAssociation2 ^ --parameters commands="echo Association" ^ --output-location S3Location='{OutputS3Region=us- east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' ^ --schedule-expression "cron(0 */1 * * ? *)" PowerShell Update-SSMAssociation ` -AssociationId b85ccafe-9f02-4812-9b81-01234EXAMPLE ` State Manager 1008 AWS Systems Manager User Guide -AssociationName TestHostnameAssociation2 ` -Parameter @{"commands"="echo Association"} ` -S3Location_OutputS3BucketName amzn-s3-demo-bucket ` -S3Location_OutputS3KeyPrefix logs ` -S3Location_OutputS3Region us-east-1 ` -ScheduleExpression "cron(0 */1 * * ? *)" The following example updates an existing association to change the name to CalendarAssociation. The new association runs when the calendar is open and writes command output to the specified Amazon S3 bucket. Linux & macOS aws ssm update-association \ --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE \ --association-name CalendarAssociation \ --parameters commands="echo Association" \ --output-location S3Location='{OutputS3Region=us- east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' \ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar2" Windows aws ssm update-association ^ --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE ^ --association-name CalendarAssociation ^ --parameters commands="echo Association" ^ --output-location S3Location='{OutputS3Region=us- east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' ^ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar2" PowerShell Update-SSMAssociation ` -AssociationId b85ccafe-9f02-4812-9b81-01234EXAMPLE ` -AssociationName CalendarAssociation ` -AssociationName OneTimeAssociation ` -Parameter @{"commands"="echo Association"} ` -S3Location_OutputS3BucketName amzn-s3-demo-bucket `
|
systems-manager-ug-316
|
systems-manager-ug.pdf
| 316 |
*/1 * * ? *)" The following example updates an existing association to change the name to CalendarAssociation. The new association runs when the calendar is open and writes command output to the specified Amazon S3 bucket. Linux & macOS aws ssm update-association \ --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE \ --association-name CalendarAssociation \ --parameters commands="echo Association" \ --output-location S3Location='{OutputS3Region=us- east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' \ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar2" Windows aws ssm update-association ^ --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE ^ --association-name CalendarAssociation ^ --parameters commands="echo Association" ^ --output-location S3Location='{OutputS3Region=us- east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' ^ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar2" PowerShell Update-SSMAssociation ` -AssociationId b85ccafe-9f02-4812-9b81-01234EXAMPLE ` -AssociationName CalendarAssociation ` -AssociationName OneTimeAssociation ` -Parameter @{"commands"="echo Association"} ` -S3Location_OutputS3BucketName amzn-s3-demo-bucket ` -CalendarNames "arn:aws:ssm:us-east-1:123456789012:document/testCalendar2" State Manager 1009 AWS Systems Manager User Guide The following example updates an existing association to change the name to MultiCalendarAssociation. The new association runs when the calendars are open and writes command output to the specified Amazon S3 bucket. Linux & macOS aws ssm update-association \ --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE \ --association-name MultiCalendarAssociation \ --parameters commands="echo Association" \ --output-location S3Location='{OutputS3Region=us- east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' \ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2" Windows aws ssm update-association ^ --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE ^ --association-name MultiCalendarAssociation ^ --parameters commands="echo Association" ^ --output-location S3Location='{OutputS3Region=us- east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' ^ --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2" PowerShell Update-SSMAssociation ` -AssociationId b85ccafe-9f02-4812-9b81-01234EXAMPLE ` -AssociationName MultiCalendarAssociation ` -Parameter @{"commands"="echo Association"} ` -S3Location_OutputS3BucketName amzn-s3-demo-bucket ` -CalendarNames "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2" 3. To view the new version of the association, run the following command. State Manager 1010 AWS Systems Manager Linux & macOS User Guide aws ssm describe-association \ --association-id b85ccafe-9f02-4812-9b81-01234EXAMPLE Windows aws ssm describe-association ^ --association-id b85ccafe-9f02-4812-9b81-01234EXAMPLE PowerShell Get-SSMAssociation ` -AssociationId b85ccafe-9f02-4812-9b81-01234EXAMPLE | Select-Object * The system returns information like the following. Linux & macOS { "AssociationDescription": { "ScheduleExpression": "cron(0 */1 * * ? *)", "OutputLocation": { "S3Location": { "OutputS3KeyPrefix": "logs", "OutputS3BucketName": "amzn-s3-demo-bucket", "OutputS3Region": "us-east-1" } }, "Name": "AWS-RunPowerShellScript", "Parameters": { "commands": [ "echo Association" ] }, "LastExecutionDate": 1559316400.338, "Overview": { "Status": "Success", "DetailedStatus": "Success", "AssociationStatusAggregatedCount": {} State Manager 1011 AWS Systems Manager }, User Guide "AssociationId": "b85ccafe-9f02-4812-9b81-01234EXAMPLE", "DocumentVersion": "$DEFAULT", "LastSuccessfulExecutionDate": 1559316400.338, "LastUpdateAssociationDate": 1559316389.753, "Date": 1559314038.532, "AssociationVersion": "2", "AssociationName": "TestHostnameAssociation2", "Targets": [ { "Values": [ "Windows" ], "Key": "tag:Environment" } ] } } Windows { "AssociationDescription": { "ScheduleExpression": "cron(0 */1 * * ? *)", "OutputLocation": { "S3Location": { "OutputS3KeyPrefix": "logs", "OutputS3BucketName": "amzn-s3-demo-bucket", "OutputS3Region": "us-east-1" } }, "Name": "AWS-RunPowerShellScript", "Parameters": { "commands": [ "echo Association" ] }, "LastExecutionDate": 1559316400.338, "Overview": { "Status": "Success", "DetailedStatus": "Success", "AssociationStatusAggregatedCount": {} }, State Manager 1012 AWS Systems Manager User Guide "AssociationId": "b85ccafe-9f02-4812-9b81-01234EXAMPLE", "DocumentVersion": "$DEFAULT", "LastSuccessfulExecutionDate": 1559316400.338, "LastUpdateAssociationDate": 1559316389.753, "Date": 1559314038.532, "AssociationVersion": "2", "AssociationName": "TestHostnameAssociation2", "Targets": [ { "Values": [ "Windows" ], "Key": "tag:Environment" } ] } } PowerShell AssociationId : b85ccafe-9f02-4812-9b81-01234EXAMPLE AssociationName : TestHostnameAssociation2 AssociationVersion : 2 AutomationTargetParameterName : ComplianceSeverity : Date : 5/31/2019 2:47:18 PM DocumentVersion : $DEFAULT InstanceId : LastExecutionDate : 5/31/2019 3:26:40 PM LastSuccessfulExecutionDate : 5/31/2019 3:26:40 PM LastUpdateAssociationDate : 5/31/2019 3:26:29 PM MaxConcurrency : MaxErrors : Name : AWS-RunPowerShellScript OutputLocation : Amazon.SimpleSystemsManagement.Model.InstanceAssociationOutputLocation Overview : Amazon.SimpleSystemsManagement.Model.AssociationOverview Parameters : {[commands, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]} ScheduleExpression : cron(0 */1 * * ? *) Status : Targets : {tag:Environment} State Manager 1013 AWS Systems Manager Deleting associations User Guide Use the following procedure to delete an association by using the AWS Systems Manager console. To delete an association 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. 3. In the navigation pane, choose State Manager. Select an association and then choose Delete. You can delete multiple associations in a single operation by running an automation from the AWS Systems Manager console. When you select multiple associations for deletion, State Manager launches the automation runbook start page with the association IDs entered as input parameter values. To delete multiple associations in a single operation 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- 2. 3. 4. manager/. In the navigation pane, choose State Manager. Select each association that you want to delete and then choose Delete. (Optional) In the Additional input parameters area, select the Amazon Resource Name (ARN) for the assume role that you want the automation to use while running. To create a new assume role, choose Create. 5. Choose Submit. Running Auto Scaling groups with associations The best practice when using associations to run Auto Scaling groups is to use tag targets. Not using tags might cause you to reach the association limit. If all nodes are tagged with the same key and value, you only need one association to run your Auto Scaling group. The following procedure describes how to create such an association. State Manager 1014 AWS Systems Manager User Guide To create an association that runs Auto Scaling groups 1. Ensure all nodes in the Auto Scaling group are tagged with the same key and value. For more instructions on tagging nodes, see Tagging Auto Scaling groups and instances in the AWS Auto Scaling User Guide. 2. Create an association by using the procedure in Working with associations in Systems Manager. If you're working
|
systems-manager-ug-317
|
systems-manager-ug.pdf
| 317 |
tagged with the same key and value, you only need one association to run your Auto Scaling group. The following procedure describes how to create such an association. State Manager 1014 AWS Systems Manager User Guide To create an association that runs Auto Scaling groups 1. Ensure all nodes in the Auto Scaling group are tagged with the same key and value. For more instructions on tagging nodes, see Tagging Auto Scaling groups and instances in the AWS Auto Scaling User Guide. 2. Create an association by using the procedure in Working with associations in Systems Manager. If you're working in the console, choose Specify instance tags in the Targets field. For Instance tags, enter the Tag key and value for your Auto Scaling group. If you're using the AWS Command Line Interface (AWS CLI), specify --targets Key=tag:tag-key,Values=tag-value where the key and value match what you tagged your nodes with. Viewing association histories You can view all executions for a specific association ID by using the DescribeAssociationExecutions API operation. Use this operation to see the status, detailed status, results, last execution time, and more information for a State Manager association. State Manager is a tool in AWS Systems Manager. This API operation also includes filters to help you locate associations according to the criteria you specify. For example, you can specify an exact date and time, and use a GREATER_THAN filter to view executions processed after the specified date and time. If, for example, an association execution failed, you can drill down into the details of a specific execution by using the DescribeAssociationExecutionTargets API operation. This operation shows you the resources, such as node IDs, where the association ran and the various association statuses. You can then see which resource or node failed to run an association. With the resource ID you can then view the command execution details to see which step in a command failed. The examples in this section also include information about how to use the StartAssociationsOnce API operation to run an association once at the time of creation. You can use this API operation when you investigate failed association executions. If you see that an association failed, you can make a change on the resource, and then immediately run the association to see if the change on the resource allows the association to run successfully. State Manager 1015 AWS Systems Manager Note User Guide API operations that are initiated by the SSM document during an association run are not logged in AWS CloudTrail. Viewing association histories (console) Use the following procedure to view the execution history for a specific association ID and then view execution details for one or more resources. To view execution history for a specific association ID 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. Choose State Manager. 3. In the Association id field, choose an association for which you want to view the history. 4. Choose the View details button. 5. Choose the Execution history tab. 6. Choose an association for which you want to view resource-level execution details. For example, choose an association that shows a status of Failed. You can then view the execution details for the nodes that failed to run the association. Use the search box filters to locate the execution for which you want to view details. 7. Choose an execution ID. The Association execution targets page opens. This page shows all the resources that ran the association. 8. Choose a resource ID to view specific information about that resource. Use the search box filters to locate the resource for which you want to view details. State Manager 1016 AWS Systems Manager User Guide 9. If you're investigating an association that failed to run, you can use the Apply association now button to run an association once at the time of creation. After you made changes on the resource where the association failed to run, choose the Association ID link in the navigation breadcrumb. 10. Choose the Apply association now button. After the execution is complete, verify that the association execution succeeded. Viewing association histories (command line) The following procedure describes how to use the AWS Command Line Interface (AWS CLI) (on Linux or Windows) or AWS Tools for PowerShell to view the execution history for a specific association ID. Following this, the procedure describes how to view execution details for one or more resources. To view execution history for a specific association ID 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. Run the following command to view a list of executions for a specific association ID. Linux & macOS aws ssm describe-association-executions
|
systems-manager-ug-318
|
systems-manager-ug.pdf
| 318 |
or Windows) or AWS Tools for PowerShell to view the execution history for a specific association ID. Following this, the procedure describes how to view execution details for one or more resources. To view execution history for a specific association ID 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. Run the following command to view a list of executions for a specific association ID. Linux & macOS aws ssm describe-association-executions \ --association-id ID \ --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN Note This command includes a filter to limit the results to only those executions that occurred after a specific date and time. If you want to view all executions for a specific association ID, remove the --filters parameter and Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN value. State Manager 1017 AWS Systems Manager Windows User Guide aws ssm describe-association-executions ^ --association-id ID ^ --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN Note This command includes a filter to limit the results to only those executions that occurred after a specific date and time. If you want to view all executions for a specific association ID, remove the --filters parameter and Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN value. PowerShell Get-SSMAssociationExecution ` -AssociationId ID ` -Filter @{"Key"="CreatedTime";"Value"="2019-06-01T19:15:38.372Z";"Type"="GREATER_THAN"} Note This command includes a filter to limit the results to only those executions that occurred after a specific date and time. If you want to view all executions for a specific association ID, remove the -Filter parameter and @{"Key"="CreatedTime";"Value"="2019-06-01T19:15:38.372Z";"Type"="GREATER_THAN"} value. The system returns information like the following. Linux & macOS { "AssociationExecutions":[ State Manager 1018 AWS Systems Manager { User Guide "Status":"Success", "DetailedStatus":"Success", "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE", "ExecutionId":"76a5a04f-caf6-490c-b448-92c02EXAMPLE", "CreatedTime":1523986028.219, "AssociationVersion":"1" }, { "Status":"Success", "DetailedStatus":"Success", "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE", "ExecutionId":"791b72e0-f0da-4021-8b35-f95dfEXAMPLE", "CreatedTime":1523984226.074, "AssociationVersion":"1" }, { "Status":"Success", "DetailedStatus":"Success", "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE", "ExecutionId":"ecec60fa-6bb0-4d26-98c7-140308EXAMPLE", "CreatedTime":1523982404.013, "AssociationVersion":"1" } ] } Windows { "AssociationExecutions":[ { "Status":"Success", "DetailedStatus":"Success", "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE", "ExecutionId":"76a5a04f-caf6-490c-b448-92c02EXAMPLE", "CreatedTime":1523986028.219, "AssociationVersion":"1" }, { "Status":"Success", "DetailedStatus":"Success", "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE", State Manager 1019 AWS Systems Manager User Guide "ExecutionId":"791b72e0-f0da-4021-8b35-f95dfEXAMPLE", "CreatedTime":1523984226.074, "AssociationVersion":"1" }, { "Status":"Success", "DetailedStatus":"Success", "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE", "ExecutionId":"ecec60fa-6bb0-4d26-98c7-140308EXAMPLE", "CreatedTime":1523982404.013, "AssociationVersion":"1" } ] } PowerShell AssociationId : c336d2ab-09de-44ba-8f6a-6136cEXAMPLE AssociationVersion : 1 CreatedTime : 8/18/2019 2:00:50 AM DetailedStatus : Success ExecutionId : 76a5a04f-caf6-490c-b448-92c02EXAMPLE LastExecutionDate : 1/1/0001 12:00:00 AM ResourceCountByStatus : {Success=1} Status : Success AssociationId : c336d2ab-09de-44ba-8f6a-6136cEXAMPLE AssociationVersion : 1 CreatedTime : 8/11/2019 2:00:54 AM DetailedStatus : Success ExecutionId : 791b72e0-f0da-4021-8b35-f95dfEXAMPLE LastExecutionDate : 1/1/0001 12:00:00 AM ResourceCountByStatus : {Success=1} Status : Success AssociationId : c336d2ab-09de-44ba-8f6a-6136cEXAMPLE AssociationVersion : 1 CreatedTime : 8/4/2019 2:01:00 AM DetailedStatus : Success ExecutionId : ecec60fa-6bb0-4d26-98c7-140308EXAMPLE LastExecutionDate : 1/1/0001 12:00:00 AM ResourceCountByStatus : {Success=1} Status : Success State Manager 1020 AWS Systems Manager User Guide You can limit the results by using one or more filters. The following example returns all associations that were run before a specific date and time. Linux & macOS aws ssm describe-association-executions \ --association-id ID \ --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=LESS_THAN Windows aws ssm describe-association-executions ^ --association-id ID ^ --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=LESS_THAN PowerShell Get-SSMAssociationExecution ` -AssociationId 14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE ` -Filter @{"Key"="CreatedTime";"Value"="2019-06-01T19:15:38.372Z";"Type"="LESS_THAN"} The following returns all associations that were successfully run after a specific date and time. Linux & macOS aws ssm describe-association-executions \ --association-id ID \ --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN Key=Status,Value=Success,Type=EQUAL Windows aws ssm describe-association-executions ^ --association-id ID ^ --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN Key=Status,Value=Success,Type=EQUAL State Manager 1021 AWS Systems Manager PowerShell User Guide Get-SSMAssociationExecution ` -AssociationId 14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE ` -Filter @{ "Key"="CreatedTime"; "Value"="2019-06-01T19:15:38.372Z"; "Type"="GREATER_THAN" }, @{ "Key"="Status"; "Value"="Success"; "Type"="EQUAL" } 3. Run the following command to view all targets where the specific execution ran. Linux & macOS aws ssm describe-association-execution-targets \ --association-id ID \ --execution-id ID Windows aws ssm describe-association-execution-targets ^ --association-id ID ^ --execution-id ID PowerShell Get-SSMAssociationExecutionTarget ` -AssociationId 14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE ` -ExecutionId 76a5a04f-caf6-490c-b448-92c02EXAMPLE You can limit the results by using one or more filters. The following example returns information about all targets where the specific association failed to run. State Manager 1022 AWS Systems Manager Linux & macOS User Guide aws ssm describe-association-execution-targets \ --association-id ID \ --execution-id ID \ --filters Key=Status,Value="Failed" Windows aws ssm describe-association-execution-targets ^ --association-id ID ^ --execution-id ID ^ --filters Key=Status,Value="Failed" PowerShell Get-SSMAssociationExecutionTarget ` -AssociationId 14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE ` -ExecutionId 76a5a04f-caf6-490c-b448-92c02EXAMPLE ` -Filter @{ "Key"="Status"; "Value"="Failed" } The following example returns information about a specific managed node where an association failed to run. Linux & macOS aws ssm describe-association-execution-targets \ --association-id ID \ --execution-id ID \ --filters Key=Status,Value=Failed Key=ResourceId,Value="i-02573cafcfEXAMPLE" Key=ResourceType,Value=ManagedInstance Windows aws ssm describe-association-execution-targets ^ --association-id ID ^ State Manager 1023 AWS Systems Manager User Guide --execution-id ID ^ --filters Key=Status,Value=Failed Key=ResourceId,Value="i-02573cafcfEXAMPLE" Key=ResourceType,Value=ManagedInstance PowerShell Get-SSMAssociationExecutionTarget ` -AssociationId 14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE ` -ExecutionId 76a5a04f-caf6-490c-b448-92c02EXAMPLE ` -Filter @{ "Key"="Status"; "Value"="Success" }, @{ "Key"="ResourceId"; "Value"="i-02573cafcfEXAMPLE" }, @{ "Key"="ResourceType"; "Value"="ManagedInstance" } 4. If you're investigating an association that failed to run, you can use the StartAssociationsOnce API operation to run an association immediately and only one time. After you change the resource where the association failed to run, run the following command to run the association immediately and only one time. Linux
|
systems-manager-ug-319
|
systems-manager-ug.pdf
| 319 |
--filters Key=Status,Value=Failed Key=ResourceId,Value="i-02573cafcfEXAMPLE" Key=ResourceType,Value=ManagedInstance Windows aws ssm describe-association-execution-targets ^ --association-id ID ^ State Manager 1023 AWS Systems Manager User Guide --execution-id ID ^ --filters Key=Status,Value=Failed Key=ResourceId,Value="i-02573cafcfEXAMPLE" Key=ResourceType,Value=ManagedInstance PowerShell Get-SSMAssociationExecutionTarget ` -AssociationId 14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE ` -ExecutionId 76a5a04f-caf6-490c-b448-92c02EXAMPLE ` -Filter @{ "Key"="Status"; "Value"="Success" }, @{ "Key"="ResourceId"; "Value"="i-02573cafcfEXAMPLE" }, @{ "Key"="ResourceType"; "Value"="ManagedInstance" } 4. If you're investigating an association that failed to run, you can use the StartAssociationsOnce API operation to run an association immediately and only one time. After you change the resource where the association failed to run, run the following command to run the association immediately and only one time. Linux & macOS aws ssm start-associations-once \ --association-id ID Windows aws ssm start-associations-once ^ --association-id ID PowerShell Start-SSMAssociationsOnce ` -AssociationId ID State Manager 1024 AWS Systems Manager User Guide Working with associations using IAM State Manager, a tool in AWS Systems Manager, uses targets to choose which instances you configure your associations with. Originally, associations were created by specifying a document name (Name) and instance ID (InstanceId). This created an association between a document and an instance or managed node. Associations used to be identified by these parameters. These parameters are now deprecated, but they're still supported. The resources instance and managed-instance were added as resources to actions with Name and InstanceId. AWS Identity and Access Management (IAM) policy enforcement behavior depends on the type of resource specified. Resources for State Manager operations are only enforced based on the passed- in request. State Manager doesn't perform a deep check for the properties of resources in your account. A request is only validated against policy resources if the request parameter contains the specified policy resources. For example, if you specify an instance in the resource block, the policy is enforced if the request uses the InstanceId parameter. The Targets parameter for each resource in the account isn't checked for that InstanceId. Following are some cases with confusing behavior: • DescribeAssociation, DeleteAssociation, and UpdateAssociation use instance, managed- instance, and document resources to specify the deprecated way of referring to associations. This includes all associations created with the deprecated InstanceId parameter. • CreateAssociation, CreateAssociationBatch, and UpdateAssociation use instance and managed-instance resources to specify the deprecated way of referring to associations. This includes all associations created with the deprecated InstanceId parameter. The document resource type is part of the deprecated way of referring to associations and is an actual property of an association. This means you can construct IAM policies with Allow or Deny permissions for both Create and Update actions based on document name. For more information about using IAM policies with Systems Manager, see Identity and access management for AWS Systems Manager or Actions, resources, and condition keys for AWS Systems Manager in the Service Authorization Reference. Creating associations that run MOF files You can run Managed Object Format (MOF) files to enforce a desired state on Windows Server managed nodes with State Manager, a tool in AWS Systems Manager, by using the AWS- ApplyDSCMofs SSM document. The AWS-ApplyDSCMofs document has two execution modes. State Manager 1025 AWS Systems Manager User Guide With the first mode, you can configure the association to scan and report if the managed nodes are in the desired state defined in the specified MOF files. In the second mode, you can run the MOF files and change the configuration of your nodes based on the resources and their values defined in the MOF files. The AWS-ApplyDSCMofs document allows you to download and run MOF configuration files from Amazon Simple Storage Service (Amazon S3), a local share, or from a secure website with an HTTPS domain. State Manager logs and reports the status of each MOF file execution during each association run. State Manager also reports the output of each MOF file execution as a compliance event which you can view on the AWS Systems Manager Compliance page. MOF file execution is built on Windows PowerShell Desired State Configuration (PowerShell DSC). PowerShell DSC is a declarative platform used for configuration, deployment, and management of Windows systems. PowerShell DSC allows administrators to describe, in simple text documents called DSC configurations, how they want a server to be configured. A PowerShell DSC configuration is a specialized PowerShell script that states what to do, but not how to do it. Running the configuration produces a MOF file. The MOF file can be applied to one or more servers to achieve the desired configuration for those servers. PowerShell DSC resources do the actual work of enforcing configuration. For more information, see Windows PowerShell Desired State Configuration Overview. Topics • Using Amazon S3 to store artifacts • Resolving credentials in MOF files • Using tokens in MOF files • Prerequisites for creating associations that run MOF files • Creating an association that runs MOF files • Troubleshooting issues when creating associations that run MOF
|
systems-manager-ug-320
|
systems-manager-ug.pdf
| 320 |
to do, but not how to do it. Running the configuration produces a MOF file. The MOF file can be applied to one or more servers to achieve the desired configuration for those servers. PowerShell DSC resources do the actual work of enforcing configuration. For more information, see Windows PowerShell Desired State Configuration Overview. Topics • Using Amazon S3 to store artifacts • Resolving credentials in MOF files • Using tokens in MOF files • Prerequisites for creating associations that run MOF files • Creating an association that runs MOF files • Troubleshooting issues when creating associations that run MOF files • Viewing DSC resource compliance details Using Amazon S3 to store artifacts If you're using Amazon S3 to store PowerShell modules, MOF files, compliance reports, or status reports, then the AWS Identity and Access Management (IAM) role used by AWS Systems Manager SSM Agent must have GetObject and ListBucket permissions on the bucket. If you State Manager 1026 AWS Systems Manager User Guide don't provide these permissions, the system returns an Access Denied error. Below is important information about storing artifacts in Amazon S3. • If the bucket is in a different AWS account, create a bucket resource policy that grants the account (or the IAM role) GetObject and ListBucket permissions. • If you want to use custom DSC resources, you can download these resources from an Amazon S3 bucket. You can also install them automatically from the PowerShell gallery. • If you're using Amazon S3 as a module source, upload the module as a Zip file in the following case-sensitive format: ModuleName_ModuleVersion.zip. For example: MyModule_1.0.0.zip. • All files must be in the bucket root. Folder structures aren't supported. Resolving credentials in MOF files Credentials are resolved by using AWS Secrets Manager or AWS Systems Manager Parameter Store. This allows you to set up automatic credential rotation. This also allows DSC to automatically propagate credentials to your servers without redeploying MOFs. To use an AWS Secrets Manager secret in a configuration, create a PSCredential object where the Username is the SecretId or SecretARN of the secret containing the credential. You can specify any value for the password. The value is ignored. Following is an example. Configuration MyConfig { $ss = ConvertTo-SecureString -String 'a_string' -AsPlaintext -Force $credential = New-Object PSCredential('a_secret_or_ARN', $ss) Node localhost { File file_name { DestinationPath = 'C:\MyFile.txt' SourcePath = '\\FileServer\Share\MyFile.txt' Credential = $credential } } } Compile your MOF using the PsAllowPlaintextPassword setting in configuration data. This is OK because the credential only contains a label. State Manager 1027 AWS Systems Manager User Guide In Secrets Manager, ensure that the node has GetSecretValue access in an IAM Managed Policy, and optionally in the Secret Resource Policy if one exists. To work with DSC, the secret must be in the following format. { 'Username': 'a_name', 'Password': 'a_password' } The secret can have other properties (for example, properties used for rotation), but it must at least have the username and password properties. We recommended that you use a multi-user rotation method, where you have two different usernames and passwords, and the rotation AWS Lambda function flips between them. This method allows you to have multiple active accounts while eliminating the risk of locking out a user during rotation. Using tokens in MOF files Tokens give you the ability to modify resource property values after the MOF has been compiled. This allows you to reuse common MOF files on multiple servers that require similar configurations. Token substitution only works for Resource Properties of type String. However, if your resource has a nested CIM node property, it also resolves tokens from String properties in that CIM node. You can't use token substitution for numerals or arrays. For example, consider a scenario where you're using the xComputerManagement resource and you want to rename the computer using DSC. Normally you would need a dedicated MOF file for that machine. However, with token support, you can create a single MOF file and apply it to all your nodes. In the ComputerName property, instead of hardcoding the computer name into the MOF, you can use an Instance Tag type token. The value is resolved during MOF parsing. See the following example. Configuration MyConfig { xComputer Computer { ComputerName = '{tag:ComputerName}' } } State Manager 1028 AWS Systems Manager User Guide You then set a tag on either the managed node in the Systems Manager console, or an Amazon Elastic Compute Cloud (Amazon EC2) tag in the Amazon EC2 console. When you run the document, the script substitutes the {tag:ComputerName} token for the value of the instance tag. You can also combine multiple tags into a single property, as shown in the following example. Configuration MyConfig { File MyFile { DestinationPath = '{env:TMP}\{tag:ComputerName}' Type = 'Directory' } } There are five different types of tokens you
|
systems-manager-ug-321
|
systems-manager-ug.pdf
| 321 |
Computer { ComputerName = '{tag:ComputerName}' } } State Manager 1028 AWS Systems Manager User Guide You then set a tag on either the managed node in the Systems Manager console, or an Amazon Elastic Compute Cloud (Amazon EC2) tag in the Amazon EC2 console. When you run the document, the script substitutes the {tag:ComputerName} token for the value of the instance tag. You can also combine multiple tags into a single property, as shown in the following example. Configuration MyConfig { File MyFile { DestinationPath = '{env:TMP}\{tag:ComputerName}' Type = 'Directory' } } There are five different types of tokens you can use: • tag: Amazon EC2 or managed node tags. • tagb64: This is the same as tag, but the system use base64 to decode the value. This allows you to use special characters in tag values. • env: Resolves Environment variables. • ssm: Parameter Store values. Only String and Secure String types are supported. • tagssm: This is the same as tag, but if the tag isn't set on the node, the system tries to resolve the value from a Systems Manager parameter with the same name. This is useful in situations when you want a 'default global value' but you want to be able to override it on a single node (for example, one-box deployments). Here is a Parameter Store example that uses the ssm token type. File MyFile { DestinationPath = "C:\ProgramData\ConnectionData.txt" Content = "{ssm:%servicePath%/ConnectionData}" } Tokens play an important role in reducing redundant code by making MOF files generic and reusable. If you can avoid server-specific MOF file, then there’s no need for a MOF building service. A MOF building service increases costs, slows provisioning time, and increases the risk of State Manager 1029 AWS Systems Manager User Guide configuration drift between grouped nodes due to differing module versions being installed on the build server when their MOFs were compiled. Prerequisites for creating associations that run MOF files Before you create an association that runs MOF files, verify that your managed nodes have the following prerequisites installed: • Windows PowerShell version 5.0 or later. For more information, see Windows PowerShell System Requirements on Microsoft.com. • AWS Tools for Windows PowerShell version 3.3.261.0 or later. • SSM Agent version 2.2 or later. Creating an association that runs MOF files To create an association that runs MOF files 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose State Manager. 3. Choose State Manager, and then choose Create association. 4. 5. 6. In the Name field, specify a name. This is optional, but recommended. A name can help you understand the purpose of the association when you created it. Spaces aren't allowed in the name. In the Document list, choose AWS-ApplyDSCMofs. In the Parameters section, specify your choices for the required and optional input parameters. a. Mofs To Apply: Specify one or more MOF files to run when this association runs. Use commas to separate a list of MOF files. You can specify the following options for locating MOF file. • An Amazon S3 bucket name. Bucket names must use lowercase letters. Specify this information by using the following format. s3:amzn-s3-demo-bucket:MOF_file_name.mof State Manager 1030 AWS Systems Manager User Guide If you want to specify an AWS Region, then use the following format. s3:bucket_Region:amzn-s3-demo-bucket:MOF_file_name.mof • A secure website. Specify this information by using the following format. https://domain_name/MOF_file_name.mof Here is an example. https://www.example.com/TestMOF.mof • A file system on a local share. Specify this information by using the following format. \server_name\shared_folder_name\MOF_file_name.mof Here is an example. \StateManagerAssociationsBox\MOFs_folder\MyMof.mof b. Service Path: (Optional) A service path is either an Amazon S3 bucket prefix where you want to write reports and status information. Or, a service path is a path for Parameter Store parameter-based tags. When resolving parameter-based tags, the system uses {ssm: %servicePath%/parameter_name} to inject the servicePath value into the parameter name. For example, if your service path is "WebServers/Production" then the systems resolves the parameter as: WebServers/Production/parameter_name. This is useful for when you're running multiple environments in the same account. c. Report Bucket Name: (Optional) Enter the name of an Amazon S3 bucket where you want to write compliance data. Reports are saved in this bucket in JSON format. Note You can prefix the bucket name with a Region where the bucket is located. Here's an example: us-west-2:MyMOFBucket. If you're using a proxy for Amazon S3 endpoints in a specific Region that doesn't include us-east-1, prefix the bucket name with a Region. If the bucket name isn't prefixed, it automatically discovers the bucket Region by using the us-east-1 endpoint. State Manager 1031 AWS Systems Manager User Guide d. Mof Operation Mode: Choose State Manager behavior when running the AWS- ApplyDSCMofs association: • Apply: Correct node configurations that aren't compliant. • ReportOnly: Don't correct node configurations, but instead
|
systems-manager-ug-322
|
systems-manager-ug.pdf
| 322 |
JSON format. Note You can prefix the bucket name with a Region where the bucket is located. Here's an example: us-west-2:MyMOFBucket. If you're using a proxy for Amazon S3 endpoints in a specific Region that doesn't include us-east-1, prefix the bucket name with a Region. If the bucket name isn't prefixed, it automatically discovers the bucket Region by using the us-east-1 endpoint. State Manager 1031 AWS Systems Manager User Guide d. Mof Operation Mode: Choose State Manager behavior when running the AWS- ApplyDSCMofs association: • Apply: Correct node configurations that aren't compliant. • ReportOnly: Don't correct node configurations, but instead log all compliance data and report nodes that aren't compliant. e. Status Bucket Name: (Optional) Enter the name of an Amazon S3 bucket where you want to write MOF execution status information. These status reports are singleton summaries of the most recent compliance run of a node. This means that the report is overwritten the next time the association runs MOF files. Note You can prefix the bucket name with a Region where the bucket is located. Here's an example: us-west-2:amzn-s3-demo-bucket. If you're using a proxy for Amazon S3 endpoints in a specific Region that doesn't include us-east-1, prefix the bucket name with a Region. If the bucket name isn't prefixed, it automatically discovers the bucket Region using the us-east-1 endpoint. f. Module Source Bucket Name: (Optional) Enter the name of an Amazon S3 bucket that contains PowerShell module files. If you specify None, choose True for the next option, Allow PS Gallery Module Source. Note You can prefix the bucket name with a Region where the bucket is located. Here's an example: us-west-2:amzn-s3-demo-bucket. If you're using a proxy for Amazon S3 endpoints in a specific Region that doesn't include us-east-1, prefix the bucket name with a Region. If the bucket name isn't prefixed, it automatically discovers the bucket Region using the us-east-1 endpoint. g. Allow PS Gallery Module Source: (Optional) Choose True to download PowerShell modules from https://www.powershellgallery.com/. If you choose False, specify a source for the previous option, ModuleSourceBucketName. h. Proxy Uri: (Optional) Use this option to download MOF files from a proxy server. i. Reboot Behavior: (Optional) Specify one of the following reboot behaviors if your MOF file execution requires rebooting: State Manager 1032 AWS Systems Manager User Guide • AfterMof: Reboots the node after all MOF executions are complete. Even if multiple MOF executions request reboots, the system waits until all MOF executions are complete to reboot. • Immediately: Reboots the node whenever a MOF execution requests it. If running multiple MOF files that request reboots, then the nodes are rebooted multiple times. • Never: Nodes aren't rebooted, even if the MOF execution explicitly requests a reboot. j. k. Use Computer Name For Reporting: (Optional) Turn on this option to use the name of the computer when reporting compliance information. The default value is false, which means that the system uses the node ID when reporting compliance information. Turn on Verbose Logging: (Optional) We recommend that you turn on verbose logging when deploying MOF files for the first time. Important When allowed, verbose logging writes more data to your Amazon S3 bucket than standard association execution logging. This might result in slower performance and higher storage charges for Amazon S3. To mitigate storage size issues, we recommend that you turn on lifecycle policies on your Amazon S3 bucket. For more information, see How Do I Create a Lifecycle Policy for an S3 Bucket? in the Amazon Simple Storage Service User Guide. l. Turn on Debug Logging: (Optional) We recommend that you turn on debug logging to troubleshoot MOF failures. We also recommend that you deactivate this option for normal use. Important When allowed, debug logging writes more data to your Amazon S3 bucket than standard association execution logging. This might result in slower performance and higher storage charges for Amazon S3. To mitigate storage size issues, we recommend that you turn on lifecycle policies on your Amazon S3 bucket. For more information, see How Do I Create a Lifecycle Policy for an S3 Bucket? in the Amazon Simple Storage Service User Guide. m. Compliance Type: (Optional) Specify the compliance type to use when reporting compliance information. The default compliance type is Custom:DSC. If you create State Manager 1033 AWS Systems Manager User Guide multiple associations that run MOF files, then be sure to specify a different compliance type for each association. If you don't, each additional association that uses Custom:DSC overwrites the existing compliance data. n. Pre Reboot Script: (Optional) Specify a script to run if the configuration has indicated that a reboot is necessary. The script runs before the reboot. The script must be a single line. Separate additional lines by using semicolons. 7. In the Targets section, choose either Specifying tags or Manually Selecting
|
systems-manager-ug-323
|
systems-manager-ug.pdf
| 323 |
The default compliance type is Custom:DSC. If you create State Manager 1033 AWS Systems Manager User Guide multiple associations that run MOF files, then be sure to specify a different compliance type for each association. If you don't, each additional association that uses Custom:DSC overwrites the existing compliance data. n. Pre Reboot Script: (Optional) Specify a script to run if the configuration has indicated that a reboot is necessary. The script runs before the reboot. The script must be a single line. Separate additional lines by using semicolons. 7. In the Targets section, choose either Specifying tags or Manually Selecting Instance. If you choose to target resources by using tags, then enter a tag key and a tag value in the fields provided. For more information about using targets, see Understanding targets and rate controls in State Manager associations. 8. In the Specify schedule section, choose either On Schedule or No schedule. If you choose On Schedule, then use the buttons provided to create a cron or rate schedule for the association. 9. In the Advanced options section: • In Compliance severity, choose a severity level for the association. Compliance reporting indicates whether the association state is compliant or noncompliant, along with the severity level you indicate here. For more information, see About State Manager association compliance. 10. In the Rate control section, configure options for running State Manager associations across of fleet of managed nodes. For more information about these options, see Understanding targets and rate controls in State Manager associations. In the Concurrency section, choose an option: • Choose targets to enter an absolute number of targets that can run the association simultaneously. • Choose percentage to enter a percentage of the target set that can run the association simultaneously. In the Error threshold section, choose an option: • Choose errors to enter an absolute number of errors allowed before State Manager stops running associations on additional targets. • Choose percentage to enter a percentage of errors allowed before State Manager stops running associations on additional targets. State Manager 1034 AWS Systems Manager User Guide 11. (Optional) For Output options, to save the command output to a file, select the Enable writing output to S3 box. Enter the bucket and prefix (folder) names in the boxes. Note The S3 permissions that grant the ability to write the data to an S3 bucket are those of the instance profile assigned to the managed node, not those of the IAM user performing this task. For more information, see Configure instance permissions required for Systems Manager or Create an IAM service role for a hybrid environment. In addition, if the specified S3 bucket is in a different AWS account, verify that the instance profile or IAM service role associated with the managed node has the necessary permissions to write to that bucket. 12. Choose Create Association. State Manager creates and immediately runs the association on the specified nodes or targets. After the initial execution, the association runs in intervals according to the schedule that you defined and according to the following rules: • State Manager runs associations on nodes that are online when the interval starts and skips offline nodes. • State Manager attempts to run the association on all configured nodes during an interval. • If an association isn't run during an interval (because, for example, a concurrency value limited the number of nodes that could process the association at one time), then State Manager attempts to run the association during the next interval. • State Manager records history for all skipped intervals. You can view the history on the Execution History tab. Note The AWS-ApplyDSCMofs is a Systems Manager Command document. This means that you can also run this document by using Run Command, a tool in AWS Systems Manager. For more information, see AWS Systems Manager Run Command. State Manager 1035 AWS Systems Manager User Guide Troubleshooting issues when creating associations that run MOF files This section includes information to help you troubleshoot issues creating associations that run MOF files. Turn on enhanced logging As a first step to troubleshooting, turn on enhanced logging. More specifically, do the following: 1. Verify that the association is configured to write command output to either Amazon S3 or Amazon CloudWatch Logs (CloudWatch). 2. 3. Set the Enable Verbose Logging parameter to True. Set the Enable Debug Logging parameter to True. With verbose and debug logging turned on, the Stdout output file includes details about the script execution. This output file can help you identify where the script failed. The Stderr output file contains errors that occurred during the script execution. Common problems when creating associations that run MOF files This section includes information about common problems that can occur when creating associations that run MOF files and steps to troubleshoot these
|
systems-manager-ug-324
|
systems-manager-ug.pdf
| 324 |
command output to either Amazon S3 or Amazon CloudWatch Logs (CloudWatch). 2. 3. Set the Enable Verbose Logging parameter to True. Set the Enable Debug Logging parameter to True. With verbose and debug logging turned on, the Stdout output file includes details about the script execution. This output file can help you identify where the script failed. The Stderr output file contains errors that occurred during the script execution. Common problems when creating associations that run MOF files This section includes information about common problems that can occur when creating associations that run MOF files and steps to troubleshoot these issues. My MOF wasn't applied If State Manager failed to apply the association to your nodes, then start by reviewing the Stderr output file. This file can help you understand the root cause of the issue. Also, verify the following: • The node has the required access permissions to all MOF-related Amazon S3 buckets. Specifically: • s3:GetObject permissions: This is required for MOF files in private Amazon S3 buckets and custom modules in Amazon S3 buckets. • s3:PutObject permission: This is required to write compliance reports and compliance status to Amazon S3 buckets. • If you're using tags, then ensure that the node has the required IAM policy. Using tags requires the instance IAM role to have a policy allowing the ec2:DescribeInstances and ssm:ListTagsForResource actions. • Ensure that the node has the expected tags or SSM parameters assigned. • Ensure that the tags or SSM parameters aren't misspelled. State Manager 1036 AWS Systems Manager User Guide • Try applying the MOF locally on the node to make sure there isn't an issue with the MOF file itself. My MOF seemed to fail, but the Systems Manager execution was successful If the AWS-ApplyDSCMofs document successfully ran, then the Systems Manager execution status shows Success. This status doesn't reflect the compliance status of your node against the configuration requirements in the MOF file. To view the compliance status of your nodes, view the compliance reports. You can view a JSON report in the Amazon S3 Report Bucket. This applies to Run Command and State Manager executions. Also, for State Manager, you can view compliance details on the Systems Manager Compliance page. Stderr states: Name resolution failure attempting to reach service This error indicates that the script can't reach a remote service. Most likely, the script can't reach Amazon S3. This issue most often occurs when the script attempts to write compliance reports or compliance status to the Amazon S3 bucket supplied in the document parameters. Typically, this error occurs when a computing environment uses a firewall or transparent proxy that includes an allow list. To resolve this issue: • Use Region-specific bucket syntax for all Amazon S3 bucket parameters. For example, the Mofs to Apply parameter should be formatted as follows: s3:bucket-region:amzn-s3-demo-bucket:mof-file-name.mof. Here is an example: s3:us-west-2:amzn-s3-demo-bucket:my-mof.mof The Report, Status, and Module Source bucket names should be formatted as follows. bucket-region:amzn-s3-demo-bucket. Here is an example: us-west-1:amzn-s3-demo- bucket; • If Region-specific syntax doesn't fix the problem, then make sure that the targeted nodes can access Amazon S3 in the desired Region. To verify this: 1. Find the endpoint name for Amazon S3 in the appropriate Amazon S3 Region. For information, see Amazon S3 Service Endpoints in the Amazon Web Services General Reference. 2. Log on to the target node and run the following ping command. ping s3.s3-region.amazonaws.com State Manager 1037 AWS Systems Manager User Guide If the ping failed, it means that either Amazon S3 is down, or a firewall/transparent proxy is blocking access to the Amazon S3 Region, or the node can't access the internet. Viewing DSC resource compliance details Systems Manager captures compliance information about DSC resource failures in the Amazon S3 Status Bucket you specified when you ran the AWS-ApplyDSCMofs document. Searching for information about DSC resource failures in an Amazon S3 bucket can be time consuming. Instead, you can view this information in the Systems Manager Compliance page. The Compliance resources summary section displays a count of resources that failed. In the following example, the ComplianceType is Custom:DSC and one resource is noncompliant. Note Custom:DSC is the default ComplianceType value in the AWS-ApplyDSCMofs document. This value is customizable. The Details overview for resources section displays information about the AWS resource with the noncompliant DSC resource. This section also includes the MOF name, script execution steps, and (when applicable) a View output link to view detailed status information. State Manager 1038 AWS Systems Manager User Guide The View output link displays the last 4,000 characters of the detailed status. Systems Manager starts with the exception as the first element, and then scans back through the verbose messages and prepends as many as it can until it reaches the 4,000 character quota. This process displays the log messages that were output
|
systems-manager-ug-325
|
systems-manager-ug.pdf
| 325 |
Details overview for resources section displays information about the AWS resource with the noncompliant DSC resource. This section also includes the MOF name, script execution steps, and (when applicable) a View output link to view detailed status information. State Manager 1038 AWS Systems Manager User Guide The View output link displays the last 4,000 characters of the detailed status. Systems Manager starts with the exception as the first element, and then scans back through the verbose messages and prepends as many as it can until it reaches the 4,000 character quota. This process displays the log messages that were output before the exception was thrown, which are the most relevant messages for troubleshooting. State Manager 1039 AWS Systems Manager User Guide For information about how to view compliance information, see AWS Systems Manager Compliance. Situations that affect compliance reporting If the State Manager association fails, then no compliance data is reported. More specifically, if a MOF fails to process, then Systems Manager doesn’t report any compliance items because the associations fails. For example, if Systems Manager attempts to download a MOF from an Amazon S3 bucket that the node doesn't have permission to access, then the association fails and no compliance data is reported. If a resource in a second MOF fails, then Systems Manager does report compliance data. For example, if a MOF tries to create a file on a drive that doesn’t exist, then Systems Manager reports compliance because the AWS-ApplyDSCMofs document is able to process completely, which means the association successfully runs. Creating associations that run Ansible playbooks You can create State Manager associations that run Ansible playbooks by using the AWS- ApplyAnsiblePlaybooks SSM document. State Manager is a tool in AWS Systems Manager. This document offers the following benefits for running playbooks: State Manager 1040 AWS Systems Manager User Guide • Support for running complex playbooks • Support for downloading playbooks from GitHub and Amazon Simple Storage Service (Amazon S3) • Support for compressed playbook structure • Enhanced logging • Ability to specify which playbook to run when playbooks are bundled Note Systems Manager includes two SSM documents that allow you to create State Manager associations that run Ansible playbooks: AWS-RunAnsiblePlaybook and AWS- ApplyAnsiblePlaybooks. The AWS-RunAnsiblePlaybook document is deprecated. It remains available in Systems Manager for legacy purposes. We recommend that you use the AWS-ApplyAnsiblePlaybooks document because of the enhancements described here. Associations that run Ansible playbooks aren't supported on macOS. Support for running complex playbooks The AWS-ApplyAnsiblePlaybooks document supports bundled, complex playbooks because it copies the entire file structure to a local directory before executing the specified main playbook. You can provide source playbooks in Zip files or in a directory structure. The Zip file or directory can be stored in GitHub or Amazon S3. Support for downloading playbooks from GitHub The AWS-ApplyAnsiblePlaybooks document uses the aws:downloadContent plugin to download playbook files. Files can be stored in GitHub in a single file or as a combined set of playbook files. To download content from GitHub, specify information about your GitHub repository in JSON format. Here is an example. { "owner":"TestUser", "repository":"GitHubTest", "path":"scripts/python/test-script", "getOptions":"branch:master", "tokenInfo":"{{ssm-secure:secure-string-token}}" State Manager 1041 AWS Systems Manager } User Guide Support for downloading playbooks from Amazon S3 You can also store and download Ansible playbooks in Amazon S3 as either a single .zip file or a directory structure. To download content from Amazon S3, specify the path to the file. Here are two examples. Example 1: Download a specific playbook file { "path":"https://s3.amazonaws.com/amzn-s3-demo-bucket/playbook.yml" } Example 2: Download the contents of a directory { "path":"https://s3.amazonaws.com/amzn-s3-demo-bucket/ansible/webservers/" } Important If you specify Amazon S3, then the AWS Identity and Access Management (IAM) instance profile on your managed nodes must include permissions for the S3 bucket. For more information, see Configure instance permissions required for Systems Manager. Support for compressed playbook structure The AWS-ApplyAnsiblePlaybooks document allows you to run compressed .zip files in the downloaded bundle. The document checks if the downloaded files contain a compressed file in .zip format. If a .zip is found, the document automatically decompresses the file and then runs the specified Ansible automation. Enhanced logging The AWS-ApplyAnsiblePlaybooks document includes an optional parameter for specifying different levels of logging. Specify -v for low verbosity, -vv or –vvv for medium verbosity, and -vvvv for debug level logging. These options directly map to Ansible verbosity options. State Manager 1042 AWS Systems Manager User Guide Ability to specify which playbook to run when playbooks are bundled The AWS-ApplyAnsiblePlaybooks document includes a required parameter for specifying which playbook to run when multiple playbooks are bundled. This option provides flexibility for running playbooks to support different use cases. Understanding installed dependencies If you specify True for the InstallDependencies parameter, then Systems Manager verifies that your nodes have the following dependencies installed: • Ubuntu Server/Debian Server: Apt-get (Package
|
systems-manager-ug-326
|
systems-manager-ug.pdf
| 326 |
low verbosity, -vv or –vvv for medium verbosity, and -vvvv for debug level logging. These options directly map to Ansible verbosity options. State Manager 1042 AWS Systems Manager User Guide Ability to specify which playbook to run when playbooks are bundled The AWS-ApplyAnsiblePlaybooks document includes a required parameter for specifying which playbook to run when multiple playbooks are bundled. This option provides flexibility for running playbooks to support different use cases. Understanding installed dependencies If you specify True for the InstallDependencies parameter, then Systems Manager verifies that your nodes have the following dependencies installed: • Ubuntu Server/Debian Server: Apt-get (Package Management), Python 3, Ansible, Unzip • Amazon Linux: Ansible • RHEL: Python 3, Ansible, Unzip If one or more of these dependencies aren't found, then Systems Manager automatically installs them. Create an association that runs Ansible playbooks (console) The following procedure describes how to use the Systems Manager console to create a State Manager association that runs Ansible playbooks by using the AWS-ApplyAnsiblePlaybooks document. To create an association that runs Ansible playbooks (console) 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose State Manager. 3. Choose State Manager, and then choose Create association. 4. 5. 6. For Name, specify a name that helps you remember the purpose of the association. In the Document list, choose AWS-ApplyAnsiblePlaybooks. In the Parameters section, for Source Type, choose either GitHub or S3. GitHub If you choose GitHub, enter repository information in the following format. { State Manager 1043 AWS Systems Manager User Guide "owner":"user_name", "repository":"name", "path":"path_to_directory_or_playbook_to_download", "getOptions":"branch:branch_name", "tokenInfo":"{{(Optional)_token_information}}" } S3 If you choose S3, enter path information in the following format. { "path":"https://s3.amazonaws.com/path_to_directory_or_playbook_to_download" } For Install Dependencies, choose an option. (Optional) For Playbook File, enter a file name. If a Zip file contains the playbook, specify a relative path to the Zip file. (Optional) For Extra Variables, enter variables that you want State Manager to send to Ansible at runtime. 7. 8. 9. 10. (Optional) For Check, choose an option. 11. (Optional) For Verbose, choose an option. 12. For Targets, choose an option. For information about using targets, see Understanding targets and rate controls in State Manager associations. 13. 14. In the Specify schedule section, choose either On schedule or No schedule. If you choose On schedule, then use the buttons provided to create a cron or rate schedule for the association. In the Advanced options section, for Compliance severity, choose a severity level for the association. Compliance reporting indicates whether the association state is compliant or noncompliant, along with the severity level you indicate here. For more information, see About State Manager association compliance. 15. In the Rate control section, configure options to run State Manager associations across a fleet of managed nodes. For information about using rate controls, see Understanding targets and rate controls in State Manager associations. In the Concurrency section, choose an option: • Choose targets to enter an absolute number of targets that can run the association simultaneously. State Manager 1044 AWS Systems Manager User Guide • Choose percentage to enter a percentage of the target set that can run the association simultaneously. In the Error threshold section, choose an option: • Choose errors to enter an absolute number of errors that are allowed before State Manager stops running associations on additional targets. • Choose percentage to enter a percentage of errors that are allowed before State Manager stops running associations on additional targets. 16. (Optional) For Output options, to save the command output to a file, select the Enable writing output to S3 box. Enter the bucket and prefix (folder) names in the boxes. Note The S3 permissions that grant the ability to write the data to an S3 bucket are those of the instance profile assigned to the managed node, not those of the IAM user performing this task. For more information, see Configure instance permissions required for Systems Manager or Create an IAM service role for a hybrid environment. In addition, if the specified S3 bucket is in a different AWS account, verify that the instance profile or IAM service role associated with the managed node has the necessary permissions to write to that bucket. 17. Choose Create Association. Note If you use tags to create an association on one or more target nodes, and then you remove the tags from a node, that node no longer runs the association. The node is disassociated from the State Manager document. Create an association that runs Ansible playbooks (CLI) The following procedure describes how to use the AWS Command Line Interface (AWS CLI) to create a State Manager association that runs Ansible playbooks by using the AWS- ApplyAnsiblePlaybooks document. State Manager 1045 AWS Systems Manager User Guide To create an association that runs Ansible playbooks (CLI) 1. Install and configure the
|
systems-manager-ug-327
|
systems-manager-ug.pdf
| 327 |
Note If you use tags to create an association on one or more target nodes, and then you remove the tags from a node, that node no longer runs the association. The node is disassociated from the State Manager document. Create an association that runs Ansible playbooks (CLI) The following procedure describes how to use the AWS Command Line Interface (AWS CLI) to create a State Manager association that runs Ansible playbooks by using the AWS- ApplyAnsiblePlaybooks document. State Manager 1045 AWS Systems Manager User Guide To create an association that runs Ansible playbooks (CLI) 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 to create an association that runs Ansible playbooks by targeting nodes using tags. Replace each example resource placeholder with your own information. Command (A) specifies GitHub as the source type. Command (B) specifies Amazon S3 as the source type. (A) GitHub source Linux & macOS aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" \ --targets Key=tag:TagKey,Values=TagValue \ --parameters '{"SourceType":["GitHub"],"SourceInfo": ["{\"owner\":\"owner_name\", \"repository\": \"name\", \"getOptions\": \"branch:master\"}"],"InstallDependencies": ["True_or_False"],"PlaybookFile":["file_name.yml"],"ExtraVariables":["key/ value_pairs_separated_by_a_space"],"Check":["True_or_False"],"Verbose":["-v,- vv,-vvv, or -vvvv"],"TimeoutSeconds":["3600"]}' \ --association-name "name" \ --schedule-expression "cron_or_rate_expression" Windows aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" ^ --targets Key=tag:TagKey,Values=TagValue ^ --parameters '{"SourceType":["GitHub"],"SourceInfo": ["{\"owner\":\"owner_name\", \"repository\": \"name\", \"getOptions\": \"branch:master\"}"],"InstallDependencies": ["True_or_False"],"PlaybookFile":["file_name.yml"],"ExtraVariables":["key/ value_pairs_separated_by_a_space"],"Check":["True_or_False"],"Verbose":["-v,- vv,-vvv, or -vvvv"], "TimeoutSeconds":["3600"]}' ^ --association-name "name" ^ --schedule-expression "cron_or_rate_expression" Here is an example. State Manager 1046 AWS Systems Manager User Guide aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" \ --targets "Key=tag:OS,Values=Linux" \ --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner\": \"ansibleDocumentTest\", \"repository\": \"Ansible\", \"getOptions\": \"branch:master\"}"],"InstallDependencies":["True"],"PlaybookFile":["hello-world- playbook.yml"],"ExtraVariables":["SSM=True"],"Check":["False"],"Verbose":["-v"]}' \ --association-name "AnsibleAssociation" \ --schedule-expression "cron(0 2 ? * SUN *)" (B) S3 source Linux & macOS aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" \ --targets Key=tag:TagKey,Values=TagValue \ --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https:// s3.amazonaws.com/ path_to_Zip_file,_directory,_or_playbook_to_download\"}"],"InstallDependencies": ["True_or_False"],"PlaybookFile":["file_name.yml"],"ExtraVariables":["key/ value_pairs_separated_by_a_space"],"Check":["True_or_False"],"Verbose":["-v,- vv,-vvv, or -vvvv"]}' \ --association-name "name" \ --schedule-expression "cron_or_rate_expression" Windows aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" ^ --targets Key=tag:TagKey,Values=TagValue ^ --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https:// s3.amazonaws.com/ path_to_Zip_file,_directory,_or_playbook_to_download\"}"],"InstallDependencies": ["True_or_False"],"PlaybookFile":["file_name.yml"],"ExtraVariables":["key/ value_pairs_separated_by_a_space"],"Check":["True_or_False"],"Verbose":["-v,- vv,-vvv, or -vvvv"]}' ^ --association-name "name" ^ --schedule-expression "cron_or_rate_expression" Here is an example. aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" \ State Manager 1047 AWS Systems Manager User Guide --targets "Key=tag:OS,Values=Linux" \ --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https:// s3.amazonaws.com/amzn-s3-demo-bucket/playbook.yml\"}"],"InstallDependencies": ["True"],"PlaybookFile":["playbook.yml"],"ExtraVariables":["SSM=True"],"Check": ["False"],"Verbose":["-v"]}' \ --association-name "AnsibleAssociation" \ --schedule-expression "cron(0 2 ? * SUN *)" Note State Manager associations don't support all cron and rate expressions. For more information about creating cron and rate expressions for associations, see Reference: Cron and rate expressions for Systems Manager. The system attempts to create the association on the nodes and immediately apply the state. 3. Run the following command to view an updated status of the association you just created. aws ssm describe-association --association-id "ID" Creating associations that run Chef recipes You can create State Manager associations that run Chef recipes by using the AWS- ApplyChefRecipes SSM document. State Manager is a tool in AWS Systems Manager. You can target Linux-based Systems Manager managed nodes with the AWS-ApplyChefRecipes SSM document. This document offers the following benefits for running Chef recipes: • Supports multiple releases of Chef (Chef 11 through Chef 18). • Automatically installs the Chef client software on target nodes. • Optionally runs Systems Manager compliance checks on target nodes, and stores the results of compliance checks in an Amazon Simple Storage Service (Amazon S3) bucket. • Runs multiple cookbooks and recipes in a single run of the document. • Optionally runs recipes in why-run mode, to show which recipes change on target nodes without making changes. • Optionally applies custom JSON attributes to chef-client runs. State Manager 1048 AWS Systems Manager User Guide • Optionally applies custom JSON attributes from a source file that is stored at a location that you specify. You can use Git, GitHub, HTTP, or Amazon S3 buckets as download sources for Chef cookbooks and recipes that you specify in an AWS-ApplyChefRecipes document. Note Associations that run Chef recipes aren't supported on macOS. Getting started Before you create an AWS-ApplyChefRecipes document, prepare your Chef cookbooks and cookbook repository. If you don't already have a Chef cookbook that you want to use, you can get started by using a test HelloWorld cookbook that AWS has prepared for you. The AWS- ApplyChefRecipes document already points to this cookbook by default. Your cookbooks should be set up similarly to the following directory structure. In the following example, jenkins and nginx are examples of Chef cookbooks that are available in the Chef Supermarket on the Chef website. Though AWS can't officially support cookbooks on the Chef Supermarket website, many of them work with the AWS-ApplyChefRecipes document. The following are examples of criteria to determine when you're testing a community cookbook: • The cookbook should support the Linux-based operating systems of the Systems Manager managed nodes that you're targeting. • The cookbook should be valid for the Chef client version (Chef 11 through Chef 18) that you use. • The cookbook is compatible with
|
systems-manager-ug-328
|
systems-manager-ug.pdf
| 328 |
structure. In the following example, jenkins and nginx are examples of Chef cookbooks that are available in the Chef Supermarket on the Chef website. Though AWS can't officially support cookbooks on the Chef Supermarket website, many of them work with the AWS-ApplyChefRecipes document. The following are examples of criteria to determine when you're testing a community cookbook: • The cookbook should support the Linux-based operating systems of the Systems Manager managed nodes that you're targeting. • The cookbook should be valid for the Chef client version (Chef 11 through Chef 18) that you use. • The cookbook is compatible with Chef Infra Client, and, doesn't require a Chef server. Verify that you can reach the Chef.io website, so that any cookbooks you specify in your run list can be installed when the Systems Manager document (SSM document) runs. Using a nested cookbooks folder is supported, but not required; you can store cookbooks directly under the root level. <Top-level directory, or the top level of the archive file (ZIP or tgz or tar.gz)> ### cookbooks (optional level) State Manager 1049 AWS Systems Manager User Guide ### jenkins # ### metadata.rb # ### recipes ### nginx ### metadata.rb ### recipes Important Before you create a State Manager association that runs Chef recipes, be aware that the document run installs the Chef client software on your Systems Manager managed nodes, unless you set the value of Chef client version to None. This operation uses an installation script from Chef to install Chef components on your behalf. Before you run an AWS- ApplyChefRecipes document, be sure your enterprise can comply with any applicable legal requirements, including license terms applicable to the use of Chef software. For more information, see the Chef website. Systems Manager can deliver compliance reports to an S3 bucket, the Systems Manager console, or make compliance results available in response to Systems Manager API commands. To run Systems Manager compliance reports, the instance profile attached to Systems Manager managed nodes must have permissions to write to the S3 bucket. The instance profile must have permissions to use the Systems Manager PutComplianceItem API. For more information about Systems Manager compliance, see AWS Systems Manager Compliance. Logging the document run When you run a Systems Manager document (SSM document) by using a State Manager association, you can configure the association to choose the output of the document run, and you can send the output to Amazon S3 or Amazon CloudWatch Logs (CloudWatch Logs). To help ease troubleshooting when an association has finished running, verify that the association is configured to write command output to either an Amazon S3 bucket or CloudWatch Logs. For more information, see Working with associations in Systems Manager. Applying JSON attributes to targets when running a recipe You can specify JSON attributes for your Chef client to apply to target nodes during an association run. When setting up the association, you can provide raw JSON or provide the path to a JSON file stored in Amazon S3. State Manager 1050 AWS Systems Manager User Guide Use JSON attributes when you want to customize how the recipe is run without having to modify the recipe itself, for example: • Overriding a small number of attributes Use custom JSON to avoid having to maintain multiple versions of a recipe to accommodate minor differences. • Providing variable values Use custom JSON to specify values that may change from run-to-run. For example, if your Chef cookbooks configure a third-party application that accepts payments, you might use custom JSON to specify the payment endpoint URL. Specifying attributes in raw JSON The following is an example of the format you can use to specify custom JSON attributes for your Chef recipe. {"filepath":"/tmp/example.txt", "content":"Hello, World!"} Specifying a path to a JSON file The following is an example of the format you can use to specify the path to custom JSON attributes for your Chef recipe. {"sourceType":"s3", "sourceInfo":"someS3URL1"}, {"sourceType":"s3", "sourceInfo":"someS3URL2"} Use Git as a cookbook source The AWS-ApplyChefRecipes document uses the aws:downloadContent plugin to download Chef cookbooks. To download content from Git, specify information about your Git repository in JSON format as in the following example. Replace each example-resource-placeholder with your own information. { "repository":"GitCookbookRepository", "privateSSHKey":"{{ssm-secure:ssh-key-secure-string-parameter}}", "skipHostKeyChecking":"false", State Manager 1051 AWS Systems Manager User Guide "getOptions":"branch:refs/head/main", "username":"{{ssm-secure:username-secure-string-parameter}}", "password":"{{ssm-secure:password-secure-string-parameter}}" } Use GitHub as a cookbook source The AWS-ApplyChefRecipes document uses the aws:downloadContent plugin to download cookbooks. To download content from GitHub, specify information about your GitHub repository in JSON format as in the following example. Replace each example-resource-placeholder with your own information. { "owner":"TestUser", "repository":"GitHubCookbookRepository", "path":"cookbooks/HelloWorld", "getOptions":"branch:refs/head/main", "tokenInfo":"{{ssm-secure:token-secure-string-parameter}}" } Use HTTP as a cookbook source You can store Chef cookbooks at a custom HTTP location as either a single .zip or tar.gz file, or a directory structure. To download content from HTTP, specify the path to the file
|
systems-manager-ug-329
|
systems-manager-ug.pdf
| 329 |
State Manager 1051 AWS Systems Manager User Guide "getOptions":"branch:refs/head/main", "username":"{{ssm-secure:username-secure-string-parameter}}", "password":"{{ssm-secure:password-secure-string-parameter}}" } Use GitHub as a cookbook source The AWS-ApplyChefRecipes document uses the aws:downloadContent plugin to download cookbooks. To download content from GitHub, specify information about your GitHub repository in JSON format as in the following example. Replace each example-resource-placeholder with your own information. { "owner":"TestUser", "repository":"GitHubCookbookRepository", "path":"cookbooks/HelloWorld", "getOptions":"branch:refs/head/main", "tokenInfo":"{{ssm-secure:token-secure-string-parameter}}" } Use HTTP as a cookbook source You can store Chef cookbooks at a custom HTTP location as either a single .zip or tar.gz file, or a directory structure. To download content from HTTP, specify the path to the file or directory in JSON format as in the following example. Replace each example-resource-placeholder with your own information. { "url":"https://my.website.com/chef-cookbooks/HelloWorld.zip", "allowInsecureDownload":"false", "authMethod":"Basic", "username":"{{ssm-secure:username-secure-string-parameter}}", "password":"{{ssm-secure:password-secure-string-parameter}}" } Use Amazon S3 as a cookbook source You can also store and download Chef cookbooks in Amazon S3 as either a single .zip or tar.gz file, or a directory structure. To download content from Amazon S3, specify the path to the file in JSON format as in the following examples. Replace each example-resource-placeholder with your own information. State Manager 1052 AWS Systems Manager User Guide Example 1: Download a specific cookbook { "path":"https://s3.amazonaws.com/chef-cookbooks/HelloWorld.zip" } Example 2: Download the contents of a directory { "path":"https://s3.amazonaws.com/chef-cookbooks-test/HelloWorld" } Important If you specify Amazon S3, the AWS Identity and Access Management (IAM) instance profile on your managed nodes must be configured with the AmazonS3ReadOnlyAccess policy. For more information, see Configure instance permissions required for Systems Manager. Create an association that runs Chef recipes (console) The following procedure describes how to use the Systems Manager console to create a State Manager association that runs Chef cookbooks by using the AWS-ApplyChefRecipes document. 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose State Manager. 3. Choose State Manager, and then choose Create association. 4. 5. 6. 7. For Name, enter a name that helps you remember the purpose of the association. In the Document list, choose AWS-ApplyChefRecipes. In Parameters, for Source Type, select either Git, GitHub, HTTP, or S3. For Source info, enter cookbook source information using the appropriate format for the Source Type that you selected in step 6. For more information, see the following topics: • the section called “Use Git as a cookbook source” • the section called “Use GitHub as a cookbook source” State Manager 1053 AWS Systems Manager User Guide • the section called “Use HTTP as a cookbook source” • the section called “Use Amazon S3 as a cookbook source” 8. In Run list, list the recipes that you want to run in the following format, separating each recipe with a comma as shown. Don't include a space after the comma. Replace each example- resource-placeholder with your own information. recipe[cookbook-name1::recipe-name],recipe[cookbook-name2::recipe-name] 9. (Optional) Specify custom JSON attributes that you want the Chef client to pass to your target nodes. a. b. In JSON attributes content, add any attributes that you want the Chef client to pass to your target nodes. In JSON attributes sources, add the paths to any attributes that you want the Chef client to pass to your target nodes. For more information, see the section called “Applying JSON attributes to targets when running a recipe”. 10. For Chef client version, specify a Chef version. Valid values are 11 through 18, or None. If you specify a number between 11 18 (inclusive), Systems Manager installs the correct Chef client version on your target nodes. If you specify None, Systems Manager doesn't install the Chef client on target nodes before running the document's recipes. 11. (Optional) For Chef client arguments, specify additional arguments that are supported for the version of Chef you're using. To learn more about supported arguments, run chef-client - h on a node that is running the Chef client. 12. (Optional) Turn on Why-run to show changes made to target nodes if the recipes are run, without actually changing target nodes. 13. For Compliance severity, choose the severity of Systems Manager Compliance results that you want reported. Compliance reporting indicates whether the association state is compliant or noncompliant, along with the severity level you specify. Compliance reports are stored in an S3 bucket that you specify as the value of the Compliance report bucket parameter (step 14). For more information about Compliance, see Learn details about Compliance in this guide. Compliance scans measure drift between configuration that is specified in your Chef recipes and node resources. Valid values are Critical, High, Medium, Low, Informational, Unspecified, or None. To skip compliance reporting, choose None. State Manager 1054 AWS Systems Manager User Guide 14. For Compliance type, specify the compliance type for which you want results reported. Valid values are Association for State Manager associations, or Custom:custom-type. The default value is Custom:Chef. 15. For Compliance report bucket, enter the
|
systems-manager-ug-330
|
systems-manager-ug.pdf
| 330 |
the value of the Compliance report bucket parameter (step 14). For more information about Compliance, see Learn details about Compliance in this guide. Compliance scans measure drift between configuration that is specified in your Chef recipes and node resources. Valid values are Critical, High, Medium, Low, Informational, Unspecified, or None. To skip compliance reporting, choose None. State Manager 1054 AWS Systems Manager User Guide 14. For Compliance type, specify the compliance type for which you want results reported. Valid values are Association for State Manager associations, or Custom:custom-type. The default value is Custom:Chef. 15. For Compliance report bucket, enter the name of an S3 bucket in which to store information about every Chef run performed by this document, including resource configuration and Compliance results. 16. In Rate control, configure options to run State Manager associations across a fleet of managed nodes. For information about using rate controls, see Understanding targets and rate controls in State Manager associations. In Concurrency, choose an option: • Choose targets to enter an absolute number of targets that can run the association simultaneously. • Choose percentage to enter a percentage of the target set that can run the association simultaneously. In Error threshold, choose an option: • Choose errors to enter an absolute number of errors that are allowed before State Manager stops running associations on additional targets. • Choose percentage to enter a percentage of errors that are allowed before State Manager stops running associations on additional targets. 17. (Optional) For Output options, to save the command output to a file, select the Enable writing output to S3 box. Enter the bucket and prefix (folder) names in the boxes. Note The S3 permissions that grant the ability to write the data to an S3 bucket are those of the instance profile assigned to the managed node, not those of the IAM user performing this task. For more information, see Configure instance permissions required for Systems Manager or Create an IAM service role for a hybrid environment. In addition, if the specified S3 bucket is in a different AWS account, verify that the instance profile or IAM service role associated with the managed node has the necessary permissions to write to that bucket. 18. Choose Create Association. State Manager 1055 AWS Systems Manager User Guide Create an association that runs Chef recipes (CLI) The following procedure describes how to use the AWS Command Line Interface (AWS CLI) to create a State Manager association that runs Chef cookbooks by using the AWS- ApplyChefRecipes document. 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 to create an association that runs Chef cookbooks on target nodes that have the specified tags. Use the command that is appropriate for your cookbook source type and operating system. Replace each example-resource- placeholder with your own information. a. Git source Linux & macOS aws ssm create-association --name "AWS-ApplyChefRecipes" \ --targets Key=tag:TagKey,Values=TagValue \ --parameters '{"SourceType":["Git"],"SourceInfo":["{\"repository\": \"repository-name\", \"getOptions\": \"branch:branch-name\", \"username \": \"{{ ssm-secure:username-secure-string-parameter }}\", \"password\": \"{{ ssm-secure:password-secure-string-parameter }}\"}"], "RunList": ["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook- name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json- content}"], "JsonAttributesSources": "{\"sourceType\":\"s3\", \"sourceInfo \":\"s3-bucket-endpoint-1\"}, {\"sourceType\":\"s3\", \"sourceInfo\": \"s3-bucket-endpoint-2\"}", "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef-client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity-value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3-bucket-name"]}' \ --association-name "name" \ --schedule-expression "cron-or-rate-expression" Windows aws ssm create-association --name "AWS-ApplyChefRecipes" ^ --targets Key=tag:TagKey,Values=TagValue ^ --parameters '{"SourceType":["Git"],"SourceInfo":["{\"repository\": \"repository-name\", \"getOptions\": \"branch:branch-name\", \"username State Manager 1056 AWS Systems Manager User Guide \": \"{{ ssm-secure:username-secure-string-parameter }}\", \"password\": \"{{ ssm-secure:password-secure-string-parameter }}\"}"], "RunList": ["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook- name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json}"], "JsonAttributesSources": "{\"sourceType\":\"s3\", \"sourceInfo\": \"s3-bucket-endpoint-1\"}, {\"sourceType\":\"s3\", \"sourceInfo\": \"s3-bucket-endpoint-2\"}", "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef-client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity-value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3-bucket-name"]}' ^ --association-name "name" ^ --schedule-expression "cron-or-rate-expression" b. GitHub source Linux & macOS aws ssm create-association --name "AWS-ApplyChefRecipes" \ --targets Key=tag:TagKey,Values=TagValue \ --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner\": \"owner-name\", \"repository\": \"name\", \"path\": \"path-to-directory- or-cookbook-to-download\", \"getOptions\": \"branch:branch-name\"}"], "RunList":["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook- name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json}"], "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef- client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity- value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3- bucket-name"]}' \ --association-name "name" \ --schedule-expression "cron-or-rate-expression" Windows aws ssm create-association --name "AWS-ApplyChefRecipes" ^ --targets Key=tag:TagKey,Values=TagValue \ --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner\": \"owner-name\", \"repository\": \"name\", \"path\": \"path-to-directory- or-cookbook-to-download\", \"getOptions\": \"branch:branch-name\"}"], "RunList":["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook- name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json}"], "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef- State Manager 1057 AWS Systems Manager User Guide client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity- value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3- bucket-name"]}' ^ --association-name "name" ^ --schedule-expression "cron-or-rate-expression" Here is an example. Linux & macOS aws ssm create-association --name "AWS-ApplyChefRecipes" \ --targets Key=tag:OS,Values=Linux \ --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner \":\"ChefRecipeTest\", \"repository\": \"ChefCookbooks\", \"path \": \"cookbooks/HelloWorld\", \"getOptions\": \"branch:master \"}"], "RunList":["{\"recipe[HelloWorld::HelloWorldRecipe]\", \"recipe[HelloWorld::InstallApp]\"}"], "JsonAttributesContent": ["{\"state\": \"visible\",\"colors\": {\"foreground\": \"light-blue \",\"background\": \"dark-gray\"}}"], "ChefClientVersion": ["14"], "ChefClientArguments":["{--fips}"], "WhyRun": false, "ComplianceSeverity": ["Medium"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["ChefComplianceResultsBucket"]}' \ --association-name "MyChefAssociation" \ --schedule-expression "cron(0 2 ? * SUN *)" Windows aws ssm create-association --name "AWS-ApplyChefRecipes" ^ --targets Key=tag:OS,Values=Linux ^ --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner \":\"ChefRecipeTest\", \"repository\": \"ChefCookbooks\", \"path \": \"cookbooks/HelloWorld\", \"getOptions\": \"branch:master \"}"], "RunList":["{\"recipe[HelloWorld::HelloWorldRecipe]\", \"recipe[HelloWorld::InstallApp]\"}"], "JsonAttributesContent": ["{\"state\": \"visible\",\"colors\":
|
systems-manager-ug-331
|
systems-manager-ug.pdf
| 331 |
"WhyRun": boolean, "ComplianceSeverity": ["severity- value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3- bucket-name"]}' ^ --association-name "name" ^ --schedule-expression "cron-or-rate-expression" Here is an example. Linux & macOS aws ssm create-association --name "AWS-ApplyChefRecipes" \ --targets Key=tag:OS,Values=Linux \ --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner \":\"ChefRecipeTest\", \"repository\": \"ChefCookbooks\", \"path \": \"cookbooks/HelloWorld\", \"getOptions\": \"branch:master \"}"], "RunList":["{\"recipe[HelloWorld::HelloWorldRecipe]\", \"recipe[HelloWorld::InstallApp]\"}"], "JsonAttributesContent": ["{\"state\": \"visible\",\"colors\": {\"foreground\": \"light-blue \",\"background\": \"dark-gray\"}}"], "ChefClientVersion": ["14"], "ChefClientArguments":["{--fips}"], "WhyRun": false, "ComplianceSeverity": ["Medium"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["ChefComplianceResultsBucket"]}' \ --association-name "MyChefAssociation" \ --schedule-expression "cron(0 2 ? * SUN *)" Windows aws ssm create-association --name "AWS-ApplyChefRecipes" ^ --targets Key=tag:OS,Values=Linux ^ --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner \":\"ChefRecipeTest\", \"repository\": \"ChefCookbooks\", \"path \": \"cookbooks/HelloWorld\", \"getOptions\": \"branch:master \"}"], "RunList":["{\"recipe[HelloWorld::HelloWorldRecipe]\", \"recipe[HelloWorld::InstallApp]\"}"], "JsonAttributesContent": ["{\"state\": \"visible\",\"colors\": {\"foreground\": \"light-blue \",\"background\": \"dark-gray\"}}"], "ChefClientVersion": ["14"], "ChefClientArguments":["{--fips}"], "WhyRun": false, "ComplianceSeverity": ["Medium"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["ChefComplianceResultsBucket"]}' ^ --association-name "MyChefAssociation" ^ --schedule-expression "cron(0 2 ? * SUN *)" State Manager 1058 AWS Systems Manager c. HTTP source Linux & macOS User Guide aws ssm create-association --name "AWS-ApplyChefRecipes" \ --targets Key=tag:TagKey,Values=TagValue \ --parameters '{"SourceType":["HTTP"],"SourceInfo":["{\"url\":\"url- to-zip-file|directory|cookbook\", \"authMethod\": \"auth-method\", \"username\": \"{{ ssm-secure:username-secure-string-parameter }}\", \"password\": \"{{ ssm-secure:password-secure-string-parameter }}\"}"], "RunList":["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook- name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json- content}"], "JsonAttributesSources": "{\"sourceType\":\"s3\", \"sourceInfo \":\"s3-bucket-endpoint-1\"}, {\"sourceType\":\"s3\", \"sourceInfo\": \"s3-bucket-endpoint-2\"}", "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef-client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity-value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3-bucket-name"]}' \ --association-name "name" \ --schedule-expression "cron-or-rate-expression" Windows aws ssm create-association --name "AWS-ApplyChefRecipes" ^ --targets Key=tag:TagKey,Values=TagValue ^ --parameters '{"SourceType":["HTTP"],"SourceInfo":["{\"url\":\"url- to-zip-file|directory|cookbook\", \"authMethod\": \"auth-method\", \"username\": \"{{ ssm-secure:username-secure-string-parameter }}\", \"password\": \"{{ ssm-secure:password-secure-string-parameter }}\"}"], "RunList":["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook- name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json- content}"], "JsonAttributesSources": "{\"sourceType\":\"s3\", \"sourceInfo \":\"s3-bucket-endpoint-1\"}, {\"sourceType\":\"s3\", \"sourceInfo\": \"s3-bucket-endpoint-2\"}", "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef-client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity-value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3-bucket-name"]}' \ --association-name "name" ^ --schedule-expression "cron-or-rate-expression" d. Amazon S3 source State Manager 1059 AWS Systems Manager Linux & macOS User Guide aws ssm create-association --name "AWS-ApplyChefRecipes" \ --targets Key=tag:TagKey,Values=TagValue \ --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https:// s3.amazonaws.com/path_to_Zip_file,_directory,_or_cookbook_to_download\"}"], "RunList":["{\"recipe[cookbook_name1::recipe_name]\", \"recipe[cookbook_name2::recipe_name]\"}"], "JsonAttributesContent": ["{Custom_JSON}"], "ChefClientVersion": ["version_number"], "ChefClientArguments":["{chef_client_arguments}"], "WhyRun": true_or_false, "ComplianceSeverity": ["severity_value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["amzn-s3-demo-bucket"]}' \ --association-name "name" \ --schedule-expression "cron_or_rate_expression" Windows aws ssm create-association --name "AWS-ApplyChefRecipes" ^ --targets Key=tag:TagKey,Values=TagValue ^ --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https:// s3.amazonaws.com/path_to_Zip_file,_directory,_or_cookbook_to_download\"}"], "RunList":["{\"recipe[cookbook_name1::recipe_name]\", \"recipe[cookbook_name2::recipe_name]\"}"], "JsonAttributesContent": ["{Custom_JSON}"], "ChefClientVersion": ["version_number"], "ChefClientArguments":["{chef_client_arguments}"], "WhyRun": true_or_false, "ComplianceSeverity": ["severity_value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["amzn-s3-demo-bucket"]}' ^ --association-name "name" ^ --schedule-expression "cron_or_rate_expression" Here is an example. Linux & macOS aws ssm create-association --name "AWS-ApplyChefRecipes" \ --targets "Key=tag:OS,Values= Linux" \ --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path \":\"https://s3.amazonaws.com/amzn-s3-demo-bucket/HelloWorld \"}"], "RunList":["{\"recipe[HelloWorld::HelloWorldRecipe]\", \"recipe[HelloWorld::InstallApp]\"}"], "JsonAttributesContent": State Manager 1060 AWS Systems Manager User Guide ["{\"state\": \"visible\",\"colors\": {\"foreground\": \"light-blue \",\"background\": \"dark-gray\"}}"], "ChefClientVersion": ["14"], "ChefClientArguments":["{--fips}"], "WhyRun": false, "ComplianceSeverity": ["Medium"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["ChefComplianceResultsBucket"]}' \ --association-name "name" \ --schedule-expression "cron(0 2 ? * SUN *)" Windows aws ssm create-association --name "AWS-ApplyChefRecipes" ^ --targets "Key=tag:OS,Values= Linux" ^ --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path \":\"https://s3.amazonaws.com/amzn-s3-demo-bucket/HelloWorld \"}"], "RunList":["{\"recipe[HelloWorld::HelloWorldRecipe]\", \"recipe[HelloWorld::InstallApp]\"}"], "JsonAttributesContent": ["{\"state\": \"visible\",\"colors\": {\"foreground\": \"light-blue \",\"background\": \"dark-gray\"}}"], "ChefClientVersion": ["14"], "ChefClientArguments":["{--fips}"], "WhyRun": false, "ComplianceSeverity": ["Medium"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["ChefComplianceResultsBucket"]}' ^ --association-name "name" ^ --schedule-expression "cron(0 2 ? * SUN *)" The system creates the association, and unless your specified cron or rate expression prevents it, the system runs the association on the target nodes. Note State Manager associations don't support all cron and rate expressions. For more information about creating cron and rate expressions for associations, see Reference: Cron and rate expressions for Systems Manager. 3. Run the following command to view the status of the association you just created. aws ssm describe-association --association-id "ID" State Manager 1061 AWS Systems Manager User Guide Viewing Chef resource compliance details Systems Manager captures compliance information about Chef-managed resources in the Amazon S3 Compliance report bucket value that you specified when you ran the AWS- ApplyChefRecipes document. Searching for information about Chef resource failures in an S3 bucket can be time consuming. Instead, you can view this information on the Systems Manager Compliance page. A Systems Manager Compliance scan collects information about resources on your managed nodes that were created or checked in the most recent Chef run. The resources can include files, directories, systemd services, yum packages, templated files, gem packages, and dependent cookbooks, among others. The Compliance resources summary section displays a count of resources that failed. In the following example, the ComplianceType is Custom:Chef and one resource is noncompliant. Note Custom:Chef is the default ComplianceType value in the AWS-ApplyChefRecipes document. This value is customizable. The Details overview for resources section shows information about the AWS resource that isn't in compliance. This section also includes the Chef resource type against which compliance was run, severity of issue, compliance status, and links to more information when applicable. State Manager 1062 AWS Systems Manager User Guide View output shows the last 4,000 characters of the detailed status. Systems Manager starts with the exception as the first element, finds verbose messages, and shows them until it reaches the 4,000 character quota. This process displays the log messages that were output before the exception was thrown, which are the most relevant messages for troubleshooting. For information about how to view compliance information, see AWS Systems Manager Compliance. Important If the State Manager association fails, no compliance data is reported. For example, if Systems Manager attempts to download a Chef cookbook from an
|
systems-manager-ug-332
|
systems-manager-ug.pdf
| 332 |
1062 AWS Systems Manager User Guide View output shows the last 4,000 characters of the detailed status. Systems Manager starts with the exception as the first element, finds verbose messages, and shows them until it reaches the 4,000 character quota. This process displays the log messages that were output before the exception was thrown, which are the most relevant messages for troubleshooting. For information about how to view compliance information, see AWS Systems Manager Compliance. Important If the State Manager association fails, no compliance data is reported. For example, if Systems Manager attempts to download a Chef cookbook from an S3 bucket that the node doesn't have permission to access, the association fails, and Systems Manager reports no compliance data. Walkthrough: Automatically update SSM Agent with the AWS CLI The following procedure walks you through the process of creating a State Manager association using the AWS Command Line Interface. The association automatically updates the SSM Agent State Manager 1063 AWS Systems Manager User Guide according to a schedule that you specify. For more information about SSM Agent, see Working with SSM Agent. To customize the update schedule for SSM Agent using the console, see Automatically updating SSM Agent. To be notified about SSM Agent updates, subscribe to the SSM Agent Release Notes page on GitHub. Before you begin Before you complete the following procedure, verify that you have at least one running Amazon Elastic Compute Cloud (Amazon EC2) instance for Linux, macOS, or Windows Server that is configured for Systems Manager. For more information, see Setting up managed nodes for AWS Systems Manager. If you create an association by using either the AWS CLI or AWS Tools for Windows PowerShell, use the --Targets parameter to target instances, as shown in the following example. Don't use the --InstanceID parameter. The --InstanceID parameter is a legacy parameter. To create an association for automatically updating SSM Agent 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 create an association by targeting instances using Amazon Elastic Compute Cloud (Amazon EC2) tags. Replace each example resource placeholder with your own information. The Schedule parameter sets a schedule to run the association every Sunday morning at 2:00 a.m. (UTC). State Manager associations don't support all cron and rate expressions. For more information about creating cron and rate expressions for associations, see Reference: Cron and rate expressions for Systems Manager. Linux & macOS aws ssm create-association \ --targets Key=tag:tag_key,Values=tag_value \ --name AWS-UpdateSSMAgent \ --schedule-expression "cron(0 2 ? * SUN *)" State Manager 1064 AWS Systems Manager Windows User Guide aws ssm create-association ^ --targets Key=tag:tag_key,Values=tag_value ^ --name AWS-UpdateSSMAgent ^ --schedule-expression "cron(0 2 ? * SUN *)" You can target multiple instances by specifying instances IDs in a comma-separated list. Linux & macOS aws ssm create-association \ --targets Key=instanceids,Values=instance_ID,instance_ID,instance_ID \ --name AWS-UpdateSSMAgent \ --schedule-expression "cron(0 2 ? * SUN *)" Windows aws ssm create-association ^ --targets Key=instanceids,Values=instance_ID,instance_ID,instance_ID ^ --name AWS-UpdateSSMAgent ^ --schedule-expression "cron(0 2 ? * SUN *)" You can specify the version of the SSM Agent you want to update to. Linux & macOS aws ssm create-association \ --targets Key=instanceids,Values=instance_ID,instance_ID,instance_ID \ --name AWS-UpdateSSMAgent \ --schedule-expression "cron(0 2 ? * SUN *)" \ --parameters version=ssm_agent_version_number Windows aws ssm create-association ^ --targets Key=instanceids,Values=instance_ID,instance_ID,instance_ID ^ --name AWS-UpdateSSMAgent ^ State Manager 1065 AWS Systems Manager User Guide --schedule-expression "cron(0 2 ? * SUN *)" ^ --parameters version=ssm_agent_version_number The system returns information like the following. { "AssociationDescription": { "ScheduleExpression": "cron(0 2 ? * SUN *)", "Name": "AWS-UpdateSSMAgent", "Overview": { "Status": "Pending", "DetailedStatus": "Creating" }, "AssociationId": "123..............", "DocumentVersion": "$DEFAULT", "LastUpdateAssociationDate": 1504034257.98, "Date": 1504034257.98, "AssociationVersion": "1", "Targets": [ { "Values": [ "TagValue" ], "Key": "tag:TagKey" } ] } } The system attempts to create the association on the instance(s) and applies the state following creation. The association status shows Pending. 3. Run the following command to view an updated status of the association you created. aws ssm list-associations If your instances aren't running the most recent version of the SSM Agent, the status shows Failed. When a new version of SSM Agent is published, the association automatically installs the new agent, and the status shows Success. State Manager 1066 AWS Systems Manager User Guide Walkthrough: Automatically update PV drivers on EC2 instances for Windows Server Amazon Windows Amazon Machine Images (AMIs) contain a set of drivers to permit access to virtualized hardware. These drivers are used by Amazon Elastic Compute Cloud (Amazon EC2) to map instance store and Amazon Elastic Block Store (Amazon EBS) volumes to their devices. We recommend that you install the latest drivers to improve stability and performance of your EC2 instances for Windows Server. For more information about PV drivers, see AWS PV Drivers. The
|
systems-manager-ug-333
|
systems-manager-ug.pdf
| 333 |
new agent, and the status shows Success. State Manager 1066 AWS Systems Manager User Guide Walkthrough: Automatically update PV drivers on EC2 instances for Windows Server Amazon Windows Amazon Machine Images (AMIs) contain a set of drivers to permit access to virtualized hardware. These drivers are used by Amazon Elastic Compute Cloud (Amazon EC2) to map instance store and Amazon Elastic Block Store (Amazon EBS) volumes to their devices. We recommend that you install the latest drivers to improve stability and performance of your EC2 instances for Windows Server. For more information about PV drivers, see AWS PV Drivers. The following walkthrough shows you how to configure a State Manager association to automatically download and install new AWS PV drivers when the drivers become available. State Manager is a tool in AWS Systems Manager. Before you begin Before you complete the following procedure, verify that you have at least one Amazon EC2 instance for Windows Server running that is configured for Systems Manager. For more information, see Setting up managed nodes for AWS Systems Manager. To create a State Manager association that automatically updates PV drivers 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose State Manager. 3. Choose Create association. 4. 5. 6. In the Name field, enter a descriptive name for the association. In the Document list, choose AWS-ConfigureAWSPackage. In the Parameters area, do the following: • For Action, choose Install. • For Installation type, choose Uninstall and reinstall. Note In-place upgrades are not supported for this package. It must be uninstalled and reinstalled. • For Name, enter AWSPVDriver. State Manager 1067 AWS Systems Manager User Guide You don't need to enter anything for Version and Additional Arguments. 7. In the Targets section, choose the managed nodes on which you want to run this operation by specifying tags, selecting instances or edge devices manually, or specifying a resource group. Tip If a managed node you expect to see isn't listed, see Troubleshooting managed node availability for troubleshooting tips. Note If you choose to target instances by using tags, and you specify tags that map to Linux instances, the association succeeds on the Windows instance but fails on the Linux instances. The overall status of the association shows Failed. 8. 9. In the Specify schedule area, choose whether to run the association on a schedule that you configure, or just once. Updated PV drivers are released a several times a year, so you can schedule the association to run once a month, if you want. In the Advanced options area, for Compliance severity, choose a severity level for the association. Compliance reporting indicates whether the association state is compliant or noncompliant, along with the severity level you indicate here. For more information, see About State Manager association compliance. 10. For Rate control: • For Concurrency, specify either a number or a percentage of managed nodes on which to run the command at the same time. Note If you selected targets by specifying tags applied to managed nodes or by specifying AWS resource groups, and you aren't certain how many managed nodes are targeted, then restrict the number of targets that can run the document at the same time by specifying a percentage. State Manager 1068 AWS Systems Manager User Guide • For Error threshold, specify when to stop running the command on other managed nodes after it fails on either a number or a percentage of nodes. For example, if you specify three errors, then Systems Manager stops sending the command when the fourth error is received. Managed nodes still processing the command might also send errors. 11. (Optional) For Output options, to save the command output to a file, select the Enable writing output to S3 box. Enter the bucket and prefix (folder) names in the boxes. Note The S3 permissions that grant the ability to write the data to an S3 bucket are those of the instance profile assigned to the managed node, not those of the IAM user performing this task. For more information, see Configure instance permissions required for Systems Manager or Create an IAM service role for a hybrid environment. In addition, if the specified S3 bucket is in a different AWS account, verify that the instance profile or IAM service role associated with the managed node has the necessary permissions to write to that bucket. 12. (Optional) In the CloudWatch alarm section, for Alarm name, choose a CloudWatch alarm to apply to your association for monitoring. Note Note the following information about this step. • The alarms list displays a maximum of 100 alarms. If you don't see your alarm in the list, use the AWS Command Line Interface to create the association. For more information, see Create an association (command line). • To attach a
|
systems-manager-ug-334
|
systems-manager-ug.pdf
| 334 |
is in a different AWS account, verify that the instance profile or IAM service role associated with the managed node has the necessary permissions to write to that bucket. 12. (Optional) In the CloudWatch alarm section, for Alarm name, choose a CloudWatch alarm to apply to your association for monitoring. Note Note the following information about this step. • The alarms list displays a maximum of 100 alarms. If you don't see your alarm in the list, use the AWS Command Line Interface to create the association. For more information, see Create an association (command line). • To attach a CloudWatch alarm to your command, the IAM principal that creates the association must have permission for the iam:createServiceLinkedRole action. For more information about CloudWatch alarms, see Using Amazon CloudWatch alarms. • If your alarm activates, any pending command invocations or automations do not run. 13. Choose Create association, and then choose Close. The system attempts to create the association on the instances and immediately apply the state. State Manager 1069 AWS Systems Manager User Guide If you created the association on one or more Amazon EC2 instances for Windows Server, the status changes to Success. If your instances aren't configured for Systems Manager, or if you inadvertently targeted Linux instances, the status shows Failed. If the status is Failed, choose the association ID, choose the Resources tab, and then verify that the association was successfully created on your EC2 instances for Windows Server. If EC2 instances for Windows Server show a status of Failed, verify that the SSM Agent is running on the instance, and verify that the instance is configured with an AWS Identity and Access Management (IAM) role for Systems Manager. For more information, see Setting up Systems Manager unified console for an organization. AWS Systems Manager change management tools AWS Systems Manager provides the following tools for making changes to your AWS resources. Topics • AWS Systems Manager Automation • AWS Systems Manager Change Calendar • AWS Systems Manager Change Manager • AWS Systems Manager Documents • AWS Systems Manager Maintenance Windows • AWS Systems Manager Quick Setup AWS Systems Manager Automation Automation, a tool in AWS Systems Manager, simplifies common maintenance, deployment, and remediation tasks for AWS services like Amazon Elastic Compute Cloud (Amazon EC2), Amazon Relational Database Service (Amazon RDS), Amazon Redshift, Amazon Simple Storage Service (Amazon S3), and many more. To get started with Automation, open the Systems Manager console. In the navigation pane, choose Automation. Automation helps you to build automated solutions to deploy, configure, and manage AWS resources at scale. With Automation, you have granular control over the concurrency of your automations. This means you can specify how many resources to target concurrently, and how many errors can occur before an automation is stopped. Change management tools 1070 AWS Systems Manager User Guide To help you get started with Automation, AWS develops and maintains several pre-defined runbooks. Depending on your use case, you can use these pre-defined runbooks that perform a variety of tasks, or create your own custom runbooks that might better suit your needs. To monitor the progress and status of your automations, you can use the Systems Manager Automation console, or your preferred command line tool. Automation also integrates with Amazon EventBridge to help you build event-driven architecture at scale. How can Automation benefit my organization? Automation offers these benefits: • Scripting support in runbook content Using the aws:executeScript action, you can run custom Python and PowerShell functions directly from your runbooks. This provides you greater flexibility in creating your custom runbooks because you can complete various tasks that other Automation actions don't support. You also have greater control over the logic of the runbook. For an example of how this action can be used and how it can help to improve an existing automated solution, see Authoring Automation runbooks. • Run automations across multiple AWS accounts and AWS Regions from a centralized location Administrators can run automations on resources across multiple accounts and Regions from the Systems Manager console. • Enhanced operations security Administrators have a centralized place to grant and revoke access to runbooks. Using only AWS Identity and Access Management (IAM) policies, you can control which individual users or groups in your organization can use Automation and which runbooks they can access. • Automate common IT tasks Automating common tasks can help improve operational efficiency, enforce organizational standards, and reduce operator errors. For example, you can use the AWS- UpdateCloudFormationStackWithApproval runbook to update resources that were deployed by using an AWS CloudFormation template. The update applies a new template. You can configure the Automation to request approval by one or more users before the update begins. • Safely perform disruptive tasks in bulk Automation 1071 AWS Systems Manager User Guide Automation includes features, like rate controls,
|
systems-manager-ug-335
|
systems-manager-ug.pdf
| 335 |
individual users or groups in your organization can use Automation and which runbooks they can access. • Automate common IT tasks Automating common tasks can help improve operational efficiency, enforce organizational standards, and reduce operator errors. For example, you can use the AWS- UpdateCloudFormationStackWithApproval runbook to update resources that were deployed by using an AWS CloudFormation template. The update applies a new template. You can configure the Automation to request approval by one or more users before the update begins. • Safely perform disruptive tasks in bulk Automation 1071 AWS Systems Manager User Guide Automation includes features, like rate controls, that allow you to control the deployment of an automation across your fleet by specifying a concurrency value and an error threshold. For more information about working with rate controls, see Run automated operations at scale. • Streamline complex tasks Automation provides pre-defined runbooks that streamline complex and time-consuming tasks such as creating golden Amazon Machine Images (AMIs). For example, you can use the AWS- UpdateLinuxAmi and AWS-UpdateWindowsAmi runbooks to create golden AMIs from a source AMI. Using these runbooks, you can run custom scripts before and after updates are applied. You can also include or exclude specific software packages from being installed. For examples of how to use these runbooks, see Tutorials. • Define constraints for inputs You can define constraints in custom runbooks to limit the values that Automation will accept for a particular input parameter. For example, allowedPattern will only accept values for an input parameter that match the regular expression you define. If you specify allowedValues for an input parameter, only the values you've specified in the runbook are accepted. • Log automation action output to Amazon CloudWatch Logs To meet operational or security requirements in your organization, you might need to provide a record of the scripts run during a runbook. With CloudWatch Logs, you can monitor, store, and access log files from various AWS services. You can send output from the aws:executeScript action to a CloudWatch Logs log group for debugging and troubleshooting purposes. Log data can be sent to your log group with or without AWS KMS encryption using your KMS key. For more information, see Logging Automation action output with CloudWatch Logs. • Amazon EventBridge integration Automation is supported as a target type in Amazon EventBridge rules. This means you can trigger runbooks by using events. For more information, see Monitoring Systems Manager events with Amazon EventBridge and Reference: Amazon EventBridge event patterns and types for Systems Manager. • Share organizational best practices You can define best practices for resource management, operations tasks, and more in runbooks that you share across accounts and Regions. Automation 1072 AWS Systems Manager User Guide Who should use Automation? • Any AWS customer who wants 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 is an automation? An automation consists of all of the tasks that are defined in a runbook, and are performed by the Automation service. Automation uses the following components to run automations. Concept Details Automation runbook A Systems Manager Automation runbook defines the automation (the actions that Systems Manager performs on your managed nodes and AWS resources). Automation includes several pre-defined runbooks that you can use to perform common tasks like restarting one or more Amazon EC2 instances or creating an Amazon Machine Image (AMI). You can create your own runbooks as well. Runbooks use YAML or JSON, and they include steps and parameters that you specify. Steps run in sequential order. For more information, see Creating your own runbooks. Runbooks are Systems Manager documents of type Automation , as opposed to Command, Policy, Session documents. Runbooks support schema version 0.3. Command documents use schema version 1.2, 2.0, or 2.2. Automation 1073 AWS Systems Manager Concept Automation action Automation quota Automation queue quota User Guide Details Policy documents use schema version 2.0 or later. The automation defined in a runbook includes one or more steps. Each step is associated with a particular action. The action determine s the inputs, behavior, and outputs of the step. Steps are defined in the mainSteps section of your runbook. Automation supports 20 distinct action types. For more information, see the Systems Manager Automation actions reference. Each AWS account can run 100 automations simultaneously. This includes child automatio ns (automations that are started by another automation), and rate control automations. If you attempt to run more automations than this, Systems Manager adds the additional automations to a queue and displays a status of Pending. This
|
systems-manager-ug-336
|
systems-manager-ug.pdf
| 336 |
includes one or more steps. Each step is associated with a particular action. The action determine s the inputs, behavior, and outputs of the step. Steps are defined in the mainSteps section of your runbook. Automation supports 20 distinct action types. For more information, see the Systems Manager Automation actions reference. Each AWS account can run 100 automations simultaneously. This includes child automatio ns (automations that are started by another automation), and rate control automations. If you attempt to run more automations than this, Systems Manager adds the additional automations to a queue and displays a status of Pending. This quota can be adjusted using adaptive concurrency. For more informati on, see Allowing Automation to adapt to your concurrency needs.For more informati on about running automations, see Run an automated operation powered by Systems Manager Automation. If you attempt to run more automations than the concurrent automation limit, subsequen t automations are added to a queue. Each AWS account can queue 5,000 automations. When an automation is complete (or reaches a terminal state), the first automation in the queue is started. Automation 1074 AWS Systems Manager Concept Rate control automation quota Rate control automation queue quota User Guide Details Each AWS account can run 25 rate control automations simultaneously. If you attempt to run more rate control automations than the concurrent rate control automation limit, Systems Manager adds the subsequent rate control automations to a queue and displays a status of Pending. For more information about running rate control automations, see Run automated operations at scale. If you attempt to run more automations than the concurrent rate control automation limit, subsequent automations are added to a queue. Each AWS account can queue 1,000 rate control automations. When an automatio n is complete (or reaches a terminal state), the first automation in the queue is started. Topics • Setting up Automation • Run an automated operation powered by Systems Manager Automation • Run an automation that requires approvals • Run automated operations at scale • Running automations in multiple AWS Regions and accounts • Run automations based on EventBridge events • Run an automation step by step • Scheduling automations with State Manager associations • Schedule automations with maintenance windows • Systems Manager Automation actions reference • Creating your own runbooks • Systems Manager Automation runbook reference Automation 1075 AWS Systems Manager • Tutorials • Learn about statuses returned by Systems Manager Automation • Troubleshooting Systems Manager Automation User Guide Setting up Automation To set up Automation, a tool in AWS Systems Manager, you must verify user access to the Automation service and situationally configure roles so that the service can perform actions on your resources. We also recommend that you opt in to the adaptive concurrency mode in your Automation preferences. Adaptive concurrency automatically scales your automation quota to meet your needs. For more information, see Allowing Automation to adapt to your concurrency needs. To ensure proper access to AWS Systems Manager Automation, review the following user and service role requirements. Verifying user access for runbooks Verify that you have permission to use runbooks. If your user, group, or role is assigned administrator permissions, then you have access to Systems Manager Automation. If you don't have administrator permissions, then an administrator must give you permission by assigning the AmazonSSMFullAccess managed policy, or a policy that provides comparable permissions, to your user, group, or role. Important The IAM policy AmazonSSMFullAccess grants permissions to Systems Manager actions. However, some runbooks require permissions to other services, such as the runbook AWS-ReleaseElasticIP, which requires IAM permissions for ec2:ReleaseAddress. Therefore, you must review the actions taken in a runbook to ensure your user, group, or role is assigned the necessary permissions to perform the actions included in the runbook. Configuring a service role (assume role) access for automations Automations can be initiated under the context of a service role (or assume role). This allows the service to perform actions on your behalf. If you don't specify an assume role, Automation uses the context of the user who invoked the automation. Automation 1076 AWS Systems Manager User Guide However, the following situations require that you specify a service role for Automation: • When you want to restrict a user's permissions on a resource, but you want the user to run an automation that requires elevated permissions. In this scenario, you can create a service role with elevated permissions and allow the user to run the automation. • When you create a Systems Manager State Manager association that runs a runbook. • When you have operations that you expect to run longer than 12 hours. • When you're running a runbook not owned by Amazon that uses the aws:executeScript action to call an AWS API operation or to act on an AWS resource. For information, see Permissions
|
systems-manager-ug-337
|
systems-manager-ug.pdf
| 337 |
restrict a user's permissions on a resource, but you want the user to run an automation that requires elevated permissions. In this scenario, you can create a service role with elevated permissions and allow the user to run the automation. • When you create a Systems Manager State Manager association that runs a runbook. • When you have operations that you expect to run longer than 12 hours. • When you're running a runbook not owned by Amazon that uses the aws:executeScript action to call an AWS API operation or to act on an AWS resource. For information, see Permissions for using runbooks. If you need to create a service role for Automation, you can use one of the following methods. Topics • Create service roles for Automation by using AWS CloudFormation • Create the service roles for Automation using the console • Allowing Automation to adapt to your concurrency needs • Implement change controls for Automation Create service roles for Automation by using AWS CloudFormation You can create a service role for Automation, a tool in AWS Systems Manager, from an AWS CloudFormation template. After you create the service role, you can specify the service role in runbooks using the parameter AutomationAssumeRole. Create the service role using AWS CloudFormation Use the following procedure to create the required AWS Identity and Access Management (IAM) role for Systems Manager Automation by using AWS CloudFormation. To create the required IAM role 1. Download and unzip the AWS-SystemsManager-AutomationServiceRole.zip file. This file includes the AWS-SystemsManager-AutomationServiceRole.yaml AWS CloudFormation template file. 2. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. Automation 1077 AWS Systems Manager 3. Choose Create Stack. User Guide 4. In the Specify template section, choose Upload a template file. 5. Choose Browse, and then choose the AWS-SystemsManager- AutomationServiceRole.yaml AWS CloudFormation template file. 6. Choose Next. 7. On the Specify stack details page, in the Stack name field, enter a name. 8. On the Configure stack options page, you don’t need to make any selections. Choose Next. 9. On the Review page, scroll down and choose the I acknowledge that AWS CloudFormation might create IAM resources option. 10. Choose Create. CloudFormation shows the CREATE_IN_PROGRESS status for approximately three minutes. The status changes to CREATE_COMPLETE after the stack is created and your roles are ready to use. Important If you run an automation workflow that invokes other services by using an AWS Identity and Access Management (IAM) service role, be aware that the service role must be configured with permission to invoke those services. This requirement applies to all AWS Automation runbooks (AWS-* runbooks) such as the AWS-ConfigureS3BucketLogging, AWS-CreateDynamoDBBackup, and AWS-RestartEC2Instance runbooks, to name a few. This requirement also applies to any custom Automation 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, configure the service role with permission to invoke those services. You can give permissions to other AWS services by adding an IAM inline policy to the role. For more information, see (Optional) Add an Automation inline policy or customer managed policy to invoke other AWS services. Copy role information for Automation Use the following procedure to copy information about the Automation service role from the AWS CloudFormation console. You must specify these roles when you use a runbook. Automation 1078 AWS Systems Manager Note User Guide You don't need to copy role information using this procedure if you run the AWS- UpdateLinuxAmi or AWS-UpdateWindowsAmi runbooks. These runbooks already have the required roles specified as default values. The roles specified in these runbooks use IAM managed policies. To copy the role names 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select the Automation Stack name you created in the previous procedure. 3. Choose the Resources tab. 4. Choose the Physical ID link for AutomationServiceRole. The IAM console opens to a summary of the Automation service role. 5. Copy the Amazon Resource Name (ARN) next to Role ARN. The ARN is similar to the following: arn:aws:iam::12345678:role/AutomationServiceRole 6. Paste the ARN into a text file to use later. You have finished configuring the service role for Automation. You can now use the Automation service role ARN in your runbooks. Create the service roles for Automation using the console If you need to create a service role for Automation, a tool in AWS Systems Manager, complete the following tasks. For more information about when a service role is required for Automation, see Setting up Automation. Tasks • Task 1: Create a service role for Automation • Task 2: Attach the iam:PassRole policy to your Automation role Task 1: Create a service role for Automation Use the following procedure to create a service role (or assume role) for Systems Manager Automation. Automation 1079 AWS Systems Manager Note User Guide You
|
systems-manager-ug-338
|
systems-manager-ug.pdf
| 338 |
runbooks. Create the service roles for Automation using the console If you need to create a service role for Automation, a tool in AWS Systems Manager, complete the following tasks. For more information about when a service role is required for Automation, see Setting up Automation. Tasks • Task 1: Create a service role for Automation • Task 2: Attach the iam:PassRole policy to your Automation role Task 1: Create a service role for Automation Use the following procedure to create a service role (or assume role) for Systems Manager Automation. Automation 1079 AWS Systems Manager Note User Guide You can also use this role in runbooks, such as the AWS-CreateManagedLinuxInstance runbook. Using this role, or the Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role, in runbooks allows Automation to perform actions in your environment, such as launch new instances and perform actions on your behalf. To create an IAM role and allow Automation to assume it 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. In the navigation pane, choose Roles, and then choose Create role. 3. Under Select type of trusted entity, choose AWS service. 4. In the Choose a use case section, choose Systems Manager, and then choose Next: Permissions. 5. On the Attached permissions policy page, search for the AmazonSSMAutomationRole policy, choose it, and then choose Next: Review. 6. On the Review page, enter a name in the Role name box, and then enter a description. 7. Choose Create role. The system returns you to the Roles page. 8. On the Roles page, choose the role you just created to open the Summary page. Note the Role Name and Role ARN. You will specify the role ARN when you attach the iam:PassRole policy to your IAM account in the next procedure. You can also specify the role name and the ARN in runbooks. Note The AmazonSSMAutomationRole policy assigns the Automation role permission to a subset of AWS Lambda functions within your account. These functions begin with "Automation". If you plan to use Automation with Lambda functions, the Lambda ARN must use the following format: "arn:aws:lambda:*:*:function:Automation*" If you have existing Lambda functions whose ARNs don't use this format, then you must also attach an additional Lambda policy to your automation role, such as the Automation 1080 AWS Systems Manager User Guide AWSLambdaRole policy. The additional policy or role must provide broader access to Lambda functions within the AWS account. After creating your service role, we recommend editing the trust policy to help prevent the cross- service confused deputy problem. The confused deputy problem is a security issue where an entity that doesn't have permission to perform an action can coerce a more-privileged entity to perform the action. In AWS, cross-service impersonation can result in the confused deputy problem. Cross- service impersonation can occur when one service (the calling service) calls another service (the called service). The calling service can be manipulated to use its permissions to act on another customer's resources in a way it should not otherwise have permission to access. To prevent this, AWS provides tools that help you protect your data for all services with service principals that have been given access to resources in your account. We recommend using the aws:SourceArn and aws:SourceAccount global condition context keys in resource policies to limit the permissions that Automation gives another service to the resource. If the aws:SourceArn value doesn't contain the account ID, such as an Amazon S3 bucket ARN, you must use both global condition context keys to limit permissions. If you use both global condition context keys and the aws:SourceArn value contains the account ID, the aws:SourceAccount value and the account in the aws:SourceArn value must use the same account ID when used in the same policy statement. Use aws:SourceArn if you want only one resource to be associated with the cross-service access. Use aws:SourceAccount if you want to allow any resource in that account to be associated with the cross-service use. The value of aws:SourceArn must be the ARN for automation executions. If you don't know the full ARN of the resource or if you're specifying multiple resources, use the aws:SourceArn global context condition key with wildcards (*) for the unknown portions of the ARN. For example, arn:aws:ssm:*:123456789012:automation-execution/*. The following example shows how you can use the aws:SourceArn and aws:SourceAccount global condition context keys for Automation to prevent the confused deputy problem. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "ssm.amazonaws.com" Automation 1081 AWS Systems Manager ] }, "Action": "sts:AssumeRole", "Condition": { "StringEquals": { "aws:SourceAccount": "123456789012" }, "ArnLike": { "aws:SourceArn": "arn:aws:ssm:*:123456789012:automation-execution/*" User Guide } } } ] } To modify the role's trust policy 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. 3. In the navigation pane, choose Roles. In the list of roles
|
systems-manager-ug-339
|
systems-manager-ug.pdf
| 339 |
for the unknown portions of the ARN. For example, arn:aws:ssm:*:123456789012:automation-execution/*. The following example shows how you can use the aws:SourceArn and aws:SourceAccount global condition context keys for Automation to prevent the confused deputy problem. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "ssm.amazonaws.com" Automation 1081 AWS Systems Manager ] }, "Action": "sts:AssumeRole", "Condition": { "StringEquals": { "aws:SourceAccount": "123456789012" }, "ArnLike": { "aws:SourceArn": "arn:aws:ssm:*:123456789012:automation-execution/*" User Guide } } } ] } To modify the role's trust policy 1. Open the IAM console at https://console.aws.amazon.com/iam/. 2. 3. In the navigation pane, choose Roles. In the list of roles in your account, choose the name of your Automation service role. 4. Choose the Trust relationships tab, and then choose Edit trust relationship. 5. Edit the trust policy using the aws:SourceArn and aws:SourceAccount global condition context keys for Automation to prevent the confused deputy problem. 6. Choose Update Trust Policy to save your changes. (Optional) Add an Automation inline policy or customer managed policy to invoke other AWS services If you run an automation that invokes other AWS services by using an IAM service role, the service role must be configured with permission to invoke those services. This requirement applies to all AWS Automation runbooks (AWS-* runbooks) such as the AWS-ConfigureS3BucketLogging, AWS-CreateDynamoDBBackup, and AWS-RestartEC2Instance runbooks, to name a few. 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, to name a few, then you must configure the service role with permission to invoke those services. You can give permissions to other AWS services by adding an IAM inline policy or customer managed policy to the role. Automation 1082 AWS Systems Manager User Guide To embed an inline policy for a service role (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 role that you want to edit. 2. 3. 4. Choose the Permissions tab. 5. 6. 7. 8. In the Add permissions dropdown, choose Attach policies or Create inline policy. If you choose Attach policies, select the check box next to the policy you want to add and choose Add permissions. If you choose Create inline policy, choose the JSON tab. 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":[ { "Effect":"Allow", "Action":"ec2:CreateSnapshot", Automation 1083 AWS Systems Manager User Guide "Resource":"*" }, { "Effect":"Allow", "Action":"ec2:DescribeSnapshots", "Resource":"*" } ] } For details about the IAM policy language, see IAM JSON Policy Reference in the IAM User Guide. 9. When you're finished, choose Review policy. The Policy Validator reports any syntax errors. 10. On the Review policy page, enter a Name for 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. 11. After you create an inline policy, it's automatically embedded in your role. Task 2: Attach the iam:PassRole policy to your Automation role Use the following procedure to attach the iam:PassRole policy to your Automation service role. This allows the Automation service to pass the role to other services or Systems Manager tools when running automations. To attach the iam:PassRole policy to your Automation role 1. In the Summary page for the role you just created, choose the Permissions tab. 2. Choose Add inline policy. 3. On the Create policy page, choose the Visual editor tab. 4. Choose Service, and then choose IAM. 5. Choose Select actions. 6. In the Filter actions text box, type PassRole, and then choose the PassRole option. 7. Choose Resources. Verify that Specific is selected, and then choose Add ARN. 8. In the Specify ARN for role field, paste the Automation role ARN that you copied at the end of Task 1. The system populates the Account and Role name with path fields. Automation 1084 AWS Systems Manager Note User Guide If you want the Automation service role to attach an IAM instance profile role to an EC2 instance, then you must add the ARN of the IAM instance profile role. This allows the Automation service role to pass the IAM instance profile role to the target EC2 instance. 9. Choose Add. 10. Choose Review policy. 11. On the Review Policy page, enter a name and then choose Create Policy. Allowing Automation to adapt to your concurrency needs By default, Automation allows you to run up to
|
systems-manager-ug-340
|
systems-manager-ug.pdf
| 340 |
and Role name with path fields. Automation 1084 AWS Systems Manager Note User Guide If you want the Automation service role to attach an IAM instance profile role to an EC2 instance, then you must add the ARN of the IAM instance profile role. This allows the Automation service role to pass the IAM instance profile role to the target EC2 instance. 9. Choose Add. 10. Choose Review policy. 11. On the Review Policy page, enter a name and then choose Create Policy. Allowing Automation to adapt to your concurrency needs By default, Automation allows you to run up to 100 concurrent automations at a time. Automation also provides an optional setting that you can use to adjust your concurrency automation quota automatically. With this setting, your concurrency automation quota can accommodate up to 500 concurrent automations, depending on available resources. Note If your automation calls API operations, adaptively scaling to your targets can result in throttling exceptions. If recurring throttling exceptions occur when running automations with adaptive concurrency turned on, you might have to request quota increases for the API operation if available. To turn on adaptive concurrency using the AWS Management Console 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 Preferences tab, and then choose Edit. 4. Select the check box next to Enable adaptive concurrency. 5. Choose Save. Automation 1085 AWS Systems Manager User Guide To turn on adaptive concurrency using the command line • Open the AWS CLI or Tools for Windows PowerShell and run the following command to turn on adaptive concurrency for your account in the requesting Region. Linux & macOS aws ssm update-service-setting \ --setting-id /ssm/automation/enable-adaptive-concurrency \ --setting-value True Windows aws ssm update-service-setting ^ --setting-id /ssm/automation/enable-adaptive-concurrency ^ --setting-value True PowerShell Update-SSMServiceSetting ` -SettingId "/ssm/automation/enable-adaptive-concurrency" ` -SettingValue "True" Implement change controls for Automation By default, Automation allows you to use runbooks without date and time constraints. By integrating Automation with Change Calendar, you can implement change controls to all automations in your AWS account. With this setting, AWS Identity and Access Management (IAM) principals in your account can only run automations during the time periods allowed by your change calendar. To learn more about working with Change Calendar, see Working with Change Calendar. To turn on change controls (console) 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 Preferences tab, and then choose Edit. Automation 1086 AWS Systems Manager User Guide 4. 5. Select the check box next to Turn on Change Calendar integration. In the Choose a change calendar dropdown list, choose the change calendar that you want Automation to follow. 6. Choose Save. Run an automated operation powered by Systems Manager Automation When you run an automation, by default, the automation runs in the context of the user who initiated the automation. This means, for example, if your user has administrator permissions, then the automation runs with administrator permissions and full access to the resources being configured by the automation. As a security best practice, we recommend that you run automation by using an IAM service role that is known in this case as an assume role that is configured with the AmazonSSMAutomationRole managed policy. You might need to add additional IAM policies to your assume role to use various runbooks. Using an IAM service role to run automation is called delegated administration. When you use a service role, the automation is allowed to run against the AWS resources, but the user who ran the automation has restricted access (or no access) to those resources. For example, you can configure a service role and use it with Automation to restart one or more Amazon Elastic Compute Cloud (Amazon EC2) instances. Automation is a tool in AWS Systems Manager. The automation restarts the instances, but the service role doesn't give the user permission to access those instances. You can specify a service role at runtime when you run an automation, or you can create custom runbooks and specify the service role directly in the runbook. If you specify a service role, either at runtime or in a runbook, then the service runs in the context of the specified service role. If you don't specify a service role, then the system creates a temporary session in the context of the user and runs the automation. Note You must specify a service role for automation that you expect to run longer than 12 hours. If you start a long-running automation in the context of a user, the user's temporary session expires after 12 hours. Automation 1087 AWS Systems Manager User Guide Delegated administration ensures elevated security and control of your AWS resources. It also allows an enhanced auditing experience because actions are
|
systems-manager-ug-341
|
systems-manager-ug.pdf
| 341 |
service runs in the context of the specified service role. If you don't specify a service role, then the system creates a temporary session in the context of the user and runs the automation. Note You must specify a service role for automation that you expect to run longer than 12 hours. If you start a long-running automation in the context of a user, the user's temporary session expires after 12 hours. Automation 1087 AWS Systems Manager User Guide Delegated administration ensures elevated security and control of your AWS resources. It also allows an enhanced auditing experience because actions are being performed against your resources by a central service role instead of multiple IAM accounts. Before you begin Before you complete the following procedures, you must create the IAM service role and configure a trust relationship for Automation, a tool in AWS Systems Manager. For more information, see Task 1: Create a service role for Automation. The following procedures describe how to use the Systems Manager console or your preferred command line tool to run a simple automation. Running a simple automation (console) The following procedure describes how to use the Systems Manager console to run a simple automation. To run a simple automation 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 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. Automation 1088 AWS Systems Manager User Guide • 1 (Default) – Choose this option to run the first version of the document, which is the default. 5. Choose Next. 6. 7. In the Execution Mode 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 a 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. Note that 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. The console displays the status of the automation. If the automation fails to run, see Troubleshooting Systems Manager Automation. Running a simple automation (command line) The following procedure describes how to use the AWS CLI (on Linux or Windows) or AWS Tools for PowerShell to run a simple automation. To run a simple automation 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. Run the following command to start a simple automation. Replace each example resource placeholder with your own information. Linux & macOS aws ssm start-automation-execution \ --document-name runbook name \ --parameters runbook parameters Automation 1089 AWS Systems Manager Windows User Guide aws ssm start-automation-execution ^ --document-name runbook name ^ --parameters runbook parameters PowerShell Start-SSMAutomationExecution ` -DocumentName runbook name ` -Parameter runbook parameters Here is an example using the runbook AWS-RestartEC2Instance to restart the specified EC2 instance. Linux & macOS aws ssm start-automation-execution \ --document-name "AWS-RestartEC2Instance" \ --parameters "InstanceId=i-02573cafcfEXAMPLE" Windows aws ssm start-automation-execution ^ --document-name "AWS-RestartEC2Instance" ^ --parameters "InstanceId=i-02573cafcfEXAMPLE" PowerShell Start-SSMAutomationExecution ` -DocumentName AWS-RestartEC2Instance ` -Parameter @{"InstanceId"="i-02573cafcfEXAMPLE"} The system returns information like the following. Linux & macOS { Automation 1090 AWS Systems Manager User Guide "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0123456789ab" } Windows { "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0123456789ab" } PowerShell 4105a4fc-f944-11e6-9d32-0123456789ab 3. Run the following command to retrieve the status of the automation. Linux & macOS aws ssm describe-automation-executions \ --filter "Key=ExecutionId,Values=4105a4fc-f944-11e6-9d32-0123456789ab" Windows aws ssm describe-automation-executions ^ --filter "Key=ExecutionId,Values=4105a4fc-f944-11e6-9d32-0123456789ab" PowerShell Get-SSMAutomationExecutionList | ` Where {$_.AutomationExecutionId -eq "4105a4fc-f944-11e6-9d32-0123456789ab"} The system returns information like the following. Linux & macOS { "AutomationExecutionMetadataList": [ { "AutomationExecutionStatus": "InProgress", "CurrentStepName": "stopInstances", "Outputs": {}, Automation 1091 AWS Systems
|
systems-manager-ug-342
|
systems-manager-ug.pdf
| 342 |
"AWS-RestartEC2Instance" ^ --parameters "InstanceId=i-02573cafcfEXAMPLE" PowerShell Start-SSMAutomationExecution ` -DocumentName AWS-RestartEC2Instance ` -Parameter @{"InstanceId"="i-02573cafcfEXAMPLE"} The system returns information like the following. Linux & macOS { Automation 1090 AWS Systems Manager User Guide "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0123456789ab" } Windows { "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0123456789ab" } PowerShell 4105a4fc-f944-11e6-9d32-0123456789ab 3. Run the following command to retrieve the status of the automation. Linux & macOS aws ssm describe-automation-executions \ --filter "Key=ExecutionId,Values=4105a4fc-f944-11e6-9d32-0123456789ab" Windows aws ssm describe-automation-executions ^ --filter "Key=ExecutionId,Values=4105a4fc-f944-11e6-9d32-0123456789ab" PowerShell Get-SSMAutomationExecutionList | ` Where {$_.AutomationExecutionId -eq "4105a4fc-f944-11e6-9d32-0123456789ab"} The system returns information like the following. Linux & macOS { "AutomationExecutionMetadataList": [ { "AutomationExecutionStatus": "InProgress", "CurrentStepName": "stopInstances", "Outputs": {}, Automation 1091 AWS Systems Manager User Guide "DocumentName": "AWS-RestartEC2Instance", "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0123456789ab", "DocumentVersion": "1", "ResolvedTargets": { "ParameterValues": [], "Truncated": false }, "AutomationType": "Local", "Mode": "Auto", "ExecutionStartTime": 1564600648.159, "CurrentAction": "aws:changeInstanceState", "ExecutedBy": "arn:aws:sts::123456789012:assumed-role/Administrator/ Admin", "LogFile": "", "Targets": [] } ] } Windows { "AutomationExecutionMetadataList": [ { "AutomationExecutionStatus": "InProgress", "CurrentStepName": "stopInstances", "Outputs": {}, "DocumentName": "AWS-RestartEC2Instance", "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0123456789ab", "DocumentVersion": "1", "ResolvedTargets": { "ParameterValues": [], "Truncated": false }, "AutomationType": "Local", "Mode": "Auto", "ExecutionStartTime": 1564600648.159, "CurrentAction": "aws:changeInstanceState", "ExecutedBy": "arn:aws:sts::123456789012:assumed-role/Administrator/ Admin", "LogFile": "", "Targets": [] } Automation 1092 AWS Systems Manager ] } PowerShell User Guide AutomationExecutionId : 4105a4fc-f944-11e6-9d32-0123456789ab AutomationExecutionStatus : InProgress AutomationType : Local CurrentAction : aws:changeInstanceState CurrentStepName : startInstances DocumentName : AWS-RestartEC2Instance DocumentVersion : 1 ExecutedBy : arn:aws:sts::123456789012:assumed-role/ Administrator/Admin ExecutionEndTime : 1/1/0001 12:00:00 AM ExecutionStartTime : 7/31/2019 7:17:28 PM FailureMessage : LogFile : MaxConcurrency : MaxErrors : Mode : Auto Outputs : {} ParentAutomationExecutionId : ResolvedTargets : Amazon.SimpleSystemsManagement.Model.ResolvedTargets Target : TargetMaps : {} TargetParameterName : Targets : {} Run an automation that requires approvals The following procedures describe how to use the AWS Systems Manager console and AWS Command Line Interface (AWS CLI) to run an automation with approvals using simple execution. The automation uses the automation action aws:approve, which temporarily pauses the automation until the designated principals either approve or deny the action. The automation runs in the context of the current user. This means that you don't need to configure additional IAM permissions as long as you have permission to use the runbook, and any actions called by the runbook. If you have administrator permissions in IAM, then you already have permission to use this runbook. Automation 1093 AWS Systems Manager Before you begin User Guide In addition to the standard inputs required by the runbook, the aws:approve action requires the following two parameters: • A list of approvers. The list of approvers must contain at least one approver in the form of a user name or a user ARN. If multiple approvers are provided, a corresponding minimum approval count must also be specified within the runbook. • An Amazon Simple Notification Service (Amazon SNS) topic ARN. The Amazon SNS topic name must start with Automation. This procedure assumes that you have already created an Amazon SNS topic, which is required to deliver the approval request. For information, see Create a Topic in the Amazon Simple Notification Service Developer Guide. Running an automation with approvers (console) To run an automation with approvers The following procedure describes how to use the Systems Manager console to run an automation with approvers. 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 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: Automation 1094 AWS Systems Manager User Guide • 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. On the Execute automation document page, choose Simple execution. 7. In the Input parameters section, specify the required input parameters. For example, if you chose the AWS-StartEC2InstanceWithApproval runbook, then you must specify or choose instance IDs for the InstanceId parameter. In the Approvers section, specify the user names or user ARNs of approvers for the automation action. In the SNSTopicARN section, specify the SNS topic ARN to use for sending approval notification. The SNS topic name must start with Automation. 8.
|
systems-manager-ug-343
|
systems-manager-ug.pdf
| 343 |
Choose this option to run the first version of the document, which is the default. 5. Choose Next. 6. On the Execute automation document page, choose Simple execution. 7. In the Input parameters section, specify the required input parameters. For example, if you chose the AWS-StartEC2InstanceWithApproval runbook, then you must specify or choose instance IDs for the InstanceId parameter. In the Approvers section, specify the user names or user ARNs of approvers for the automation action. In the SNSTopicARN section, specify the SNS topic ARN to use for sending approval notification. The SNS topic name must start with Automation. 8. 9. 10. Optionally, you can choose an IAM service role from the AutomationAssumeRole list. If you're targeting more than 100 accounts and Regions, you must specify the AWS-SystemsManager- AutomationAdministrationRole. 11. Choose Execute automation. The specified approver receives an Amazon SNS notification with details to approve or reject the automation. This approval action is valid for 7 days from the date of issue and can be issued using the Systems Manager console or the AWS Command Line Interface (AWS CLI). If you chose to approve the automation, the automation continues to run the steps included in the specified runbook. The console displays the status of the automation. If the automation fails to run, see Troubleshooting Systems Manager Automation. To approve or deny an automation 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Automation, and then select the automation that was run in the previous procedure. Automation 1095 AWS Systems Manager User Guide 3. Choose Actions and then choose Approve/Deny. 4. Choose to Approve or Deny and optionally provide a comment. 5. Choose Submit. Running an automation with approvers (command line) The following procedure describes how to use the AWS CLI (on Linux or Windows) or AWS Tools for PowerShell to run an automation with approvers. To run an automation with approvers 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. Run the following command to run an automation with approvers. Replace each example resource placeholder with your own information. In the document name section, specify a runbook that includes the automation action, aws:approve. For Approvers, specify the user names or user ARNs of approvers for the action. For SNSTopic, specify the SNS topic ARN to use to send approval notification. The Amazon SNS topic name must start with Automation. Note The specific names of the parameter values for approvers and the SNS topic depend on the values specified within the runbook you choose. Linux & macOS aws ssm start-automation-execution \ --document-name "AWS-StartEC2InstanceWithApproval" \ --parameters "InstanceId=i-02573cafcfEXAMPLE,Approvers=arn:aws:iam::123456789012:role/ Administrator,SNSTopicArn=arn:aws:sns:region:123456789012:AutomationApproval" Automation 1096 AWS Systems Manager Windows User Guide aws ssm start-automation-execution ^ --document-name "AWS-StartEC2InstanceWithApproval" ^ --parameters "InstanceId=i-02573cafcfEXAMPLE,Approvers=arn:aws:iam::123456789012:role/ Administrator,SNSTopicArn=arn:aws:sns:region:123456789012:AutomationApproval" PowerShell Start-SSMAutomationExecution ` -DocumentName AWS-StartEC2InstanceWithApproval ` -Parameters @{ "InstanceId"="i-02573cafcfEXAMPLE" "Approvers"="arn:aws:iam::123456789012:role/Administrator" "SNSTopicArn"="arn:aws:sns:region:123456789012:AutomationApproval" } The system returns information like the following. Linux & macOS { "AutomationExecutionId": "df325c6d-b1b1-4aa0-8003-6cb7338213c6" } Windows { "AutomationExecutionId": "df325c6d-b1b1-4aa0-8003-6cb7338213c6" } PowerShell df325c6d-b1b1-4aa0-8003-6cb7338213c6 Automation 1097 AWS Systems Manager To approve an automation User Guide • Run the following command to approve an automation. Replace each example resource placeholder with your own information. Linux & macOS aws ssm send-automation-signal \ --automation-execution-id "df325c6d-b1b1-4aa0-8003-6cb7338213c6" \ --signal-type "Approve" \ --payload "Comment=your comments" Windows aws ssm send-automation-signal ^ --automation-execution-id "df325c6d-b1b1-4aa0-8003-6cb7338213c6" ^ --signal-type "Approve" ^ --payload "Comment=your comments" PowerShell Send-SSMAutomationSignal ` -AutomationExecutionId df325c6d-b1b1-4aa0-8003-6cb7338213c6 ` -SignalType Approve ` -Payload @{"Comment"="your comments"} There is no output if the command succeeds. To deny an automation • Run the following command to deny an automation. Replace each example resource placeholder with your own information. Linux & macOS aws ssm send-automation-signal \ --automation-execution-id "df325c6d-b1b1-4aa0-8003-6cb7338213c6" \ --signal-type "Deny" \ --payload "Comment=your comments" Automation 1098 AWS Systems Manager Windows User Guide aws ssm send-automation-signal ^ --automation-execution-id "df325c6d-b1b1-4aa0-8003-6cb7338213c6" ^ --signal-type "Deny" ^ --payload "Comment=your comments" PowerShell Send-SSMAutomationSignal ` -AutomationExecutionId df325c6d-b1b1-4aa0-8003-6cb7338213c6 ` -SignalType Deny ` -Payload @{"Comment"="your comments"} There is no output if the command succeeds. Run automated operations at scale With AWS Systems Manager Automation, you can run automations on a fleet of AWS resources by using targets. Additionally, you can control the deployment of the automation across your fleet by specifying a concurrency value and an error threshold. The concurrency and error threshold features are collectively called rate controls. The concurrency value determines how many resources are allowed to run the automation simultaneously. Automation also provides an adaptive concurrency mode you can opt in to. Adaptive concurrency automatically scales your automation quota from 100 concurrently running automations up to 500. An error threshold determines how many automations are allowed to fail before Systems Manager stops sending the automation to other resources. For more information about concurrency and error thresholds, see Control automations at
|
systems-manager-ug-344
|
systems-manager-ug.pdf
| 344 |
of the automation across your fleet by specifying a concurrency value and an error threshold. The concurrency and error threshold features are collectively called rate controls. The concurrency value determines how many resources are allowed to run the automation simultaneously. Automation also provides an adaptive concurrency mode you can opt in to. Adaptive concurrency automatically scales your automation quota from 100 concurrently running automations up to 500. An error threshold determines how many automations are allowed to fail before Systems Manager stops sending the automation to other resources. For more information about concurrency and error thresholds, see Control automations at scale. For more information about targets, see Mapping targets for an automation. The following procedures show you how to turn on adaptive concurrency, and how to run an automation with targets and rate controls by using the Systems Manager console and AWS Command Line Interface (AWS CLI). Automation 1099 AWS Systems Manager User Guide Running an automation with targets and rate controls (console) The following procedure describes how to use the Systems Manager console to run an automation with targets and rate controls. To run an automation with targets and rate controls 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 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 Execution Mode section, choose Rate Control. You must use this mode or Multi- account and Region if you want to use targets and rate controls. In the Targets section, choose how you want to target the AWS resources where you want to run the Automation. These options are required. a. Use the Parameter list to choose a parameter. The items in the Parameter list are determined by the parameters in the Automation runbook that you selected at the start Automation 1100 AWS Systems Manager User Guide of this procedure. By choosing a parameter you define the type of resource on which the Automation workflow runs. b. Use the Targets list to choose how you want to target resources. i. ii. iii. iv. If you chose to target resources by using parameter values, then enter the parameter value for the parameter you chose in the Input parameters section. If you chose to target resources by using AWS Resource Groups, then choose the name of the group from the Resource Group list. If you chose to target resources by using tags, then enter the tag key and (optionally) the tag value in the fields provided. Choose Add. If you want to run an Automation runbook on all instances in the current AWS account and AWS Region, then choose All instances. 8. In the Input parameters section, specify the required inputs. Optionally, you can choose an IAM service role from the AutomationAssumeRole list. Note You might not need to choose some of the options in the Input parameters section. This is because you targeted resources by using tags or a resource group. For example, if you chose the AWS-RestartEC2Instance runbook, then you don't need to specify or choose instance IDs in the Input parameters section. The Automation execution locates the instances to restart by using the tags or resource group you specified. 9. Use the options in the Rate control section to restrict the number of AWS resources that can run the Automation within each account-Region pair. In the Concurrency section, choose an option: • Choose targets to enter an absolute number of targets that can run the Automation workflow simultaneously. • Choose percentage to enter a percentage of the target set that can run the Automation workflow simultaneously. 10. In the Error threshold section, choose an option: • Choose errors to enter an absolute number of errors allowed before Automation stops sending the workflow to other
|
systems-manager-ug-345
|
systems-manager-ug.pdf
| 345 |
or resource group you specified. 9. Use the options in the Rate control section to restrict the number of AWS resources that can run the Automation within each account-Region pair. In the Concurrency section, choose an option: • Choose targets to enter an absolute number of targets that can run the Automation workflow simultaneously. • Choose percentage to enter a percentage of the target set that can run the Automation workflow simultaneously. 10. In the Error threshold section, choose an option: • Choose errors to enter an absolute number of errors allowed before Automation stops sending the workflow to other resources. Automation 1101 AWS Systems Manager User Guide • Choose percentage to enter a percentage of errors allowed before Automation stops sending the workflow to other resources. 11. (Optional) Choose a 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. Note that if your alarm activates, the automation is stopped. If you use AWS CloudTrail, you will see the API call in your trail. 12. Choose Execute. To view automations started by your rate control automation, in the navigation pane, choose Automation, and then select Show child automations. Running an automation with targets and rate controls (command line) The following procedure describes how to use the AWS CLI (on Linux or Windows) or AWS Tools for PowerShell to run an automation with targets and rate controls. To run an automation with targets and rate controls 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. Run the following command to view a list of documents. Linux & macOS aws ssm list-documents Windows aws ssm list-documents PowerShell Get-SSMDocumentList Automation 1102 AWS Systems Manager User Guide Note the name of the runbook that you want to use. 3. Run the following command to view details about the runbook. Replace the runbook name with the name of the runbook whose details you want to view. Also, note a parameter name (for example, InstanceId) that you want to use for the --target-parameter-name option. This parameter determines the type of resource on which the automation runs. Linux & macOS aws ssm describe-document \ --name runbook name Windows aws ssm describe-document ^ --name runbook name PowerShell Get-SSMDocumentDescription ` -Name runbook name 4. Create a command that uses the targets and rate control options you want to run. Replace each example resource placeholder with your own information. Targeting using tags Linux & macOS aws ssm start-automation-execution \ --document-name runbook name \ --targets Key=tag:key name,Values=value \ --target-parameter-name parameter name \ --parameters "input parameter name=input parameter value,input parameter 2 name=input parameter 2 value" \ --max-concurrency 10 \ --max-errors 25% Automation 1103 AWS Systems Manager Windows User Guide aws ssm start-automation-execution ^ --document-name runbook name ^ --targets Key=tag:key name,Values=value ^ --target-parameter-name parameter name ^ --parameters "input parameter name=input parameter value,input parameter 2 name=input parameter 2 value" ^ --max-concurrency 10 ^ --max-errors 25% PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "tag:key name" $Targets.Values = "value" Start-SSMAutomationExecution ` DocumentName "runbook name" ` -Targets $Targets ` -TargetParameterName "parameter name" ` -Parameter @{"input parameter name"="input parameter value";"input parameter 2 name"="input parameter 2 value"} ` -MaxConcurrency "10" ` -MaxError "25%" Targeting using parameter values Linux & macOS aws ssm start-automation-execution \ --document-name runbook name \ --targets Key=ParameterValues,Values=value,value 2,value 3 \ --target-parameter-name parameter name \ --parameters "input parameter name=input parameter value" \ --max-concurrency 10 \ --max-errors 25% Automation 1104 AWS Systems Manager Windows User Guide aws ssm start-automation-execution ^ --document-name runbook name ^ --targets Key=ParameterValues,Values=value,value 2,value 3 ^ --target-parameter-name parameter name ^ --parameters "input parameter name=input parameter value" ^ --max-concurrency 10 ^ --max-errors 25% PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "ParameterValues" $Targets.Values = "value","value 2","value 3" Start-SSMAutomationExecution ` -DocumentName "runbook name" ` -Targets $Targets ` -TargetParameterName "parameter name" ` -Parameter @{"input parameter name"="input parameter value"} ` -MaxConcurrency "10" ` -MaxError "25%" Targeting using AWS Resource Groups Linux & macOS aws ssm start-automation-execution \ --document-name runbook name \ --targets Key=ResourceGroup,Values=Resource group nname \ --target-parameter-name parameter name \ --parameters "input parameter name=input parameter value" \ --max-concurrency 10 \ --max-errors 25% Windows aws ssm start-automation-execution ^ --document-name runbook name ^ Automation 1105 AWS Systems Manager User Guide --targets Key=ResourceGroup,Values=Resource group name ^ --target-parameter-name parameter name ^ --parameters "input parameter name=input parameter value" ^ --max-concurrency 10 ^ --max-errors 25% PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "ResourceGroup" $Targets.Values = "Resource group name" Start-SSMAutomationExecution ` -DocumentName "runbook name" ` -Targets $Targets ` -TargetParameterName "parameter name" ` -Parameter @{"input parameter name"="input parameter value"} ` -MaxConcurrency "10" ` -MaxError "25%" Targeting
|
systems-manager-ug-346
|
systems-manager-ug.pdf
| 346 |
runbook name \ --targets Key=ResourceGroup,Values=Resource group nname \ --target-parameter-name parameter name \ --parameters "input parameter name=input parameter value" \ --max-concurrency 10 \ --max-errors 25% Windows aws ssm start-automation-execution ^ --document-name runbook name ^ Automation 1105 AWS Systems Manager User Guide --targets Key=ResourceGroup,Values=Resource group name ^ --target-parameter-name parameter name ^ --parameters "input parameter name=input parameter value" ^ --max-concurrency 10 ^ --max-errors 25% PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "ResourceGroup" $Targets.Values = "Resource group name" Start-SSMAutomationExecution ` -DocumentName "runbook name" ` -Targets $Targets ` -TargetParameterName "parameter name" ` -Parameter @{"input parameter name"="input parameter value"} ` -MaxConcurrency "10" ` -MaxError "25%" Targeting all Amazon EC2 instances in the current AWS account and AWS Region Linux & macOS aws ssm start-automation-execution \ --document-name runbook name \ --targets "Key=AWS::EC2::Instance,Values=*" \ --target-parameter-name instanceId \ --parameters "input parameter name=input parameter value" \ --max-concurrency 10 \ --max-errors 25% Windows aws ssm start-automation-execution ^ --document-name runbook name ^ --targets Key=AWS::EC2::Instance,Values=* ^ --target-parameter-name instanceId ^ --parameters "input parameter name=input parameter value" ^ --max-concurrency 10 ^ Automation 1106 AWS Systems Manager User Guide --max-errors 25% PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "AWS::EC2::Instance" $Targets.Values = "*" Start-SSMAutomationExecution ` -DocumentName "runbook name" ` -Targets $Targets ` -TargetParameterName "instanceId" ` -Parameter @{"input parameter name"="input parameter value"} ` -MaxConcurrency "10" ` -MaxError "25%" The command returns an execution ID. Copy this ID to the clipboard. You can use this ID to view the status of the automation. Linux & macOS { "AutomationExecutionId": "a4a3c0e9-7efd-462a-8594-01234EXAMPLE" } Windows { "AutomationExecutionId": "a4a3c0e9-7efd-462a-8594-01234EXAMPLE" } PowerShell a4a3c0e9-7efd-462a-8594-01234EXAMPLE 5. Run the following command to view the automation. Replace each automation execution ID with your own information. Automation 1107 AWS Systems Manager Linux & macOS User Guide aws ssm describe-automation-executions \ --filter Key=ExecutionId,Values=automation execution ID Windows aws ssm describe-automation-executions ^ --filter Key=ExecutionId,Values=automation execution ID PowerShell Get-SSMAutomationExecutionList | ` Where {$_.AutomationExecutionId -eq "automation execution ID"} 6. To view details about the automation progress, run the following command. Replace each automation execution ID with your own information. Linux & macOS aws ssm get-automation-execution \ --automation-execution-id automation execution ID Windows aws ssm get-automation-execution ^ --automation-execution-id automation execution ID PowerShell Get-SSMAutomationExecution ` -AutomationExecutionId automation execution ID The system returns information like the following. Linux & macOS { Automation 1108 AWS Systems Manager User Guide "AutomationExecution": { "StepExecutionsTruncated": false, "AutomationExecutionStatus": "Success", "MaxConcurrency": "1", "Parameters": {}, "MaxErrors": "1", "Outputs": {}, "DocumentName": "AWS-StopEC2Instance", "AutomationExecutionId": "a4a3c0e9-7efd-462a-8594-01234EXAMPLE", "ResolvedTargets": { "ParameterValues": [ "i-02573cafcfEXAMPLE" ], "Truncated": false }, "ExecutionEndTime": 1564681619.915, "Targets": [ { "Values": [ "DEV" ], "Key": "tag:ENV" } ], "DocumentVersion": "1", "ExecutionStartTime": 1564681576.09, "ExecutedBy": "arn:aws:sts::123456789012:assumed-role/Administrator/ Admin", "StepExecutions": [ { "Inputs": { "InstanceId": "i-02573cafcfEXAMPLE" }, "Outputs": {}, "StepName": "i-02573cafcfEXAMPLE", "ExecutionEndTime": 1564681619.093, "StepExecutionId": "86c7b811-3896-4b78-b897-01234EXAMPLE", "ExecutionStartTime": 1564681576.836, "Action": "aws:executeAutomation", "StepStatus": "Success" } ], "TargetParameterName": "InstanceId", "Mode": "Auto" Automation 1109 AWS Systems Manager User Guide } } Windows { "AutomationExecution": { "StepExecutionsTruncated": false, "AutomationExecutionStatus": "Success", "MaxConcurrency": "1", "Parameters": {}, "MaxErrors": "1", "Outputs": {}, "DocumentName": "AWS-StopEC2Instance", "AutomationExecutionId": "a4a3c0e9-7efd-462a-8594-01234EXAMPLE", "ResolvedTargets": { "ParameterValues": [ "i-02573cafcfEXAMPLE" ], "Truncated": false }, "ExecutionEndTime": 1564681619.915, "Targets": [ { "Values": [ "DEV" ], "Key": "tag:ENV" } ], "DocumentVersion": "1", "ExecutionStartTime": 1564681576.09, "ExecutedBy": "arn:aws:sts::123456789012:assumed-role/Administrator/ Admin", "StepExecutions": [ { "Inputs": { "InstanceId": "i-02573cafcfEXAMPLE" }, "Outputs": {}, "StepName": "i-02573cafcfEXAMPLE", "ExecutionEndTime": 1564681619.093, "StepExecutionId": "86c7b811-3896-4b78-b897-01234EXAMPLE", Automation 1110 AWS Systems Manager User Guide "ExecutionStartTime": 1564681576.836, "Action": "aws:executeAutomation", "StepStatus": "Success" } ], "TargetParameterName": "InstanceId", "Mode": "Auto" } } PowerShell AutomationExecutionId : a4a3c0e9-7efd-462a-8594-01234EXAMPLE AutomationExecutionStatus : Success CurrentAction : CurrentStepName : DocumentName : AWS-StopEC2Instance DocumentVersion : 1 ExecutedBy : arn:aws:sts::123456789012:assumed-role/ Administrator/Admin ExecutionEndTime : 8/1/2019 5:46:59 PM ExecutionStartTime : 8/1/2019 5:46:16 PM FailureMessage : MaxConcurrency : 1 MaxErrors : 1 Mode : Auto Outputs : {} Parameters : {} ParentAutomationExecutionId : ProgressCounters : ResolvedTargets : Amazon.SimpleSystemsManagement.Model.ResolvedTargets StepExecutions : {i-02573cafcfEXAMPLE} StepExecutionsTruncated : False Target : TargetLocations : {} TargetMaps : {} TargetParameterName : InstanceId Targets : {tag:Name} Automation 1111 AWS Systems Manager Note User Guide You can also monitor the status of the automation in the console. In the Automation executions list, choose the automation you just ran and then choose the Execution steps tab. This tab shows the status of the automation actions. Mapping targets for an automation Use the Targets parameter to quickly define which resources are targeted by an automation. For example, if you want to run an automation that restarts your managed instances, then instead of manually selecting dozens of instance IDs in the console or typing them in a command, you can target instances by specifying Amazon Elastic Compute Cloud (Amazon EC2) tags with the Targets parameter. When you run an automation that uses a target, AWS Systems Manager creates a child automation for each target. For example, if you target Amazon Elastic Block Store (Amazon EBS) volumes by specifying tags, and those tags resolve to 100 Amazon EBS volumes, then Systems Manager creates 100 child automations. The parent automation is complete when all child automations reach a final state. Note Any input parameters that you specify at
|
systems-manager-ug-347
|
systems-manager-ug.pdf
| 347 |
of instance IDs in the console or typing them in a command, you can target instances by specifying Amazon Elastic Compute Cloud (Amazon EC2) tags with the Targets parameter. When you run an automation that uses a target, AWS Systems Manager creates a child automation for each target. For example, if you target Amazon Elastic Block Store (Amazon EBS) volumes by specifying tags, and those tags resolve to 100 Amazon EBS volumes, then Systems Manager creates 100 child automations. The parent automation is complete when all child automations reach a final state. Note Any input parameters that you specify at runtime (either in the Input parameters section of the console or by using the parameters option from the command line) are automatically processed by all child automations. You can target resources for an automation by using tags, Resource Groups,and parameter values. Additionally, you can use the TargetMaps option to target multiple parameter values from the command line or a file. The following section describes each of these targeting options in more detail. Targeting a tag You can specify a single tag as the target of an automation. Many AWS resources support tags, including Amazon Elastic Compute Cloud (Amazon EC2) and Amazon Relational Database Service (Amazon RDS) instances, Amazon Elastic Block Store (Amazon EBS) volumes and snapshots, Automation 1112 AWS Systems Manager User Guide Resource Groups,and Amazon Simple Storage Service (Amazon S3) buckets, to name a few. You can quickly run automation on your AWS resources by targeting a tag. A tag is a key-value pair, such as Operating_System:Linux or Department:Finance. If you assign a specific name to a resource, then you can also use the word "Name" as a key, and the name of the resource as the value. When you specify a tag as the target for an automation, you also specify a target parameter. The target parameter uses the TargetParameterName option. By choosing a target parameter, you define the type of resource on which the automation runs. The target parameter you specify with the tag must be a valid parameter defined in the runbook. For example, if you want to target dozens of EC2 instances by using tags, then choose the InstanceId target parameter. By choosing this parameter, you define instances as the resource type for the automation. When creating a custom runbook you must specify the Target type as /AWS::EC2::Instance to ensure only instances are used. Otherwise, all resources with the same tag will be targeted. When targeting instances with a tag, terminated instances might be included. The following screenshot uses the AWS-DetachEBSVolume runbook. The logical target parameter is VolumeId. The AWS-DetachEBSVolume runbook also includes a special property called Target type, which is set to /AWS::EC2::Volume. This means that if the tag-key pair Finance:TestEnv returns different types of resources (for example, EC2 instances, Amazon EBS volumes, Amazon EBS snapshots) then only Amazon EBS volumes will be used. Important Target parameter names are case sensitive. If you run automations by using either the AWS Command Line Interface (AWS CLI) or AWS Tools for Windows PowerShell, then you must Automation 1113 AWS Systems Manager User Guide enter the target parameter name exactly as it's defined in the runbook. If you don't, the system returns an InvalidAutomationExecutionParametersException error. You can use the DescribeDocument API operation to see information about the available target parameters in a specific runbook. Following is an example AWS CLI command that provides information about the AWS-DeleteSnapshot document. aws ssm describe-document \ --name AWS-DeleteSnapshot Here are some example AWS CLI commands that target resources by using a tag. Example 1: Targeting a tag using a key-value pair to restart Amazon EC2 instances This example restarts all Amazon EC2 instances that are tagged with a key of Department and a value of HumanResources. The target parameter uses the InstanceId parameter from the runbook. The example uses an additional parameter to run the automation by using an Automation service role (also called an assume role). aws ssm start-automation-execution \ --document-name AWS-RestartEC2Instance \ --targets Key=tag:Department,Values=HumanResources \ --target-parameter-name InstanceId \ --parameters "AutomationAssumeRole=arn:aws:iam::111122223333:role/ AutomationServiceRole" Example 2: Targeting a tag using a key-value pair to delete Amazon EBS snapshots The following example uses the AWS-DeleteSnapshot runbook to delete all snapshots with a key of Name and a value of January2018Backups. The target parameter uses the VolumeId parameter. aws ssm start-automation-execution \ --document-name AWS-DeleteSnapshot \ --targets Key=tag:Name,Values=January2018Backups \ --target-parameter-name VolumeId Targeting AWS Resource Groups You can specify a single AWS resource group as the target of an automation. Systems Manager creates a child automation for every object in the target Resource Group. Automation 1114 AWS Systems Manager User Guide For example, say that one of your Resource Groups is named PatchedAMIs. This Resource Group includes a list of 25 Windows Amazon Machine Images (AMIs) that are routinely patched. If you run an automation that
|
systems-manager-ug-348
|
systems-manager-ug.pdf
| 348 |
of Name and a value of January2018Backups. The target parameter uses the VolumeId parameter. aws ssm start-automation-execution \ --document-name AWS-DeleteSnapshot \ --targets Key=tag:Name,Values=January2018Backups \ --target-parameter-name VolumeId Targeting AWS Resource Groups You can specify a single AWS resource group as the target of an automation. Systems Manager creates a child automation for every object in the target Resource Group. Automation 1114 AWS Systems Manager User Guide For example, say that one of your Resource Groups is named PatchedAMIs. This Resource Group includes a list of 25 Windows Amazon Machine Images (AMIs) that are routinely patched. If you run an automation that uses the AWS-CreateManagedWindowsInstance runbook and target this Resource Group, then Systems Manager creates a child automation for each of the 25 AMIs. This means, that by targeting the PatchedAMIs Resource Group, the automation creates 25 instances from a list of patched AMIs. The parent automation is complete when all child automations complete processing or reach a final state. The following AWS CLI command applies to the PatchAMIs Resource Group example. The command takes the AmiId parameter for the --target-parameter-name option. The command doesn't include an additional parameter defining which type of instance to create from each AMI. The AWS- CreateManagedWindowsInstance runbook defaults to the t2.medium instance type, so this command would create 25 t2.medium Amazon EC2 instances for Windows Server. aws ssm start-automation-execution \ --document-name AWS-CreateManagedWindowsInstance \ --targets Key=ResourceGroup,Values=PatchedAMIs \ --target-parameter-name AmiId The following console example uses a Resource Group called t2-micro-instances. Targeting parameter values You can also target a parameter value. You enter ParameterValues as the key and then enter the specific resource value where you want the automation to run. If you specify multiple values, Systems Manager runs a child automation on each value specified. Automation 1115 AWS Systems Manager User Guide For example, say that your runbook includes an InstanceID parameter. If you target the values of the InstanceID parameter when you run the Automation, then Systems Manager runs a child automation for each instance ID value specified. The parent automation is complete when the automation finishes running each specified instance, or if the automation fails. You can target a maximum of 50 parameter values. The following example uses the AWS-CreateImage runbook. The target parameter name specified is InstanceId. The key uses ParameterValues. The values are two Amazon EC2 instance IDs. This command creates an automation for each instance, which produces an AMI from each instance. aws ssm start-automation-execution --document-name AWS-CreateImage \ --target-parameter-name InstanceId \ --targets Key=ParameterValues,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE Note AutomationAssumeRole isn't a valid parameter. Don’t choose this item when running automation that target a parameter value. Targeting parameter value maps The TargetMaps option expands your ability to target ParameterValues. You can enter an array of parameter values by using TargetMaps at the command line. You can specify a maximum of 50 parameter values at the command line. If you want to run commands that specify more than 50 parameter values, then you can enter the values in a JSON file. You can then call the file from the command line. Note The TargetMaps option isn't supported in the console. Use the following format to specify multiple parameter values by using the TargetMaps option in a command. Replace each example resource placeholder with your own information. aws ssm start-automation-execution \ --document-name runbook name \ Automation 1116 AWS Systems Manager User Guide --target-maps “parameter=value, parameter 2=value, parameter 3=value” “parameter 4=value, parameter 5=value, parameter 6=value” If you want to enter more than 50 parameter values for the TargetMaps option, then specify the values in a file by using the following JSON format. Using a JSON file also improves readability when providing multiple parameter values. [ {“parameter”: "value", “parameter 2”: "value", “parameter 3”: "value"}, {“parameter 4”: "value", “parameter 5”: "value", "parameter 6": "value"} ] Save the file with a .json file extension. You can call the file by using the following command. Replace each example resource placeholder with your own information. aws ssm start-automation-execution \ --document-name runbook name \ –-parameters input parameters \ --target-maps path to file/file name.json You can also download the file from an Amazon Simple Storage Service (Amazon S3) bucket, as long as you have permission to read data from the bucket. Use the following command format. Replace each example resource placeholder with your own information. aws ssm start-automation-execution \ --document-name runbook name \ --target-maps http://amzn-s3-demo-bucket.s3.amazonaws.com/file_name.json Here is an example scenario to help you understand the TargetMaps option. In this scenario, a user wants to create Amazon EC2 instances of different types from different AMIs. To perform this task, the user creates a runbook named AMI_Testing. This runbook defines two input parameters: instanceType and imageId. { "description": "AMI Testing", "schemaVersion": "0.3", Automation 1117 AWS Systems Manager User Guide "assumeRole": "{{assumeRole}}", "parameters": { "assumeRole": { "type": "String", "description": "Role under which to run the automation", "default": "" }, "instanceType": {
|
systems-manager-ug-349
|
systems-manager-ug.pdf
| 349 |
example resource placeholder with your own information. aws ssm start-automation-execution \ --document-name runbook name \ --target-maps http://amzn-s3-demo-bucket.s3.amazonaws.com/file_name.json Here is an example scenario to help you understand the TargetMaps option. In this scenario, a user wants to create Amazon EC2 instances of different types from different AMIs. To perform this task, the user creates a runbook named AMI_Testing. This runbook defines two input parameters: instanceType and imageId. { "description": "AMI Testing", "schemaVersion": "0.3", Automation 1117 AWS Systems Manager User Guide "assumeRole": "{{assumeRole}}", "parameters": { "assumeRole": { "type": "String", "description": "Role under which to run the automation", "default": "" }, "instanceType": { "type": "String", "description": "Type of EC2 Instance to launch for this test" }, "imageId": { "type": "String", "description": "Source AMI id from which to run instance" } }, "mainSteps": [ { "name": "runInstances", "action": "aws:runInstances", "maxAttempts": 1, "onFailure": "Abort", "inputs": { "ImageId": "{{imageId}}", "InstanceType": "{{instanceType}}", "MinInstanceCount": 1, "MaxInstanceCount": 1 } } ], "outputs": [ "runInstances.InstanceIds" ] } The user then specifies the following target parameter values in a file named AMI_instance_types.json. [ { "instanceType" : ["t2.micro"], "imageId" : ["ami-b70554c8"] }, Automation 1118 User Guide AWS Systems Manager { "instanceType" : ["t2.small"], "imageId" : ["ami-b70554c8"] }, { "instanceType" : ["t2.medium"], "imageId" : ["ami-cfe4b2b0"] }, { "instanceType" : ["t2.medium"], "imageId" : ["ami-cfe4b2b0"] }, { "instanceType" : ["t2.medium"], "imageId" : ["ami-cfe4b2b0"] } ] The user can run the automation and create the five EC2 instances defined in AMI_instance_types.json by running the following command. aws ssm start-automation-execution \ --document-name AMI_Testing \ --target-parameter-name imageId \ --target-maps file:///home/TestUser/workspace/runinstances/AMI_instance_types.json Targeting all Amazon EC2 instances You can run an automation on all Amazon EC2 instances in the current AWS account and AWS Region by choosing All instances in the Targets list. For example, if you want to restart all Amazon EC2 instances your AWS account and the current AWS Region, you can choose the AWS- RestartEC2Instance runbook and then choose All instances from the Targets list. Automation 1119 AWS Systems Manager User Guide After you choose All instances, Systems Manager populates the Instance field with an asterisk (*) and makes the field unavailable for changes (the field is grayed out). Systems Manager also makes the InstanceId field in the Input parameters field unavailable for changes. Making these fields unavailable for changes is expected behavior if you choose to target all instances. Control automations at scale You can control the deployment of an automation across a fleet of AWS resources by specifying a concurrency value and an error threshold. Concurrency and error threshold are collectively called rate controls. Concurrency Use Concurrency to specify how many resources are allowed to run an automation simultaneously. Concurrency helps to limit the impact or downtime on your resources when processing an automation. You can specify either an absolute number of resources, for example 20, or a percentage of the target set, for example 10%. The queueing system delivers the automation to a single resource and waits until the initial invocation is complete before sending the automation to two more resources. The system exponentially sends the automation to more resources until the concurrency value is met. Error thresholds Use an error threshold to specify how many automations are allowed to fail before AWS Systems Manager stops sending the automation to other resources. You can specify either an absolute number of errors, for example 10, or a percentage of the target set, for example 10%. Automation 1120 AWS Systems Manager User Guide If you specify an absolute number of 3 errors, for example, the system stops running the automation when the fourth error is received. If you specify 0, then the system stops running the automation on additional targets after the first error result is returned. If you send an automation to, for example, 50 instances and set the error threshold to 10%, then the system stops sending the command to additional instances when the fifth error is received. Invocations that are already running an automation when an error threshold is reached are allowed to be completed, but some of these automations might fail as well. If you need to ensure that there won’t be more errors than the number specified for the error threshold, then set the Concurrency value to 1 so that automations proceed one at a time. Running automations in multiple AWS Regions and accounts You can run AWS Systems Manager automations across multiple AWS Regions and AWS accounts or AWS Organizations organizational units (OUs) from a central account. Automation is a tool in AWS Systems Manager. Running automations in multiple Regions and accounts or OUs reduces the time required to administer your AWS resources while enhancing the security of your computing environment. For example, you can do the following by using automation runbooks: • Implement patching and security updates centrally. • Remediate compliance drift on VPC configurations or Amazon S3 bucket
|
systems-manager-ug-350
|
systems-manager-ug.pdf
| 350 |
proceed one at a time. Running automations in multiple AWS Regions and accounts You can run AWS Systems Manager automations across multiple AWS Regions and AWS accounts or AWS Organizations organizational units (OUs) from a central account. Automation is a tool in AWS Systems Manager. Running automations in multiple Regions and accounts or OUs reduces the time required to administer your AWS resources while enhancing the security of your computing environment. For example, you can do the following by using automation runbooks: • Implement patching and security updates centrally. • Remediate compliance drift on VPC configurations or Amazon S3 bucket policies. • Manage resources, such as Amazon Elastic Compute Cloud (Amazon EC2) EC2 instances, at scale. The following diagram shows an example of a user who is running the AWS- RestartEC2Instances runbook in multiple Regions and accounts from a central account. The automation locates the instances by using the specified tags in the targeted Regions and accounts. Automation 1121 AWS Systems Manager User Guide Choose a central account for Automation If you want to run automations across OUs, the central account must have permissions to list all of the accounts in the OUs. This is only possible from a delegated administrator account, or the management account of the organization. We recommend that you follow AWS Organizations best practices and use a delegated administrator account. For more information about AWS Organizations best practices, see Best practices for the management account in the AWS Organizations User Guide. To create a delegated administrator account for Systems Manager, you can use the register-delegated-administrator command with the AWS CLI as shown in the following example. aws organizations register-delegated-administrator \ --account-id delegated admin account ID \ --service-principal ssm.amazonaws.com If you want to run automations across multiple accounts that are not managed by AWS Organizations, we recommend creating a dedicated account for automation management. Running all cross-account automations from a dedicated account simplifies IAM permissions management, troubleshooting efforts, and creates a layer of separation between operations and administration. Automation 1122 AWS Systems Manager User Guide This approach is also recommended if you use AWS Organizations, but only want to target individual accounts and not OUs. How running automations works Running automations across multiple Regions and accounts or OUs works as follows: 1. Sign in to the account that you want to configure as the Automation central account. 2. Use the Setting up management account permissions for multi-Region and multi-account automation procedure in this topic to create the following IAM roles: • AWS-SystemsManager-AutomationAdministrationRole - This role gives the user permission to run automations in multiple accounts and OUs. • AWS-SystemsManager-AutomationExecutionRole - This role gives the user permission to run automations in the targeted accounts. 3. Choose the runbook, Regions, and accounts or OUs where you want to run the automation. Note Be sure that the target OU contains the desired accounts. If you choose a custom runbook, the runbook must be shared with all of the target accounts. For information about sharing runbooks, see Sharing SSM documents. For information about using shared runbooks, see Using shared SSM documents. 4. Run the automation. Note When running automations across multiple Regions, accounts, or OUs, the automation you run from the primary account starts child automations in each of the target accounts. The automation in the primary account contains aws:executeAutomation steps for each of the target accounts. 5. Use the GetAutomationExecution, DescribeAutomationStepExecutions, and DescribeAutomationExecutions API operations from the AWS Systems Manager console or the AWS CLI to monitor automation progress. The output of the steps for the automation in your primary account will be the AutomationExecutionId of the child automations. To view the output of the child automations created in your target accounts, be sure to specify the appropriate account, Region, and AutomationExecutionId in your request. Automation 1123 AWS Systems Manager User Guide Setting up management account permissions for multi-Region and multi-account automation Use the following procedure to create the required IAM roles for Systems Manager Automation multi-Region and multi-account automation by using AWS CloudFormation. This procedure describes how to create the AWS-SystemsManager-AutomationAdministrationRole role. You only need to create this role in the Automation central account. This procedure also describes how to create the AWS-SystemsManager-AutomationExecutionRole role. You must create this role in every account that you want to target to run multi-Region and multi- account automations. We recommend using AWS CloudFormation StackSets to create the AWS- SystemsManager-AutomationExecutionRole role in the accounts you want to target to run multi-Region and multi-account automations. To create the required IAM administration role for multi-Region and multi-account automations by using AWS CloudFormation 1. Download and unzip the AWS-SystemsManager-AutomationAdministrationRole.zip. Or, if your accounts are managed by AWS Organizations AWS-SystemsManager- AutomationAdministrationRole (org).zip. This file contains the AWS- SystemsManager-AutomationAdministrationRole.yaml AWS CloudFormation template file. 2. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 3. Choose Create stack. 4. In the Specify
|
systems-manager-ug-351
|
systems-manager-ug.pdf
| 351 |
in every account that you want to target to run multi-Region and multi- account automations. We recommend using AWS CloudFormation StackSets to create the AWS- SystemsManager-AutomationExecutionRole role in the accounts you want to target to run multi-Region and multi-account automations. To create the required IAM administration role for multi-Region and multi-account automations by using AWS CloudFormation 1. Download and unzip the AWS-SystemsManager-AutomationAdministrationRole.zip. Or, if your accounts are managed by AWS Organizations AWS-SystemsManager- AutomationAdministrationRole (org).zip. This file contains the AWS- SystemsManager-AutomationAdministrationRole.yaml AWS CloudFormation template file. 2. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 3. Choose Create stack. 4. In the Specify template section, choose Upload a template. 5. Choose Choose file, and then choose the AWS-SystemsManager- AutomationAdministrationRole.yaml AWS CloudFormation template file. 6. Choose Next. 7. On the Specify stack details page, in the Stack name field, enter a name. 8. Choose Next. 9. On the Configure stack options page, enter values for any options you want to use. Choose Next. 10. On the Review page, scroll down and choose the I acknowledge that AWS CloudFormation might create IAM resources with custom names option. 11. Choose Create stack. Automation 1124 AWS Systems Manager User Guide AWS CloudFormation shows the CREATE_IN_PROGRESS status for approximately three minutes. The status changes to CREATE_COMPLETE. You must repeat the following procedure in every account that you want to target to run multi- Region and multi-account automations. To create the required IAM automation role for multi-Region and multi-account automations by using AWS CloudFormation 1. Download the AWS-SystemsManager-AutomationExecutionRole.zip. Or, if your accounts are managed by AWS Organizations AWS-SystemsManager- AutomationExecutionRole (org).zip. This file contains the AWS-SystemsManager- AutomationExecutionRole.yaml AWS CloudFormation template file. 2. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 3. Choose Create stack. 4. In the Specify template section, choose Upload a template. 5. Choose Choose file, and then choose the AWS-SystemsManager- AutomationExecutionRole.yaml AWS CloudFormation template file. 6. Choose Next. 7. On the Specify stack details page, in the Stack name field, enter a name. 8. 9. In the Parameters section, in the AdminAccountId field, enter the ID for the Automation central account. If you are setting up this role for an AWS Organizations environment, there is another field in the section called OrganizationID. Enter the ID of your AWS organization. 10. Choose Next. 11. On the Configure stack options page, enter values for any options you want to use. Choose Next. 12. On the Review page, scroll down and choose the I acknowledge that AWS CloudFormation might create IAM resources with custom names option. 13. Choose Create stack. AWS CloudFormation shows the CREATE_IN_PROGRESS status for approximately three minutes. The status changes to CREATE_COMPLETE. Automation 1125 AWS Systems Manager User Guide Run an automation in multiple Regions and accounts (console) The following procedure describes how to use the Systems Manager console to run an automation in multiple Regions and accounts from the Automation management account. Before you begin Before you complete the following procedure, note the following information: • The user or role you use to run a multi-Region or multi-account automation must have the iam:PassRole permission for the AWS-SystemsManager- AutomationAdministrationRole role. • AWS account IDs or OUs where you want to run the automation. • Regions supported by Systems Manager where you want to run the automation. • The tag key and the tag value, or the name of the resource group, where you want to run the automation. To run an automation in multiple Regions and accounts 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 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. Automation 1126 AWS Systems Manager User Guide • 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. On the Execute automation document page, choose Multi-account and Region. 7. In the Target accounts and Regions section, use the Accounts and organizational
|
systems-manager-ug-352
|
systems-manager-ug.pdf
| 352 |
runtime – Choose this option if the Automation runbook is updated periodically and a new default version is assigned. Automation 1126 AWS Systems Manager User Guide • 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. On the Execute automation document page, choose Multi-account and Region. 7. In the Target accounts and Regions section, use the Accounts and organizational (OUs) field to specify the different AWS accounts or AWS organizational units (OUs) where you want to run the automation. Separate multiple accounts or OUs with a comma. 8. Use the AWS Regions list to choose one or more Regions where you want to run the automation. 9. Use the Multi-Region and account rate control options to restrict the automation to a limited number of accounts running in a limited number of Regions. These options don't restrict the number of AWS resources that can run the automations. a. In the Location (account-Region pair) concurrency section, choose an option to restrict the number of automations that can run in multiple accounts and Regions at the same time. For example, if you choose to run an automation in five (5) AWS accounts, which are located in four (4) AWS Regions, then Systems Manager runs automations in a total of 20 account-Region pairs. You can use this option to specify an absolute number, such as 2, so that the automation only runs in two account-Region pairs at the same time. Or you can specify a percentage of the account-Region pairs that can run at the same time. For example, with 20 account-Region pairs, if you specify 20%, then the automation simultaneously runs in a maximum of five (5) account-Region pairs. • Choose targets to enter an absolute number of account-Region pairs that can run the automation simultaneously. • Choose percent to enter a percentage of the total number of account-Region pairs that can run the automation simultaneously. b. In the Error threshold section, choose an option: • Choose errors to enter an absolute number of errors allowed before Automation stops sending the automation to other resources. • Choose percent to enter a percentage of errors allowed before Automation stops sending the automation to other resources. Automation 1127 AWS Systems Manager User Guide 10. In the Targets section, choose how you want to target the AWS resources where you want to run the Automation. These options are required. a. Use the Parameter list to choose a parameter. The items in the Parameter list are determined by the parameters in the Automation runbook that you selected at the start of this procedure. By choosing a parameter you define the type of resource on which the Automation workflow runs. b. Use the Targets list to choose how you want to target resources. i. ii. iii. iv. If you chose to target resources by using parameter values, then enter the parameter value for the parameter you chose in the Input parameters section. If you chose to target resources by using AWS Resource Groups, then choose the name of the group from the Resource Group list. If you chose to target resources by using tags, then enter the tag key and (optionally) the tag value in the fields provided. Choose Add. If you want to run an Automation runbook on all instances in the current AWS account and AWS Region, then choose All instances. 11. In the Input parameters section, specify the required inputs. Choose the AWS- SystemsManager-AutomationAdministrationRole IAM service role from the AutomationAssumeRole list. Note You might not need to choose some of the options in the Input parameters section. This is because you targeted resources in multiple Regions and accounts by using tags or a resource group. For example, if you chose the AWS-RestartEC2Instance runbook, then you don't need to specify or choose instance IDs in the Input parameters section. The automation locates the instances to restart by using the tags you specified. 12. (Optional) Choose a 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. Note that if your alarm activates, the automation is cancelled and any OnCancel steps you have defined run. If you use AWS CloudTrail, you will see the API call in your trail. Automation 1128 AWS Systems Manager User Guide 13. Use the options in the Rate control section to restrict the number of AWS resources that can run the Automation within each account-Region pair. In the Concurrency
|
systems-manager-ug-353
|
systems-manager-ug.pdf
| 353 |
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. Note that if your alarm activates, the automation is cancelled and any OnCancel steps you have defined run. If you use AWS CloudTrail, you will see the API call in your trail. Automation 1128 AWS Systems Manager User Guide 13. Use the options in the Rate control section to restrict the number of AWS resources that can run the Automation within each account-Region pair. In the Concurrency section, choose an option: • Choose targets to enter an absolute number of targets that can run the Automation workflow simultaneously. • Choose percentage to enter a percentage of the target set that can run the Automation workflow simultaneously. 14. In the Error threshold section, choose an option: • Choose errors to enter an absolute number of errors allowed before Automation stops sending the workflow to other resources. • Choose percentage to enter a percentage of errors allowed before Automation stops sending the workflow to other resources. 15. Choose Execute. Run an Automation in multiple Regions and accounts (command line) The following procedure describes how to use the AWS CLI (on Linux or Windows) or AWS Tools for PowerShell to run an automation in multiple Regions and accounts from the Automation management account. Before you begin Before you complete the following procedure, note the following information: • AWS account IDs or OUs where you want to run the automation. • Regions supported by Systems Manager where you want to run the automation. • The tag key and the tag value, or the name of the resource group, where you want to run the automation. To run an automation in multiple Regions and accounts 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. Automation 1129 AWS Systems Manager User Guide 2. Use the following format to create a command to run an automation in multiple Regions and accounts. Replace each example resource placeholder with your own information. Linux & macOS aws ssm start-automation-execution \ --document-name runbook name \ --parameters AutomationAssumeRole=arn:aws:iam::management account ID:role/AWS-SystemsManager-AutomationAdministrationRole \ --target-parameter-name parameter name \ --targets Key=tag key,Values=value \ --target-locations Accounts=account ID,account ID 2,Regions=Region,Region 2,ExecutionRoleName=AWS-SystemsManager- AutomationExecutionRole Windows aws ssm start-automation-execution ^ --document-name runbook name ^ --parameters AutomationAssumeRole=arn:aws:iam::management account ID:role/AWS-SystemsManager-AutomationAdministrationRole ^ --target-parameter-name parameter name ^ --targets Key=tag key,Values=value ^ --target-locations Accounts=account ID,account ID 2,Regions=Region,Region 2,ExecutionRoleName=AWS-SystemsManager- AutomationExecutionRole PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "tag key" $Targets.Values = "value" Start-SSMAutomationExecution ` -DocumentName "runbook name" ` -Parameter @{ "AutomationAssumeRole"="arn:aws:iam::management account ID:role/AWS- SystemsManager-AutomationAdministrationRole" } ` -TargetParameterName "parameter name" ` -Target $Targets ` -TargetLocation @{ "Accounts"="account ID","account ID 2"; Automation 1130 AWS Systems Manager User Guide "Regions"="Region","Region 2"; "ExecutionRoleName"="AWS-SystemsManager-AutomationExecutionRole" } Here are several examples. Example 1: This example restarts EC2 instances in three Regions across an entire AWS Organizations organization. This is achieved by targeting the root ID of the organization, and including child OUs. Linux & macOS aws ssm start-automation-execution \ --document-name "AWS-RestartEC2Instance" \ --target-parameter-name InstanceId \ --targets '[{"Key":"AWS::EC2::Instance","Values":["*"]}]' \ --target-locations '[{ "Accounts": ["r-example"], "IncludeChildOrganizationUnits": true, "Regions": ["us-east-1", "us-east-2", "us-west-2"] }]' Windows aws ssm start-automation-execution \ --document-name "AWS-RestartEC2Instance" ^ --target-parameter-name InstanceId ^ --targets '[{"Key":"AWS::EC2::Instance","Values":["*"]}]' ^ --target-locations '[{ "Accounts": ["r-example"], "IncludeChildOrganizationUnits": true, "Regions": ["us-east-1", "us-east-2", "us-west-2"] }]' PowerShell Start-SSMAutomationExecution ` -DocumentName "AWS-RestartEC2Instance" ` -TargetParameterName "InstanceId" ` -Targets '[{"Key":"AWS::EC2::Instance","Values":["*"]}]' -TargetLocation @{ "Accounts"="r-example"; Automation 1131 AWS Systems Manager User Guide "Regions"="us-east-1", "us-east-2", "us-west-2"; "IncludeChildOrganizationUnits"=true} Example 2: This example restarts specific EC2 instances in different accounts and Regions. Linux & macOS aws ssm start-automation-execution \ --document-name "AWS-RestartEC2Instance" \ --target-parameter-name InstanceId \ --target-locations '[{ "Accounts": ["123456789012"], "Targets": [{ "Key":"ParameterValues", "Values":["i-02573cafcfEXAMPLE", "i-0471e04240EXAMPLE"] }], "TargetLocationMaxConcurrency": "100%", "Regions": ["us-east-1"] }, { "Accounts": ["987654321098"], "Targets": [{ "Key":"ParameterValues", "Values":["i-07782c72faEXAMPLE"] }], "TargetLocationMaxConcurrency": "100%", "Regions": ["us-east-2"] }]' Windows aws ssm start-automation-execution ^ --document-name "AWS-RestartEC2Instance" ^ --target-parameter-name InstanceId ^ --target-locations '[{ "Accounts": ["123456789012"], "Targets": [{ "Key":"ParameterValues", "Values":["i-02573cafcfEXAMPLE", "i-0471e04240EXAMPLE"] }], "TargetLocationMaxConcurrency": "100%", "Regions": ["us-east-1"] }, { Automation 1132 AWS Systems Manager User Guide "Accounts": ["987654321098"], "Targets": [{ "Key":"ParameterValues", "Values":["i-07782c72faEXAMPLE"] }], "TargetLocationMaxConcurrency": "100%", "Regions": ["us-east-2"] }]' PowerShell Start-SSMAutomationExecution ` -DocumentName "AWS-RestartEC2Instance" ` -TargetParameterName "InstanceId" ` -Targets '[{"Key":"AWS::EC2::Instance","Values":["*"]}]' -TargetLocation @({ "Accounts"="123456789012", "Targets"= @{ "Key":"ParameterValues", "Values":["i-02573cafcfEXAMPLE", "i-0471e04240EXAMPLE"] }, "TargetLocationMaxConcurrency"="100%", "Regions"=["us-east-1"] }, { "Accounts"="987654321098", "Targets": @{ "Key":"ParameterValues", "Values":["i-07782c72faEXAMPLE"] }, "TargetLocationMaxConcurrency": "100%", "Regions"=["us-east-2"] }) Example 3: This example restarts EC2 instances in the 123456789012 and 987654321098 accounts, which are located in the us-east-2 and us-west-1 Regions. The instances must be tagged with the tag key-pair value Env-PROD. Linux & macOS aws ssm start-automation-execution \ --document-name AWS-RestartEC2Instance \ Automation 1133 AWS Systems Manager User Guide --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS- SystemsManager-AutomationAdministrationRole \ --target-parameter-name InstanceId \ --targets Key=tag:Env,Values=PROD \ --target-locations Accounts=123456789012,987654321098,Regions=us- east-2,us-west-1,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole Windows aws ssm start-automation-execution ^ --document-name AWS-RestartEC2Instance
|
systems-manager-ug-354
|
systems-manager-ug.pdf
| 354 |
"AWS-RestartEC2Instance" ` -TargetParameterName "InstanceId" ` -Targets '[{"Key":"AWS::EC2::Instance","Values":["*"]}]' -TargetLocation @({ "Accounts"="123456789012", "Targets"= @{ "Key":"ParameterValues", "Values":["i-02573cafcfEXAMPLE", "i-0471e04240EXAMPLE"] }, "TargetLocationMaxConcurrency"="100%", "Regions"=["us-east-1"] }, { "Accounts"="987654321098", "Targets": @{ "Key":"ParameterValues", "Values":["i-07782c72faEXAMPLE"] }, "TargetLocationMaxConcurrency": "100%", "Regions"=["us-east-2"] }) Example 3: This example restarts EC2 instances in the 123456789012 and 987654321098 accounts, which are located in the us-east-2 and us-west-1 Regions. The instances must be tagged with the tag key-pair value Env-PROD. Linux & macOS aws ssm start-automation-execution \ --document-name AWS-RestartEC2Instance \ Automation 1133 AWS Systems Manager User Guide --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS- SystemsManager-AutomationAdministrationRole \ --target-parameter-name InstanceId \ --targets Key=tag:Env,Values=PROD \ --target-locations Accounts=123456789012,987654321098,Regions=us- east-2,us-west-1,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole Windows aws ssm start-automation-execution ^ --document-name AWS-RestartEC2Instance ^ --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS- SystemsManager-AutomationAdministrationRole ^ --target-parameter-name InstanceId ^ --targets Key=tag:Env,Values=PROD ^ --target-locations Accounts=123456789012,987654321098,Regions=us- east-2,us-west-1,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "tag:Env" $Targets.Values = "PROD" Start-SSMAutomationExecution ` -DocumentName "AWS-RestartEC2Instance" ` -Parameter @{ "AutomationAssumeRole"="arn:aws:iam::123456789012:role/AWS- SystemsManager-AutomationAdministrationRole" } ` -TargetParameterName "InstanceId" ` -Target $Targets ` -TargetLocation @{ "Accounts"="123456789012","987654321098"; "Regions"="us-east-2","us-west-1"; "ExecutionRoleName"="AWS-SystemsManager-AutomationExecutionRole" } Example 4: This example restarts EC2 instances in the 123456789012 and 987654321098 accounts, which are located in the eu-central-1 Region. The instances must be members of the prod-instances AWS resource group. Automation 1134 AWS Systems Manager Linux & macOS User Guide aws ssm start-automation-execution \ --document-name AWS-RestartEC2Instance \ --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS- SystemsManager-AutomationAdministrationRole \ --target-parameter-name InstanceId \ --targets Key=ResourceGroup,Values=prod-instances \ --target-locations Accounts=123456789012,987654321098,Regions=eu- central-1,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole Windows aws ssm start-automation-execution ^ --document-name AWS-RestartEC2Instance ^ --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS- SystemsManager-AutomationAdministrationRole ^ --target-parameter-name InstanceId ^ --targets Key=ResourceGroup,Values=prod-instances ^ --target-locations Accounts=123456789012,987654321098,Regions=eu- central-1,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "ResourceGroup" $Targets.Values = "prod-instances" Start-SSMAutomationExecution ` -DocumentName "AWS-RestartEC2Instance" ` -Parameter @{ "AutomationAssumeRole"="arn:aws:iam::123456789012:role/AWS- SystemsManager-AutomationAdministrationRole" } ` -TargetParameterName "InstanceId" ` -Target $Targets ` -TargetLocation @{ "Accounts"="123456789012","987654321098"; "Regions"="eu-central-1"; "ExecutionRoleName"="AWS-SystemsManager-AutomationExecutionRole" } Automation 1135 AWS Systems Manager User Guide Example 5: This example restarts EC2 instances in the ou-1a2b3c-4d5e6c AWS organizational unit (OU). The instances are located in the us-west-1 and us-west-2 Regions. The instances must be members of the WebServices AWS resource group. Linux & macOS aws ssm start-automation-execution \ --document-name AWS-RestartEC2Instance \ --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS- SystemsManager-AutomationAdministrationRole \ --target-parameter-name InstanceId \ --targets Key=ResourceGroup,Values=WebServices \ --target-locations Accounts=ou-1a2b3c-4d5e6c,Regions=us-west-1,us- west-2,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole Windows aws ssm start-automation-execution ^ --document-name AWS-RestartEC2Instance ^ --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS- SystemsManager-AutomationAdministrationRole ^ --target-parameter-name InstanceId ^ --targets Key=ResourceGroup,Values=WebServices ^ --target-locations Accounts=ou-1a2b3c-4d5e6c,Regions=us-west-1,us- west-2,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "ResourceGroup" $Targets.Values = "WebServices" Start-SSMAutomationExecution ` -DocumentName "AWS-RestartEC2Instance" ` -Parameter @{ "AutomationAssumeRole"="arn:aws:iam::123456789012:role/AWS- SystemsManager-AutomationAdministrationRole" } ` -TargetParameterName "InstanceId" ` -Target $Targets ` -TargetLocation @{ Automation 1136 AWS Systems Manager User Guide "Accounts"="ou-1a2b3c-4d5e6c"; "Regions"="us-west-1"; "ExecutionRoleName"="AWS-SystemsManager-AutomationExecutionRole" } The system returns information similar to the following. Linux & macOS { "AutomationExecutionId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" } Windows { "AutomationExecutionId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" } PowerShell 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE 3. Run the following command to view details for the automation. Replace automation execution ID with your own information. Linux & macOS aws ssm describe-automation-executions \ --filters Key=ExecutionId,Values=automation execution ID Windows aws ssm describe-automation-executions ^ --filters Key=ExecutionId,Values=automation execution ID PowerShell Get-SSMAutomationExecutionList | ` Where {$_.AutomationExecutionId -eq "automation execution ID"} Automation 1137 AWS Systems Manager User Guide 4. Run the following command to view details about the automation progress. Linux & macOS aws ssm get-automation-execution \ --automation-execution-id 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE Windows aws ssm get-automation-execution ^ --automation-execution-id 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE PowerShell Get-SSMAutomationExecution ` -AutomationExecutionId a4a3c0e9-7efd-462a-8594-01234EXAMPLE Note You can also monitor the status of the automation in the console. In the Automation executions list, choose the automation you just ran and then choose the Execution steps tab. This tab shows the status of the automation actions. More info Centralized multi-account and multi-Region patching with AWS Systems Manager Automation Run automations based on EventBridge events You can start an automation by specifying a runbook as the target of an Amazon EventBridge event. You can start automations according to a schedule, or when a specific AWS system event occurs. For example, let's say you create a runbook named BootStrapInstances that installs software on an instance when an instance starts. To specify the BootStrapInstances runbook (and corresponding automation) as a target of an EventBridge event, you first create a new EventBridge rule. (Here's an example rule: Service name: EC2, Event Type: EC2 Instance State-change Notification, Specific state(s): running, Any instance.) Then you use the following procedures to Automation 1138 AWS Systems Manager User Guide specify the BootStrapInstances runbook as the target of the event using the EventBridge console and AWS Command Line Interface (AWS CLI). When a new instance starts, the system runs the automation and installs software. For information about creating runbooks, see Creating your own runbooks. Creating an EventBridge event that uses a runbook (console) Use the following procedure to configure a runbook as the target of a EventBridge event. To configure a runbook as a target of a EventBridge event rule 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. 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
|
systems-manager-ug-355
|
systems-manager-ug.pdf
| 355 |
software. For information about creating runbooks, see Creating your own runbooks. Creating an EventBridge event that uses a runbook (console) Use the following procedure to configure a runbook as the target of a EventBridge event. To configure a runbook as a target of a EventBridge event rule 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. 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. Choose how the rule is triggered. To create a rule based on... Do this... Event a. For Rule type, choose Rule with an event pattern. b. Choose Next. c. For Event source, choose AWS events or EventBrid ge partner events. d. In the Event pattern section, do one of the following: Automation 1139 AWS Systems Manager User Guide To create a rule based on... Do this... • To use a template to create your event pattern, choose Event pattern form and choose Event source, AWS service, and Event type. If you choose All Events as the event type, all events emitted by the AWS service will match the rule. To customize the template, choose Custom pattern (JSON editor) and make your changes. • To use a custom event pattern, choose Custom pattern (JSON editor) and create your event pattern. Automation 1140 AWS Systems Manager User Guide To create a rule based on... Do this... Schedule a. For Rule type, choose Schedule. b. Choose Next. c. For Schedule pattern, do one of the following: • To use a cron expressio n to define the schedule, choose A fine-grained schedule that runs at a specific time, such as 8:00 a.m. PST on the first Monday of every month and enter the cron expression. • To use a rate expression to define the schedule, choose A schedule that runs at a regular rate, such as every 10 minutes and enter the rate expression. 7. Choose Next. 8. 9. For Target types, choose AWS service. For Select a target, choose Systems Manager Automation. 10. For Document, choose a runbook to use when your target is invoked. 11. In the Configure automation parameter(s) section, either keep the default parameter values (if available) or enter your own values. Automation 1141 AWS Systems Manager Note User Guide To create a target, you must specify a value for each required parameter. If you don't, the system creates the rule, but the rule won't run. 12. For many target types, EventBridge needs permissions to send events to the target. In these cases, EventBridge can create the IAM role needed for your rule to run. Do one of the following: • To create an IAM role automatically, choose Create a new role for this specific resource. • To use an IAM role that you created earlier, choose Use existing role and select the existing role from the dropdown. Note that you might need to update the trust policy for your IAM role to include EventBridge. The following is an example: { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": [ "events.amazonaws.com", "ssm.amazonaws.com" ] }, "Action": "sts:AssumeRole" } ] } 13. Choose Next. 14. (Optional) Enter one or more tags for the rule. For more information, see Tagging Your Amazon EventBridge Resources in the Amazon EventBridge User Guide. 15. Choose Next. 16. Review the details of the rule and choose Create rule. Automation 1142 AWS Systems Manager User Guide Create an EventBridge event that uses a runbook (command line) The following procedure describes how to use the AWS CLI (on Linux or Windows) or AWS Tools for PowerShell to create an EventBridge event rule and configure a runbook as the target. To configure a runbook as a target of an EventBridge event rule 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 command to specify a new EventBridge event rule. Replace each example resource placeholder with your own information. Triggers based on a schedule Linux & macOS aws events put-rule \ --name "rule name" \ --schedule-expression "cron or rate expression" Windows aws events put-rule ^ --name "rule name" ^ --schedule-expression "cron or rate expression" PowerShell Write-CWERule ` -Name "rule name" ` -ScheduleExpression "cron or rate expression"
|
systems-manager-ug-356
|
systems-manager-ug.pdf
| 356 |
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 command to specify a new EventBridge event rule. Replace each example resource placeholder with your own information. Triggers based on a schedule Linux & macOS aws events put-rule \ --name "rule name" \ --schedule-expression "cron or rate expression" Windows aws events put-rule ^ --name "rule name" ^ --schedule-expression "cron or rate expression" PowerShell Write-CWERule ` -Name "rule name" ` -ScheduleExpression "cron or rate expression" The following example creates an EventBridge event rule that starts every day at 9:00 AM (UTC). Linux & macOS aws events put-rule \ Automation 1143 AWS Systems Manager User Guide --name "DailyAutomationRule" \ --schedule-expression "cron(0 9 * * ? *)" Windows aws events put-rule ^ --name "DailyAutomationRule" ^ --schedule-expression "cron(0 9 * * ? *)" PowerShell Write-CWERule ` -Name "DailyAutomationRule" ` -ScheduleExpression "cron(0 9 * * ? *)" Triggers based on an event Linux & macOS aws events put-rule \ --name "rule name" \ --event-pattern "{\"source\":[\"aws.service\"],\"detail-type\":[\"service event detail type\"]}" Windows aws events put-rule ^ --name "rule name" ^ --event-pattern "{\"source\":[\"aws.service\"],\"detail-type\":[\"service event detail type\"]}" PowerShell Write-CWERule ` -Name "rule name" ` -EventPattern '{"source":["aws.service"],"detail-type":["service event detail type"]}' Automation 1144 AWS Systems Manager User Guide The following example creates an EventBridge event rule that starts when any EC2 instance in the Region changes state. Linux & macOS aws events put-rule \ --name "EC2InstanceStateChanges" \ --event-pattern "{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change Notification\"]}" Windows aws events put-rule ^ --name "EC2InstanceStateChanges" ^ --event-pattern "{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change Notification\"]}" PowerShell Write-CWERule ` -Name "EC2InstanceStateChanges" ` -EventPattern '{"source":["aws.ec2"],"detail-type":["EC2 Instance State-change Notification"]}' The command returns details for the new EventBridge rule similar to the following. Linux & macOS { "RuleArn": "arn:aws:events:us-east-1:123456789012:rule/automationrule" } Windows { "RuleArn": "arn:aws:events:us-east-1:123456789012:rule/automationrule" } Automation 1145 AWS Systems Manager PowerShell User Guide arn:aws:events:us-east-1:123456789012:rule/EC2InstanceStateChanges 3. Create a command to specify a runbook as a target of the EventBridge event rule you created in step 2. Replace each example resource placeholder with your own information. Linux & macOS aws events put-targets \ --rule rule name \ --targets '{"Arn": " arn:aws:ssm:region:account ID:automation-definition/runbook name","Input":"{\"Message\":[\"{\\\"Key\\\":\\\"key name\\\",\\\"Values\\\":[\\ \"value\\\"]}\"]}","Id": "target ID","RoleArn": "arn:aws:iam::123456789012:role/ service-role/EventBridge service role"}' Windows aws events put-targets ^ --rule rule name ^ --targets '{"Arn": "arn:aws:ssm:region:account ID:automation-definition/runbook name","Input":"{\"Message\":[\"{\\\"Key\\\":\\\"key name\\\",\\\"Values\\\":[\\ \"value\\\"]}\"]}","Id": "target ID","RoleArn": "arn:aws:iam::123456789012:role/ service-role/EventBridge service role"}' PowerShell $Target = New-Object Amazon.CloudWatchEvents.Model.Target $Target.Id = "target ID" $Target.Arn = "arn:aws:ssm:region:account ID:automation-definition/runbook name" $Target.RoleArn = "arn:aws:iam::123456789012:role/service-role/EventBridge service role" $Target.Input = '{"input parameter":["value"],"AutomationAssumeRole": ["arn:aws:iam::123456789012:role/AutomationServiceRole"]}' Write-CWETarget ` -Rule "rule name" ` -Target $Target Automation 1146 AWS Systems Manager User Guide The following example creates an EventBridge event target that starts the specified instance ID using the runbook AWS-StartEC2Instance. Linux & macOS aws events put-targets \ --rule DailyAutomationRule \ --targets '{"Arn": "arn:aws:ssm:region:*:automation-definition/AWS- StartEC2Instance","Input":"{\"InstanceId\":[\"i-02573cafcfEXAMPLE\"], \"AutomationAssumeRole\":[\"arn:aws:iam::123456789012:role/AutomationServiceRole \"]}","Id": "Target1","RoleArn": "arn:aws:iam::123456789012:role/service-role/ AWS_Events_Invoke_Start_Automation_Execution_1213609520"}' Windows aws events put-targets ^ --rule DailyAutomationRule ^ --targets '{"Arn": "arn:aws:ssm:region:*:automation-definition/AWS- StartEC2Instance","Input":"{\"InstanceId\":[\"i-02573cafcfEXAMPLE\"], \"AutomationAssumeRole\":[\"arn:aws:iam::123456789012:role/AutomationServiceRole \"]}","Id": "Target1","RoleArn": "arn:aws:iam::123456789012:role/service-role/ AWS_Events_Invoke_Start_Automation_Execution_1213609520"}' PowerShell $Target = New-Object Amazon.CloudWatchEvents.Model.Target $Target.Id = "Target1" $Target.Arn = "arn:aws:ssm:region:*:automation-definition/AWS-StartEC2Instance" $Target.RoleArn = "arn:aws:iam::123456789012:role/service-role/ AWS_Events_Invoke_Start_Automation_Execution_1213609520" $Target.Input = '{"InstanceId":["i-02573cafcfEXAMPLE"],"AutomationAssumeRole": ["arn:aws:iam::123456789012:role/AutomationServiceRole"]}' Write-CWETarget ` -Rule "DailyAutomationRule" ` -Target $Target The system returns information like the following. Automation 1147 User Guide AWS Systems Manager Linux & macOS { "FailedEntries": [], "FailedEntryCount": 0 } Windows { "FailedEntries": [], "FailedEntryCount": 0 } PowerShell There is no output if the command succeeds for PowerShell. Run an automation step by step The following procedures describe how to use the AWS Systems Manager console and AWS Command Line Interface (AWS CLI) to run an automation using the manual execution mode. By using the manual execution mode, the automation starts in a Waiting status and pauses in the Waiting status between each step. This allows you to control when the automation proceeds, which is useful if you need to review the result of a step before continuing. The automation runs in the context of the current user. This means that you don't need to configure additional IAM permissions as long as you have permission to use the runbook, and any actions called by the runbook. If you have administrator permissions in IAM, then you already have permission to run this automation. Running an automation step by step (console) The following procedure shows how to use the Systems Manager console to manually run an automation step by step. Automation 1148 AWS Systems Manager User Guide To run an automation step by step 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 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
|
systems-manager-ug-357
|
systems-manager-ug.pdf
| 357 |
Systems Manager console to manually run an automation step by step. Automation 1148 AWS Systems Manager User Guide To run an automation step by step 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 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 Execution Mode section, choose Manual execution. In the Input parameters section, specify the required inputs. Optionally, you can choose an IAM service role from the AutomationAssumeRole list. 8. Choose Execute. 9. Choose Execute this step when you're ready to start the first step of the automation. The automation proceeds with step one and pauses before running any subsequent steps specified in the runbook you chose in step 3 of this procedure. If the runbook has multiple steps, you must select Execute this step for each step for the automation to proceed. Each time you choose Execute this step the action runs. Automation 1149 AWS Systems Manager Note User Guide The console displays the status of the automation. If the automation fails to run a step, see Troubleshooting Systems Manager Automation. 10. After you complete all steps specified in the runbook, choose Complete and view results to finish the automation and view the results. Running an automation step by step (command line) The following procedure describes how to use the AWS CLI (on Linux, macOS, or Windows) or AWS Tools for PowerShell to manually run an automation step by step. To run an automation step by step 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. Run the following command to start a manual automation. Replace each example resource placeholder with your own information. Linux & macOS aws ssm start-automation-execution \ --document-name runbook name \ --mode Interactive \ --parameters runbook parameters Windows aws ssm start-automation-execution ^ --document-name runbook name ^ --mode Interactive ^ --parameters runbook parameters PowerShell Start-SSMAutomationExecution ` Automation 1150 AWS Systems Manager User Guide -DocumentName runbook name ` -Mode Interactive ` -Parameter runbook parameters Here is an example using the runbook AWS-RestartEC2Instance to restart the specified EC2 instance. Linux & macOS aws ssm start-automation-execution \ --document-name "AWS-RestartEC2Instance" \ --mode Interactive \ --parameters "InstanceId=i-02573cafcfEXAMPLE" Windows aws ssm start-automation-execution ^ --document-name "AWS-RestartEC2Instance" ^ --mode Interactive ^ --parameters "InstanceId=i-02573cafcfEXAMPLE" PowerShell Start-SSMAutomationExecution ` -DocumentName AWS-RestartEC2Instance ` -Mode Interactive -Parameter @{"InstanceId"="i-02573cafcfEXAMPLE"} The system returns information like the following. Linux & macOS { "AutomationExecutionId": "ba9cd881-1b36-4d31-a698-0123456789ab" } Windows { Automation 1151 AWS Systems Manager User Guide "AutomationExecutionId": "ba9cd881-1b36-4d31-a698-0123456789ab" } PowerShell ba9cd881-1b36-4d31-a698-0123456789ab 3. Run the following command when you're ready to start the first step of the automation. Replace each example resource placeholder with your own information. The automation proceeds with step one and pauses before running any subsequent steps specified in the runbook you chose in step 1 of this procedure. If the runbook has multiple steps, you must run the following command for each step for the automation to proceed. Linux & macOS aws ssm send-automation-signal \ --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab \ --signal-type StartStep \ --payload StepName="stopInstances" Windows aws ssm send-automation-signal ^ --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab ^ --signal-type StartStep ^ --payload StepName="stopInstances" PowerShell Send-SSMAutomationSignal ` -AutomationExecutionId ba9cd881-1b36-4d31-a698-0123456789ab ` -SignalType StartStep -Payload @{"StepName"="stopInstances"} There is no output if the command succeeds. 4. Run the following command to retrieve the status of each step execution in the automation. Automation 1152 AWS Systems Manager Linux & macOS User Guide aws ssm describe-automation-step-executions \ --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab Windows aws ssm describe-automation-step-executions ^ --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab PowerShell Get-SSMAutomationStepExecution ` -AutomationExecutionId ba9cd881-1b36-4d31-a698-0123456789ab The system returns information like the following. Linux & macOS { "StepExecutions": [ { "StepName": "stopInstances", "Action": "aws:changeInstanceState", "ExecutionStartTime": 1557167178.42, "ExecutionEndTime": 1557167220.617, "StepStatus": "Success", "Inputs": { "DesiredState":
|
systems-manager-ug-358
|
systems-manager-ug.pdf
| 358 |
ssm send-automation-signal ^ --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab ^ --signal-type StartStep ^ --payload StepName="stopInstances" PowerShell Send-SSMAutomationSignal ` -AutomationExecutionId ba9cd881-1b36-4d31-a698-0123456789ab ` -SignalType StartStep -Payload @{"StepName"="stopInstances"} There is no output if the command succeeds. 4. Run the following command to retrieve the status of each step execution in the automation. Automation 1152 AWS Systems Manager Linux & macOS User Guide aws ssm describe-automation-step-executions \ --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab Windows aws ssm describe-automation-step-executions ^ --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab PowerShell Get-SSMAutomationStepExecution ` -AutomationExecutionId ba9cd881-1b36-4d31-a698-0123456789ab The system returns information like the following. Linux & macOS { "StepExecutions": [ { "StepName": "stopInstances", "Action": "aws:changeInstanceState", "ExecutionStartTime": 1557167178.42, "ExecutionEndTime": 1557167220.617, "StepStatus": "Success", "Inputs": { "DesiredState": "\"stopped\"", "InstanceIds": "[\"i-02573cafcfEXAMPLE\"]" }, "Outputs": { "InstanceStates": [ "stopped" ] }, "StepExecutionId": "654243ba-71e3-4771-b04f-0123456789ab", "OverriddenParameters": {}, "ValidNextSteps": [ "startInstances" Automation 1153 AWS Systems Manager User Guide ] }, { "StepName": "startInstances", "Action": "aws:changeInstanceState", "ExecutionStartTime": 1557167273.754, "ExecutionEndTime": 1557167480.73, "StepStatus": "Success", "Inputs": { "DesiredState": "\"running\"", "InstanceIds": "[\"i-02573cafcfEXAMPLE\"]" }, "Outputs": { "InstanceStates": [ "running" ] }, "StepExecutionId": "8a4a1e0d-dc3e-4039-a599-0123456789ab", "OverriddenParameters": {} } ] } Windows { "StepExecutions": [ { "StepName": "stopInstances", "Action": "aws:changeInstanceState", "ExecutionStartTime": 1557167178.42, "ExecutionEndTime": 1557167220.617, "StepStatus": "Success", "Inputs": { "DesiredState": "\"stopped\"", "InstanceIds": "[\"i-02573cafcfEXAMPLE\"]" }, "Outputs": { "InstanceStates": [ "stopped" ] }, "StepExecutionId": "654243ba-71e3-4771-b04f-0123456789ab", Automation 1154 AWS Systems Manager User Guide "OverriddenParameters": {}, "ValidNextSteps": [ "startInstances" ] }, { "StepName": "startInstances", "Action": "aws:changeInstanceState", "ExecutionStartTime": 1557167273.754, "ExecutionEndTime": 1557167480.73, "StepStatus": "Success", "Inputs": { "DesiredState": "\"running\"", "InstanceIds": "[\"i-02573cafcfEXAMPLE\"]" }, "Outputs": { "InstanceStates": [ "running" ] }, "StepExecutionId": "8a4a1e0d-dc3e-4039-a599-0123456789ab", "OverriddenParameters": {} } ] } PowerShell Action: aws:changeInstanceState ExecutionEndTime : 5/6/2019 19:45:46 ExecutionStartTime : 5/6/2019 19:45:03 FailureDetails : FailureMessage : Inputs : {[DesiredState, "stopped"], [InstanceIds, ["i-02573cafcfEXAMPLE"]]} IsCritical : False IsEnd : False MaxAttempts : 0 NextStep : OnFailure : Outputs : {[InstanceStates, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]} OverriddenParameters : {} Automation 1155 AWS Systems Manager User Guide Response : ResponseCode : StepExecutionId : 8fcc9641-24b7-40b3-a9be-0123456789ab StepName : stopInstances StepStatus : Success TimeoutSeconds : 0 ValidNextSteps : {startInstances} 5. Run the following command to complete the automation after all steps specified within the chosen runbook have finished. Replace each example resource placeholder with your own information. Linux & macOS aws ssm stop-automation-execution \ --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab \ --type Complete Windows aws ssm stop-automation-execution ^ --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab ^ --type Complete PowerShell Stop-SSMAutomationExecution ` -AutomationExecutionId ba9cd881-1b36-4d31-a698-0123456789ab ` -Type Complete There is no output if the command succeeds. Scheduling automations with State Manager associations You can start an automation by creating a State Manager association with a runbook. State Manager is a tool in AWS Systems Manager. By creating a State Manager association with a runbook, you can target different types of AWS resources. For example, you can create associations that enforce a desired state on an AWS resource, including the following: Automation 1156 AWS Systems Manager User Guide • Attach a Systems Manager role to Amazon Elastic Compute Cloud (Amazon EC2) instances to make them managed instances. • Enforce desired ingress and egress rules for a security group. • Create or delete Amazon DynamoDB backups. • Create or delete Amazon Elastic Block Store (Amazon EBS) snapshots. • Turn off read and write permissions on Amazon Simple Storage Service (Amazon S3) buckets. • Start, restart, or stop managed instances and Amazon Relational Database Service (Amazon RDS) instances. • Apply patches to Linux, macOS, and Window AMIs. Use the following procedures to create a State Manager association that runs an automation using the AWS Systems Manager console and AWS Command Line Interface (AWS CLI). For general information about associations and information about creating an association that uses an SSM Command document or Policy document, see Creating associations. Before you begin Be aware of the following important details before you run an automation by using State Manager: • Before you can create an association that uses a runbook, verify that you configured permissions for Automation, a tool in AWS Systems Manager. For more information, see Setting up Automation. • State Manager associations that use runbooks contribute to the maximum number of concurrently running automations in your AWS account. You can have a maximum of 100 concurrent automations running. For information, see Systems Manager service quotas in the Amazon Web Services General Reference. • When running an automation, State Manager does not log the API operations initiated by the automation in AWS CloudTrail. • Systems Manager automatically creates a service-linked role so that State Manager has permission to call Systems Manager Automation API operations. If you want, you can create the service-linked role yourself by running the following command from the AWS CLI or AWS Tools for PowerShell. Linux & macOS aws iam create-service-linked-role \ Automation 1157 AWS Systems Manager User Guide --aws-service-name ssm.amazonaws.com Windows aws iam create-service-linked-role ^ --aws-service-name ssm.amazonaws.com PowerShell New-IAMServiceLinkedRole ` -AWSServiceName ssm.amazonaws.com For more information about service-linked roles, see Using service-linked roles for Systems Manager. Creating an association that runs an automation (console) The following procedure describes how to use the Systems Manager console to create a State
|
systems-manager-ug-359
|
systems-manager-ug.pdf
| 359 |
that State Manager has permission to call Systems Manager Automation API operations. If you want, you can create the service-linked role yourself by running the following command from the AWS CLI or AWS Tools for PowerShell. Linux & macOS aws iam create-service-linked-role \ Automation 1157 AWS Systems Manager User Guide --aws-service-name ssm.amazonaws.com Windows aws iam create-service-linked-role ^ --aws-service-name ssm.amazonaws.com PowerShell New-IAMServiceLinkedRole ` -AWSServiceName ssm.amazonaws.com For more information about service-linked roles, see Using service-linked roles for Systems Manager. Creating an association that runs an automation (console) The following procedure describes how to use the Systems Manager console to create a State Manager association that runs an automation. To create a State Manager association that runs an automation 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. 3. 4. In the navigation pane, choose State Manager, and then choose Create association. In the Name field, specify a name. This is optional, but recommended. In the Document list, choose a runbook. Use the Search bar to filter on Document type : Equal : Automation runbooks. To view more runbooks, use the numbers to the right of the Search bar. Note You can view information about a runbook by choosing the runbook name. 5. Choose Simple execution to run the automation on one or more targets by specifying the resource ID for those targets. Choose Rate control to run the automation across a fleet of AWS resources by specifying a targeting option such as tags or AWS Resource Groups. You can also Automation 1158 AWS Systems Manager User Guide control the operation of the automation across your resources by specifying concurrency and error thresholds. If you chose Rate control, the Targets section is displayed. 6. In the Targets section, choose a method for targeting resources. a. (Required) In the Parameter list, choose a parameter. The items in the Parameter list are determined by the parameters in the runbook that you selected at the start of this procedure. By choosing a parameter, you define the type of resource on which the automation runs. b. (Required) In the Targets list, choose a method for targeting the resources. • Resource Group: Choose the name of the group from the Resource Group list. For more information about targeting AWS Resource Groups in runbooks, see Targeting AWS Resource Groups. • Tags: Enter the tag key and (optionally) the tag value in the fields provided. Choose Add. For more information about targeting tags in runbooks, see Targeting a tag. • Parameter Values: Enter values in the Input parameters section. If you specify multiple values, Systems Manager runs a child automation on each value specified. For example, say that your runbook includes an InstanceID parameter. If you target the values of the InstanceID parameter when you run the automation, then Systems Manager runs a child automation for each instance ID value specified. The parent automation is complete when the automation finishes running each specified instance, or if the automation fails. You can target a maximum of 50 parameter values. For more information about targeting parameter values in runbooks, see Targeting parameter values. 7. In the Input parameters section, specify the required input parameters. If you chose to target resources by using tags or a resource group, then you might not need to choose some of the options in the Input parameters section. For example, if you chose the AWS-RestartEC2Instance runbook, and you chose to target instances by using tags, then you don't need to specify or choose instance IDs in the Input parameters section. The automation locates the instances to restart by using the tags you specified. Automation 1159 AWS Systems Manager User Guide Important You must specify a role ARN in the AutomationAssumeRole field. State Manager uses the assume role to call AWS services specified in the runbook and run Automation associations on your behalf. 8. In the Specify schedule section, choose On Schedule if you want to run the association at regular intervals. If you choose this option, then use the options provided to create the schedule using Cron or Rate expressions. For more information about Cron and Rate expressions for State Manager, see Cron and rate expressions for associations. Note Rate expressions are the preferred scheduling mechanism for State Manager associations that use runbooks. Rate expressions allow more flexibility for running associations in the event that you reach the maximum number of concurrently running automations. With a rate schedule, Systems Manager can retry the automation shortly after receiving notification that concurrent automations have reached their maximum and have been throttled. Choose No schedule if you want to run the association one time. 9. (Optional) In the Rate Control section, choose Concurrency and Error threshold options to control the automation deployment across your AWS resources. a. In the Concurrency section, choose an option: • Choose targets to
|
systems-manager-ug-360
|
systems-manager-ug.pdf
| 360 |
mechanism for State Manager associations that use runbooks. Rate expressions allow more flexibility for running associations in the event that you reach the maximum number of concurrently running automations. With a rate schedule, Systems Manager can retry the automation shortly after receiving notification that concurrent automations have reached their maximum and have been throttled. Choose No schedule if you want to run the association one time. 9. (Optional) In the Rate Control section, choose Concurrency and Error threshold options to control the automation deployment across your AWS resources. a. In the Concurrency section, choose an option: • Choose targets to enter an absolute number of targets that can run the automation simultaneously. • Choose percentage to enter a percentage of the target set that can run the automation simultaneously. b. In the Error threshold section, choose an option: • Choose errors to enter an absolute number of errors allowed before Automation stops sending the automation to other resources. Automation 1160 AWS Systems Manager User Guide • Choose percentage to enter a percentage of errors allowed before Automation stops sending the automation to other resources. For more information about using targets and rate controls with Automation, see Run automated operations at scale. 10. Choose Create Association. Important When you create an association, the association immediately runs against the specified targets. The association then runs based on the cron or rate expression you chose. If you chose No schedule, the association doesn't run again. Creating an association that runs an automation (command line) The following procedure describes how to use the AWS CLI (on Linux or Windows) or AWS Tools for PowerShell to create a State Manager association that runs an automation. Before you begin Before you complete the following procedure, make sure you have created an IAM service role that contains the permissions necessary to run the runbook, and configured a trust relationship for Automation, a tool in AWS Systems Manager. For more information, see Task 1: Create a service role for Automation. To create an association that runs an automation 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. Run the following command to view a list of documents. Linux & macOS aws ssm list-documents Automation 1161 AWS Systems Manager Windows aws ssm list-documents PowerShell Get-SSMDocumentList User Guide Note the name of the runbook that you want to use for the association. 3. Run the following command to view details about the runbook. In the following command, replace runbook name with your own information. Linux & macOS aws ssm describe-document \ --name runbook name Note a parameter name (for example, InstanceId) that you want to use for the -- automation-target-parameter-name option. This parameter determines the type of resource on which the automation runs. Windows aws ssm describe-document ^ --name runbook name Note a parameter name (for example, InstanceId) that you want to use for the -- automation-target-parameter-name option. This parameter determines the type of resource on which the automation runs. PowerShell Get-SSMDocumentDescription ` -Name runbook name Note a parameter name (for example, InstanceId) that you want to use for the AutomationTargetParameterName option. This parameter determines the type of resource on which the automation runs. Automation 1162 AWS Systems Manager User Guide 4. Create a command that runs an automation using a State Manager association. Replace each example resource placeholder with your own information. Targeting using tags Linux & macOS aws ssm create-association \ --association-name association name \ --targets Key=tag:key name,Values=value \ --name runbook name \ --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/ RunbookAssumeRole \ --automation-target-parameter-name target parameter \ --schedule "cron or rate expression" Note If you create an association by using the AWS CLI, use the --targets parameter to target instances for the association. Don't use the --instance-id parameter. The --instance-id parameter is a legacy parameter. Windows aws ssm create-association ^ --association-name association name ^ --targets Key=tag:key name,Values=value ^ --name runbook name ^ --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/ RunbookAssumeRole ^ --automation-target-parameter-name target parameter ^ --schedule "cron or rate expression" Note If you create an association by using the AWS CLI, use the --targets parameter to target instances for the association. Don't use the --instance-id parameter. The --instance-id parameter is a legacy parameter. Automation 1163 AWS Systems Manager PowerShell User Guide $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "tag:key name" $Targets.Values = "value" New-SSMAssociation ` -AssociationName "association name" ` -Target $Targets ` -Name "runbook name" ` -Parameters @{ "AutomationAssumeRole"="arn:aws:iam::123456789012:role/RunbookAssumeRole" } ` -AutomationTargetParameterName "target parameter" ` -ScheduleExpression "cron or rate expression" Note If you create an association by using the AWS Tools for PowerShell, use the Target parameter to target instances for the association. Don't use the InstanceId parameter. The InstanceId parameter is a legacy parameter. Targeting using parameter values Linux &
|
systems-manager-ug-361
|
systems-manager-ug.pdf
| 361 |
association. Don't use the --instance-id parameter. The --instance-id parameter is a legacy parameter. Automation 1163 AWS Systems Manager PowerShell User Guide $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "tag:key name" $Targets.Values = "value" New-SSMAssociation ` -AssociationName "association name" ` -Target $Targets ` -Name "runbook name" ` -Parameters @{ "AutomationAssumeRole"="arn:aws:iam::123456789012:role/RunbookAssumeRole" } ` -AutomationTargetParameterName "target parameter" ` -ScheduleExpression "cron or rate expression" Note If you create an association by using the AWS Tools for PowerShell, use the Target parameter to target instances for the association. Don't use the InstanceId parameter. The InstanceId parameter is a legacy parameter. Targeting using parameter values Linux & macOS aws ssm create-association \ --association-name association name \ --targets Key=ParameterValues,Values=value,value 2,value 3 \ --name runbook name \ --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/ RunbookAssumeRole \ --automation-target-parameter-name target parameter \ --schedule "cron or rate expression" Windows aws ssm create-association ^ --association-name association name ^ Automation 1164 AWS Systems Manager User Guide --targets Key=ParameterValues,Values=value,value 2,value 3 ^ --name runbook name ^ --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/ RunbookAssumeRole ^ --automation-target-parameter-name target parameter ^ --schedule "cron or rate expression" PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "ParameterValues" $Targets.Values = "value","value 2","value 3" New-SSMAssociation ` -AssociationName "association name" ` -Target $Targets ` -Name "runbook name" ` -Parameters @{ "AutomationAssumeRole"="arn:aws:iam::123456789012:role/RunbookAssumeRole"} ` -AutomationTargetParameterName "target parameter" ` -ScheduleExpression "cron or rate expression" Targeting using AWS Resource Groups Linux & macOS aws ssm create-association \ --association-name association name \ --targets Key=ResourceGroup,Values=resource group name \ --name runbook name \ --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/ RunbookAssumeRole \ --automation-target-parameter-name target parameter \ --schedule "cron or rate expression" Windows aws ssm create-association ^ --association-name association name ^ --targets Key=ResourceGroup,Values=resource group name ^ --name runbook name ^ Automation 1165 AWS Systems Manager User Guide --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/ RunbookAssumeRole ^ --automation-target-parameter-name target parameter ^ --schedule "cron or rate expression" PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "ResourceGroup" $Targets.Values = "resource group name" New-SSMAssociation ` -AssociationName "association name" ` -Target $Targets ` -Name "runbook name" ` -Parameters @{ "AutomationAssumeRole"="arn:aws:iam::123456789012:role/RunbookAssumeRole"} ` -AutomationTargetParameterName "target parameter" ` -ScheduleExpression "cron or rate expression" Targeting multiple accounts and Regions Linux & macOS aws ssm create-association \ --association-name association name \ --targets Key=ResourceGroup,Values=resource group name \ --name runbook name \ --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/ RunbookAssumeRole \ --automation-target-parameter-name target parameter \ --schedule "cron or rate expression" \ --target-locations Accounts=111122223333,444455556666,444455556666,Regions=region,region Windows aws ssm create-association ^ --association-name association name ^ --targets Key=ResourceGroup,Values=resource group name ^ --name runbook name ^ Automation 1166 AWS Systems Manager User Guide --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/ RunbookAssumeRole ^ --automation-target-parameter-name target parameter ^ --schedule "cron or rate expression" ^ --target-locations Accounts=111122223333,444455556666,444455556666,Regions=region,region PowerShell $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target $Targets.Key = "ResourceGroup" $Targets.Values = "resource group name" New-SSMAssociation ` -AssociationName "association name" ` -Target $Targets ` -Name "runbook name" ` -Parameters @{ "AutomationAssumeRole"="arn:aws:iam::123456789012:role/RunbookAssumeRole"} ` -AutomationTargetParameterName "target parameter" ` -ScheduleExpression "cron or rate expression" ` -TargetLocations @{ "Accounts"=["111122223333,444455556666,444455556666"], "Regions"=["region,region"] The command returns details for the new association similar to the following. Linux & macOS { "AssociationDescription": { "ScheduleExpression": "cron(0 7 ? * MON *)", "Name": "AWS-StartEC2Instance", "Parameters": { "AutomationAssumeRole": [ "arn:aws:iam::123456789012:role/RunbookAssumeRole" ] }, "Overview": { "Status": "Pending", "DetailedStatus": "Creating" }, Automation 1167 AWS Systems Manager User Guide "AssociationId": "1450b4b7-bea2-4e4b-b340-01234EXAMPLE", "DocumentVersion": "$DEFAULT", "AutomationTargetParameterName": "InstanceId", "LastUpdateAssociationDate": 1564686638.498, "Date": 1564686638.498, "AssociationVersion": "1", "AssociationName": "CLI", "Targets": [ { "Values": [ "DEV" ], "Key": "tag:ENV" } ] } } Windows { "AssociationDescription": { "ScheduleExpression": "cron(0 7 ? * MON *)", "Name": "AWS-StartEC2Instance", "Parameters": { "AutomationAssumeRole": [ "arn:aws:iam::123456789012:role/RunbookAssumeRole" ] }, "Overview": { "Status": "Pending", "DetailedStatus": "Creating" }, "AssociationId": "1450b4b7-bea2-4e4b-b340-01234EXAMPLE", "DocumentVersion": "$DEFAULT", "AutomationTargetParameterName": "InstanceId", "LastUpdateAssociationDate": 1564686638.498, "Date": 1564686638.498, "AssociationVersion": "1", "AssociationName": "CLI", "Targets": [ { "Values": [ Automation 1168 AWS Systems Manager User Guide "DEV" ], "Key": "tag:ENV" } ] } } PowerShell Name : AWS-StartEC2Instance InstanceId : Date : 8/1/2019 7:31:38 PM Status.Name : Status.Date : Status.Message : Status.AdditionalInfo : Note If you use tags to create an association on one or more target instances, and then you remove the tags from an instance, that instance no longer runs the association. The instance is disassociated from the State Manager document. Troubleshooting automations run by State Manager associations Systems Manager Automation enforces a limit of 100 concurrent automations, and 1,000 queued automations per account, per Region. If a State Manager association that uses a runbook shows a status of Failed and a detailed status of AutomationExecutionLimitExceeded, then your automation might have reached the limit. As a result, Systems Manager throttles the automations. To resolve this issue, do the following: • Use a different rate or cron expression for your association. For example, if the association is scheduled to run every 30 minutes, then change the expression so that it runs every hour or two. • Delete existing automations that have a status of Pending. By deleting these automations, you clear the current queue. Automation 1169 AWS Systems Manager User Guide Schedule automations with maintenance windows You can start an automation by configuring a runbook as a registered task for a maintenance window. By registering the runbook as
|
systems-manager-ug-362
|
systems-manager-ug.pdf
| 362 |
Systems Manager throttles the automations. To resolve this issue, do the following: • Use a different rate or cron expression for your association. For example, if the association is scheduled to run every 30 minutes, then change the expression so that it runs every hour or two. • Delete existing automations that have a status of Pending. By deleting these automations, you clear the current queue. Automation 1169 AWS Systems Manager User Guide Schedule automations with maintenance windows You can start an automation by configuring a runbook as a registered task for a maintenance window. By registering the runbook as a registered task, the maintenance window runs the automation during the scheduled maintenance period. For example, let's say you create a runbook named CreateAMI that creates an Amazon Machine Image (AMI) of instances registered as targets to the maintenance window. To specify the CreateAMI runbook (and corresponding automation) as a registered task of a maintenance window, you first create a maintenance window and register targets. Then you use the following procedure to specify the CreateAMI document as a registered task within the maintenance window. When the maintenance window starts during the scheduled period, the system runs the automation and creates an AMI of the registered targets. For information about creating Automation runbooks, see Creating your own runbooks. Automation is a tool in AWS Systems Manager. Use the following procedures to configure an automation as a registered task for a maintenance window using the AWS Systems Manager console, AWS Command Line Interface (AWS CLI), or AWS Tools for Windows PowerShell. Registering an automation task to a maintenance window (console) The following procedure describes how to use the Systems Manager console to configure an automation as a registered task for a maintenance window. Before you begin Before you complete the following procedure, you must create a maintenance window and register at least one target. For more information, see the following procedures: • Create a maintenance window using the console. • Assign targets to a maintenance window using the console To configure an automation as a registered task for a maintenance window 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the left navigation pane, choose Maintenance Windows, and then choose the maintenance window you want to register an Automation task with. Automation 1170 AWS Systems Manager User Guide 3. Choose Actions. Then choose Register Automation task to run your choice of an automation 4. 5. 6. 7. 8. 9. on targets by using a runbook. For Name, enter a name for the task. For Description, enter a description. For Document, choose the runbook that defines the tasks to run. For Document version, choose the runbook version to use. For Task priority, specify a priority for this task. 1 is the highest priority. Tasks in a maintenance window are scheduled in priority order; tasks that have the same priority are scheduled in parallel. In the Targets section, if the runbook you chose is one that runs tasks on resources, identify the targets on which you want to run this automation by specifying tags or by selecting instances manually. Note If you want to pass the resources through input parameters instead of targets, you don't need to specify a maintenance window target. In many cases, you don't need to explicitly specify a target for an automation task. For example, say that you're creating an Automation-type task to update an Amazon Machine Image (AMI) for Linux using the AWS-UpdateLinuxAmi runbook. When the task runs, the AMI is updated with the latest available Linux distribution packages and Amazon software. New instances created from the AMI already have these updates installed. Because the ID of the AMI to be updated is specified in the input parameters for the runbook, there is no need to specify a target again in the maintenance window task. For information about maintenance window tasks that don't require targets, see the section called “Registering maintenance window tasks without targets”. 10. (Optional) For Rate control: Automation 1171 AWS Systems Manager Note User Guide If the task you're running doesn't specify targets, you don;t need to specify rate controls. • For Concurrency, specify either a number or a percentage of targets on which to run the automation at the same time. If you selected targets by choosing tag key-value pairs, and you aren't certain how many targets use the selected tags, then limit the number of automations that can run at the same time by specifying a percentage. When the maintenance window runs, a new automation is initiated per target. There is a limit of 100 concurrent automations per AWS account. If you specify a concurrency rate greater than 100, concurrent automations greater than 100 are automatically added to the automation queue. For information, see Systems Manager service quotas in the Amazon
|
systems-manager-ug-363
|
systems-manager-ug.pdf
| 363 |
which to run the automation at the same time. If you selected targets by choosing tag key-value pairs, and you aren't certain how many targets use the selected tags, then limit the number of automations that can run at the same time by specifying a percentage. When the maintenance window runs, a new automation is initiated per target. There is a limit of 100 concurrent automations per AWS account. If you specify a concurrency rate greater than 100, concurrent automations greater than 100 are automatically added to the automation queue. For information, see Systems Manager service quotas in the Amazon Web Services General Reference. • For Error threshold, specify when to stop running the automation on other targets after it fails on either a number or a percentage of targets. For example, if you specify three errors, then Systems Manager stops running automations when the fourth error is received. Targets still processing the automation might also send errors. 11. In the Input Parameters section, specify parameters for the runbook. For runbooks, the system auto-populates some of the values. You can keep or replace these values. Important For runbooks, you can optionally specify an Automation Assume Role. If you don't specify a role for this parameter, then the automation assumes the maintenance window service role you choose in step 11. As such, you must ensure that the maintenance window service role you choose has the appropriate AWS Identity and Access Management (IAM) permissions to perform the actions defined within the runbook. For example, the service-linked role for Systems Manager doesn't have the IAM permission ec2:CreateSnapshot, which is required to use the runbook AWS- CopySnapshot. In this scenario, you must either use a custom maintenance window Automation 1172 AWS Systems Manager User Guide service role or specify an Automation assume role that has ec2:CreateSnapshot permissions. For information, see Setting up Automation. 12. In the IAM service role area, choose a role to provide permissions for Systems Manager to start the automation. To create a service role for maintenance window tasks, see Setting up Maintenance Windows. 13. Choose Register Automation task. Registering an Automation task to a maintenance window (command line) The following procedure describes how to use the AWS CLI (on Linux or Windows) or AWS Tools for PowerShell to configure an automation as a registered task for a maintenance window. Before you begin Before you complete the following procedure, you must create a maintenance window and register at least one target. For more information, see the following procedures: • Step 1: Create the maintenance window using the AWS CLI. • Step 2: Register a target node with the maintenance window using the AWS CLI To configure an automation as a registered task for a maintenance window 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 command to configure an automation as a registered task for a maintenance window. Replace each example resource placeholder with your own information. Linux & macOS aws ssm register-task-with-maintenance-window \ --window-id window ID \ --name task name \ --task-arn runbook name \ --targets Key=targets,Values=value \ --service-role-arn IAM role arn \ Automation 1173 AWS Systems Manager User Guide --task-type AUTOMATION \ --task-invocation-parameters task parameters \ --priority task priority \ --max-concurrency 10% \ --max-errors 5 Note If you configure an automation as a registered task by using the AWS CLI, use the --Task-Invocation-Parameters parameter to specify parameters to pass to a task when it runs. Don't use the --Task-Parameters parameter. The --Task- Parameters parameter is a legacy parameter. For maintenance window tasks without a target specified, you can't supply values for --max-errors and --max-concurrency. Instead, the system inserts a placeholder value of 1, which might be reported in the response to commands such as describe-maintenance-window-tasks and get-maintenance-window-task. These values don't affect the running of your task and can be ignored. For information about maintenance window tasks that don't require targets, see Registering maintenance window tasks without targets. Windows aws ssm register-task-with-maintenance-window ^ --window-id window ID ^ --name task name ^ --task-arn runbook name ^ --targets Key=targets,Values=value ^ --service-role-arn IAM role arn ^ --task-type AUTOMATION ^ --task-invocation-parameters task parameters ^ --priority task priority ^ --max-concurrency 10% ^ --max-errors 5 Note If you configure an automation as a registered task by using the AWS CLI, use the --task-invocation-parameters parameter to specify parameters to pass to Automation 1174 AWS Systems Manager User Guide a task when it runs. Don't use the --task-parameters parameter. The --task- parameters parameter is a legacy parameter. For maintenance window tasks without a target specified, you can't supply values for --max-errors and --max-concurrency. Instead, the system inserts a placeholder value of 1, which might be reported in
|
systems-manager-ug-364
|
systems-manager-ug.pdf
| 364 |
IAM role arn ^ --task-type AUTOMATION ^ --task-invocation-parameters task parameters ^ --priority task priority ^ --max-concurrency 10% ^ --max-errors 5 Note If you configure an automation as a registered task by using the AWS CLI, use the --task-invocation-parameters parameter to specify parameters to pass to Automation 1174 AWS Systems Manager User Guide a task when it runs. Don't use the --task-parameters parameter. The --task- parameters parameter is a legacy parameter. For maintenance window tasks without a target specified, you can't supply values for --max-errors and --max-concurrency. Instead, the system inserts a placeholder value of 1, which might be reported in the response to commands such as describe-maintenance-window-tasks and get-maintenance-window-task. These values don't affect the running of your task and can be ignored. For information about maintenance window tasks that don't require targets, see Registering maintenance window tasks without targets. PowerShell Register-SSMTaskWithMaintenanceWindow ` -WindowId window ID ` -Name "task name" ` -TaskArn "runbook name" ` -Target @{ Key="targets";Values="value" } ` -ServiceRoleArn "IAM role arn" ` -TaskType "AUTOMATION" ` -Automation_Parameter @{ "task parameter"="task parameter value"} ` -Priority task priority ` -MaxConcurrency 10% ` -MaxError 5 Note If you configure an automation as a registered task by using the AWS Tools for PowerShell, use the -Automation_Parameter parameter to specify parameters to pass to a task when the task runs. Don't use the -TaskParameters parameter. The -TaskParameters parameter is a legacy parameter. For maintenance window tasks without a target specified, you can't supply values for -MaxError and -MaxConcurrency. Instead, the system inserts a placeholder value of 1, which might be reported in the response to commands such as Get- SSMMaintenanceWindowTaskList and Get-SSMMaintenanceWindowTask. These values don't affect the running of your task and can be ignored. Automation 1175 AWS Systems Manager User Guide For information about maintenance window tasks that don't require targets, see Registering maintenance window tasks without targets. The following example configures an automation as a registered task to a maintenance window with priority 1. It also demonstrates omitting the --targets, --max-errors, and --max-concurrency options for a targetless maintenance window task. The automation uses the AWS-StartEC2Instance runbook and the specified Automation assume role to start EC2 instances registered as targets to the maintenance window. The maintenance window runs the automation simultaneously on 5 instances maximum at any given time. Also, the registered task stops running on more instances for a particular interval if the error count exceeds 1. Linux & macOS aws ssm register-task-with-maintenance-window \ --window-id mw-0c50858d01EXAMPLE \ --name StartEC2Instances \ --task-arn AWS-StartEC2Instance \ --service-role-arn arn:aws:iam::123456789012:role/MaintenanceWindowRole \ --task-type AUTOMATION \ --task-invocation-parameters "{\"Automation\":{\"Parameters\":{\"InstanceId\": [\"{{TARGET_ID}}\"],\"AutomationAssumeRole\":[\"arn:aws:iam::123456789012:role/ AutomationAssumeRole\"]}}}" \ --priority 1 Windows aws ssm register-task-with-maintenance-window ^ --window-id mw-0c50858d01EXAMPLE ^ --name StartEC2Instances ^ --task-arn AWS-StartEC2Instance ^ --service-role-arn arn:aws:iam::123456789012:role/MaintenanceWindowRole ^ --task-type AUTOMATION ^ --task-invocation-parameters "{\"Automation\":{\"Parameters\":{\"InstanceId\": [\"{{TARGET_ID}}\"],\"AutomationAssumeRole\":[\"arn:aws:iam::123456789012:role/ AutomationAssumeRole\"]}}}" ^ --priority 1 Automation 1176 AWS Systems Manager PowerShell User Guide Register-SSMTaskWithMaintenanceWindow ` -WindowId mw-0c50858d01EXAMPLE ` -Name "StartEC2" ` -TaskArn "AWS-StartEC2Instance" ` -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowRole" ` -TaskType "AUTOMATION" ` -Automation_Parameter @{ "InstanceId"="{{TARGET_ID}}";"AutomationAssumeRole"="arn:aws:iam::123456789012:role/ AutomationAssumeRole" } ` -Priority 1 The command returns details for the new registered task similar to the following. Linux & macOS { "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" } Windows { "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" } PowerShell 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE 3. To view the registered task, run the following command. Replace maintenance windows ID with your own information. Linux & macOS aws ssm describe-maintenance-window-tasks \ --window-id maintenance window ID Automation 1177 AWS Systems Manager Windows User Guide aws ssm describe-maintenance-window-tasks ^ --window-id maintenance window ID PowerShell Get-SSMMaintenanceWindowTaskList ` -WindowId maintenance window ID The system returns information like the following. Linux & macOS { "Tasks": [ { "ServiceRoleArn": "arn:aws:iam::123456789012:role/ MaintenanceWindowRole", "MaxErrors": "1", "TaskArn": "AWS-StartEC2Instance", "MaxConcurrency": "1", "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE", "TaskParameters": {}, "Priority": 1, "WindowId": "mw-0c50858d01EXAMPLE", "Type": "AUTOMATION", "Targets": [ ], "Name": "StartEC2" } ] } Windows { "Tasks": [ { Automation 1178 AWS Systems Manager User Guide "ServiceRoleArn": "arn:aws:iam::123456789012:role/ MaintenanceWindowRole", "MaxErrors": "1", "TaskArn": "AWS-StartEC2Instance", "MaxConcurrency": "1", "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE", "TaskParameters": {}, "Priority": 1, "WindowId": "mw-0c50858d01EXAMPLE", "Type": "AUTOMATION", "Targets": [ ], "Name": "StartEC2" } ] } PowerShell Description : LoggingInfo : MaxConcurrency : 5 MaxErrors : 1 Name : StartEC2 Priority : 1 ServiceRoleArn : arn:aws:iam::123456789012:role/MaintenanceWindowRole Targets : {} TaskArn : AWS-StartEC2Instance TaskParameters : {} Type : AUTOMATION WindowId : mw-0c50858d01EXAMPLE WindowTaskId : 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE Systems Manager Automation actions reference This reference describes the Automation actions that you can specify in an Automation runbook. Automation is a tool in AWS Systems Manager. These actions can't be used in other types of Systems Manager (SSM) documents. For information about plugins for other types of SSM documents, see Command document plugin reference. Automation 1179 AWS Systems Manager User Guide Systems Manager Automation runs steps defined in Automation runbooks. Each step is associated with a particular action. The action determines the inputs, behavior, and outputs of the step. Steps are defined in the mainSteps section of your runbook. You don't need to specify the outputs of an action or step. The outputs are predetermined by the action
|
systems-manager-ug-365
|
systems-manager-ug.pdf
| 365 |
Automation is a tool in AWS Systems Manager. These actions can't be used in other types of Systems Manager (SSM) documents. For information about plugins for other types of SSM documents, see Command document plugin reference. Automation 1179 AWS Systems Manager User Guide Systems Manager Automation runs steps defined in Automation runbooks. Each step is associated with a particular action. The action determines the inputs, behavior, and outputs of the step. Steps are defined in the mainSteps section of your runbook. You don't need to specify the outputs of an action or step. The outputs are predetermined by the action associated with the step. When you specify step inputs in your runbooks, you can reference one or more outputs from an earlier step. For example, you can make the output of aws:runInstances available for a subsequent aws:runCommand action. You can also reference outputs from earlier steps in the Output section of the runbook. Important If you run an automation workflow that invokes other services by using an AWS Identity and Access Management (IAM) service role, be aware that the service role must be configured with permission to invoke those services. This requirement applies to all AWS Automation runbooks (AWS-* runbooks) such as the AWS-ConfigureS3BucketLogging, AWS-CreateDynamoDBBackup, and AWS-RestartEC2Instance runbooks, to name a few. This requirement also applies to any custom Automation 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, configure the service role with permission to invoke those services. You can give permissions to other AWS services by adding an IAM inline policy to the role. For more information, see (Optional) Add an Automation inline policy or customer managed policy to invoke other AWS services. Topics • Properties shared by all actions • aws:approve – Pause an automation for manual approval • aws:assertAwsResourceProperty – Assert an AWS resource state or event state • aws:branch – Run conditional automation steps • aws:changeInstanceState – Change or assert instance state • aws:copyImage – Copy or encrypt an Amazon Machine Image • aws:createImage – Create an Amazon Machine Image • aws:createStack – Create an AWS CloudFormation stack • aws:createTags – Create tags for AWS resources Automation 1180 AWS Systems Manager User Guide • aws:deleteImage – Delete an Amazon Machine Image • aws:deleteStack – Delete an AWS CloudFormation stack • aws:executeAutomation – Run another automation • aws:executeAwsApi – Call and run AWS API operations • aws:executeScript – Run a script • aws:executeStateMachine – Run an AWS Step Functions state machine • aws:invokeWebhook – Invoke an Automation webhook integration • aws:invokeLambdaFunction – Invoke an AWS Lambda function • aws:loop – Iterate over steps in an automation • aws:pause – Pause an automation • aws:runCommand – Run a command on a managed instance • aws:runInstances – Launch an Amazon EC2 instance • aws:sleep – Delay an automation • aws:updateVariable – Updates a value for a runbook variable • aws:waitForAwsResourceProperty – Wait on an AWS resource property • Automation system variables Properties shared by all actions Common properties are parameters or options that are found in all actions. Some options define behavior for a step, such as how long to wait for a step to complete and what to do if the step fails. The following properties are common to all actions. description Information you provide to describe the purpose of a runbook or a step. Type: String Required: No name An identifier that must be unique across all step names in the runbook. Type: String Allowed pattern: [a-zA-Z0-9_]+$ Automation 1181 AWS Systems Manager Required: Yes action User Guide The name of the action the step is to run. aws:runCommand – Run a command on a managed instance is an example of an action you can specify here. This document provides detailed information about all available actions. Type: String Required: Yes maxAttempts The number of times the step should be retried in case of failure. If the value is greater than 1, the step isn't considered to have failed until all retry attempts have failed. The default value is 1. Type: Integer Required: No timeoutSeconds The timeout value for the step. If the timeout is reached and the value of maxAttempts is greater than 1, then the step isn't considered to have timed out until all retries have been attempted. Type: Integer Required: No onFailure Indicates whether the automation should stop, continue, or go to a different step on failure. The default value for this option is abort. Type: String Valid values: Abort | Continue | step:step_name Required: No onCancel Indicates which step the automation should go to in the event that a user cancels the automation. Automation runs the cancellation workflow for a maximum of two minutes. Automation 1182 AWS Systems Manager Type: String Valid values: Abort | step:step_name Required:
|
systems-manager-ug-366
|
systems-manager-ug.pdf
| 366 |
is greater than 1, then the step isn't considered to have timed out until all retries have been attempted. Type: Integer Required: No onFailure Indicates whether the automation should stop, continue, or go to a different step on failure. The default value for this option is abort. Type: String Valid values: Abort | Continue | step:step_name Required: No onCancel Indicates which step the automation should go to in the event that a user cancels the automation. Automation runs the cancellation workflow for a maximum of two minutes. Automation 1182 AWS Systems Manager Type: String Valid values: Abort | step:step_name Required: No The onCancel property doesn't support moving to the following actions: User Guide • aws:approve • aws:copyImage • aws:createImage • aws:createStack • aws:createTags • aws:loop • aws:pause • aws:runInstances • aws:sleep isEnd This option stops an automation at the end of a specific step. The automation stops if the step failed or succeeded. The default value is false. Type: Boolean Valid values: true | false Required: No nextStep Specifies which step in an automation to process next after successfully completing a step. Type: String Required: No isCritical 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. This property is only evaluated if you explicitly define it in your step. If the onFailure property Automation 1183 AWS Systems Manager User Guide is set to Continue in a step, the value defaults to false. Otherwise, the default value for this option is true. Type: Boolean Valid values: true | false Required: No inputs The properties specific to the action. Type: Map Required: Yes Example --- description: "Custom Automation 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 }}" Automation 1184 AWS Systems Manager outputs: User Guide - 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 maxAttempts: 3 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 #Initialize client ec2 = boto3.client('ec2') rootVolumeId = events['rootVolumeId'] snapshotsQuery = ec2.describe_snapshots( Filters=[ { Automation 1185 AWS Systems Manager User Guide "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 onCancel: step:startInstance inputs: Choices: - NextStep: createNewRootVolumeFromSnapshot Not: Variable: "{{ getSnapshotsByStartTime.noSnapshotFound }}" StringEquals: "NoSnapshotFound" isEnd: true - name: createNewRootVolumeFromSnapshot action: aws:executeAwsApi onFailure: Abort inputs: Service: ec2 Api: CreateVolume AvailabilityZone: "{{ getInstanceDetails.availabilityZone }}" SnapshotId: "{{ getSnapshotsByStartTime.latestSnapshotId }}" Automation 1186 User Guide AWS Systems Manager 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 action: aws:executeAwsApi onFailure: Abort isCritical: true inputs: Service: ec2 Automation 1187 User Guide AWS Systems Manager 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 inputs: Service: ec2 Api: StartInstances InstanceIds: Automation 1188 AWS Systems Manager - "{{ InstanceId }}" User Guide aws:approve – Pause an
|
systems-manager-ug-367
|
systems-manager-ug.pdf
| 367 |
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 inputs: Service: ec2 Api: StartInstances InstanceIds: Automation 1188 AWS Systems Manager - "{{ InstanceId }}" User Guide aws:approve – Pause an automation for manual approval Temporarily pauses an automation until designated principals either approve or reject the action. After the required number of approvals is reached, the automation resumes. You can insert the approval step any place in the mainSteps section of your runbook. Note This action doesn't support multi-account and Region automations. The default timeout for this action is 7 days (604800 seconds) and the maximum value is 30 days (2592000 seconds). You can limit or extend the timeout by specifying the timeoutSeconds parameter for an aws:approve step. In the following example, the aws:approve action temporarily pauses the automation until one approver either accepts or rejects the automation. Upon approval, the automation runs a simple PowerShell command. YAML --- description: RunInstancesDemo1 schemaVersion: '0.3' assumeRole: "{{ assumeRole }}" parameters: assumeRole: type: String message: type: String mainSteps: - name: approve action: aws:approve timeoutSeconds: 1000 onFailure: Abort inputs: NotificationArn: arn:aws:sns:us-east-2:12345678901:AutomationApproval Message: "{{ message }}" MinRequiredApprovals: 1 Approvers: Automation 1189 AWS Systems Manager User Guide - arn:aws:iam::12345678901:user/AWS-User-1 - name: run action: aws:runCommand inputs: InstanceIds: - i-1a2b3c4d5e6f7g DocumentName: AWS-RunPowerShellScript Parameters: commands: - date JSON { "description":"RunInstancesDemo1", "schemaVersion":"0.3", "assumeRole":"{{ assumeRole }}", "parameters":{ "assumeRole":{ "type":"String" }, "message":{ "type":"String" } }, "mainSteps":[ { "name":"approve", "action":"aws:approve", "timeoutSeconds":1000, "onFailure":"Abort", "inputs":{ "NotificationArn":"arn:aws:sns:us- east-2:12345678901:AutomationApproval", "Message":"{{ message }}", "MinRequiredApprovals":1, "Approvers":[ "arn:aws:iam::12345678901:user/AWS-User-1" ] } }, { "name":"run", Automation 1190 AWS Systems Manager User Guide "action":"aws:runCommand", "inputs":{ "InstanceIds":[ "i-1a2b3c4d5e6f7g" ], "DocumentName":"AWS-RunPowerShellScript", "Parameters":{ "commands":[ "date" ] } } } ] } You can approve or deny Automations that are waiting for approval in the console. To approve or deny waiting Automations 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 option next to an Automation with a status of Waiting. 4. Choose Approve/Deny. 5. Review the details of the Automation. 6. Choose either Approve or Deny, type an optional comment, and then choose Submit. Input example Automation 1191 AWS Systems Manager YAML User Guide NotificationArn: arn:aws:sns:us-west-1:12345678901:Automation-ApprovalRequest Message: Please approve this step of the Automation. MinRequiredApprovals: 3 Approvers: - IamUser1 - IamUser2 - arn:aws:iam::12345678901:user/IamUser3 - arn:aws:iam::12345678901:role/IamRole JSON { "NotificationArn":"arn:aws:sns:us-west-1:12345678901:Automation-ApprovalRequest", "Message":"Please approve this step of the Automation.", "MinRequiredApprovals":3, "Approvers":[ "IamUser1", "IamUser2", "arn:aws:iam::12345678901:user/IamUser3", "arn:aws:iam::12345678901:role/IamRole" ] } NotificationArn The Amazon Resource Name (ARN of an Amazon Simple Notification Service (Amazon SNS) topic for Automation approvals. When you specify an aws:approve step in a runbook, Automation sends a message to this topic letting principals know that they must either approve or reject an Automation step. The title of the Amazon SNS topic must be prefixed with "Automation". Type: String Required: No Message The information you want to include in the Amazon SNS topic when the approval request is sent. The maximum message length is 4096 characters. Automation 1192 AWS Systems Manager Type: String Required: No MinRequiredApprovals User Guide The minimum number of approvals required to resume the automation. If you don't specify a value, the system defaults to one. The value for this parameter must be a positive number. The value for this parameter can't exceed the number of approvers defined by the Approvers parameter. Type: Integer Required: No Approvers A list of AWS authenticated principals who are able to either approve or reject the action. The maximum number of approvers is 10. You can specify principals by using any of the following formats: • A user name • A user ARN • An IAM role ARN • An IAM assume role ARN Type: StringList Required: Yes EnhancedApprovals This input is only used for Change Manager templates. A list of AWS authenticated principals who are able to either approve or reject the action, the type of IAM principal, and the minimum number of approvers. The following is an example: schemaVersion: "0.3" emergencyChange: false autoApprovable: false mainSteps: - name: ApproveAction1 action: aws:approve timeoutSeconds: 604800 Automation 1193 AWS Systems Manager inputs: User Guide Message: Please approve this change request MinRequiredApprovals: 3 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 Type: StringList Required: Yes Output ApprovalStatus The approval status of the step. The status can be one of the following: Approved, Rejected, or Waiting. Waiting means that Automation
|
systems-manager-ug-368
|
systems-manager-ug.pdf
| 368 |
minimum number of approvers. The following is an example: schemaVersion: "0.3" emergencyChange: false autoApprovable: false mainSteps: - name: ApproveAction1 action: aws:approve timeoutSeconds: 604800 Automation 1193 AWS Systems Manager inputs: User Guide Message: Please approve this change request MinRequiredApprovals: 3 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 Type: StringList Required: Yes Output ApprovalStatus The approval status of the step. The status can be one of the following: Approved, Rejected, or Waiting. Waiting means that Automation is waiting for input from approvers. Type: String ApproverDecisions A JSON map that includes the approval decision of each approver. Type: MapList aws:assertAwsResourceProperty – Assert an AWS resource state or event state The aws:assertAwsResourceProperty action allows you to assert a specific resource state or event state for a specific Automation step. Automation 1194 AWS Systems Manager User Guide For more examples of how to use this action, see Additional runbook examples. Input Inputs are defined by the API operation that you choose. YAML action: aws:assertAwsResourceProperty inputs: Service: The official namespace of the service Api: The API operation or method name API operation inputs or parameters: A value PropertySelector: Response object DesiredValues: - Desired property values JSON { "action": "aws:assertAwsResourceProperty", "inputs": { "Service":"The official namespace of the service", "Api":"The API operation or method name", "API operation inputs or parameters":"A value", "PropertySelector": "Response object", "DesiredValues": [ "Desired property values" ] } } Service The AWS service namespace that contains the API operation that you want to run. For example, the namespace for Systems Manager is ssm. The namespace for Amazon EC2 is ec2. You can view a list of supported AWS service namespaces in the Available Services section of the AWS CLI Command Reference. Type: String Required: Yes Automation 1195 AWS Systems Manager Api User Guide The name of the API operation that you want to run. 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. Type: String Required: Yes API operation inputs One or more API operation inputs. You can view the available inputs (also called parameters) 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 methods for Amazon RDS are listed on the following page: Amazon RDS methods. Choose the describe_db_instances method and scroll down to see the available parameters, such as DBInstanceIdentifier, Name, and Values. Use the following format to specify more than one input. YAML inputs: Service: The official namespace of the service Api: The API operation name API input 1: A value API Input 2: A value API Input 3: A value JSON "inputs":{ "Service":"The official namespace of the service", "Api":"The API operation name", "API input 1":"A value", "API Input 2":"A value", "API Input 3":"A value" } Type: Determined by chosen API operation Automation 1196 AWS Systems Manager Required: Yes PropertySelector User Guide The JSONPath to a specific attribute in the response object. You can view the response objects 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 methods for Amazon RDS are listed on the following page: Amazon RDS methods. Choose the describe_db_instances method and scroll down to the Response Structure section. DBInstances is listed as a response object. Type: String Required: Yes DesiredValues The expected status or state on which to continue the automation. If you specify a Boolean value, you must use a capital letter such as True or False. Type: StringList Required: Yes aws:branch – Run conditional automation steps The aws:branch action allows you to create a dynamic automation that evaluates different choices in a single step and then jumps to a different step in the runbook based on the results of that evaluation. When you specify the aws:branch action for a step, you specify Choices that the automation must evaluate. The Choices can be based on either a value that you specified in the Parameters section of the runbook, or a dynamic value generated as the output from the previous step. The automation evaluates each choice by using a Boolean expression. If the first choice is true, then the automation jumps to the step designated for that choice. If the first choice is false, the automation evaluates the next choice. The automation continues evaluating each
|
systems-manager-ug-369
|
systems-manager-ug.pdf
| 369 |
runbook based on the results of that evaluation. When you specify the aws:branch action for a step, you specify Choices that the automation must evaluate. The Choices can be based on either a value that you specified in the Parameters section of the runbook, or a dynamic value generated as the output from the previous step. The automation evaluates each choice by using a Boolean expression. If the first choice is true, then the automation jumps to the step designated for that choice. If the first choice is false, the automation evaluates the next choice. The automation continues evaluating each choice until it process a true choice. 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. Automation 1197 AWS Systems Manager User Guide The aws:branch action supports complex choice evaluations by using a combination of And, Not, and Or operators. For more information about how to use aws:branch, including example runbooks and examples that use different operators, see Using conditional statements in runbooks. Input Specify one or more Choices in a step. The Choices can be based on either a value that you specified in the Parameters section of the runbook, or a dynamic value generated as the output from the previous step. Here is a YAML sample that evaluates a parameter. mainSteps: - name: chooseOS action: aws:branch inputs: Choices: - NextStep: runWindowsCommand Variable: "{{Name of a parameter defined in the Parameters section. For example: OS_name}}" StringEquals: windows - NextStep: runLinuxCommand Variable: "{{Name of a parameter defined in the Parameters section. For example: OS_name}}" StringEquals: linux Default: sleep3 Here is a YAML sample that evaluates output from a previous step. mainSteps: - name: chooseOS action: aws:branch inputs: Choices: - NextStep: runPowerShellCommand Variable: "{{Name of a response object. For example: GetInstance.platform}}" StringEquals: Windows - NextStep: runShellCommand Variable: "{{Name of a response object. For example: GetInstance.platform}}" StringEquals: Linux Default: sleep3 Automation 1198 AWS Systems Manager Choices User Guide One or more expressions that the Automation should evaluate when determining the next step to process. 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. Or specify an output object from a previous step in the runbook. For more information about creating variables for aws:branch, see About creating the output variable. • Operation: The criteria used to evaluate the choice. 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 1199 AWS Systems Manager User Guide Important 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 The name of a step the automation should jump to if none of the Choices are true. Type: String Required: No Note The aws:branch action supports And, Or, and Not operators. For examples of aws:branch that use operators, see Using conditional statements in runbooks. aws:changeInstanceState – Change or assert instance state Changes or asserts the state of the instance. This action can be used in assert mode (doesn't run the API to change the state but verifies the instance is in the desired state.) To use assert mode, set the CheckStateOnly parameter to true. This mode is useful when running the Sysprep command on Windows, which is an asynchronous command that can run in the background for a long time. You can ensure that the instance is stopped before you create an Amazon Machine Image (AMI). Note The default timeout value for this action is 3600 seconds (one hour). You can limit or extend the timeout by specifying the timeoutSeconds parameter for an aws:changeInstanceState step. Input Automation 1200 User Guide AWS Systems Manager YAML name: stopMyInstance action: aws:changeInstanceState maxAttempts: 3 timeoutSeconds: 3600 onFailure: Abort inputs: InstanceIds: - i-1234567890abcdef0 CheckStateOnly: true DesiredState: stopped JSON { "name":"stopMyInstance", "action": "aws:changeInstanceState", "maxAttempts": 3, "timeoutSeconds": 3600, "onFailure": "Abort", "inputs": { "InstanceIds": ["i-1234567890abcdef0"], "CheckStateOnly": true, "DesiredState": "stopped" } } InstanceIds The IDs of the instances. Type: StringList Required: Yes CheckStateOnly If false, sets the instance state to the desired state. If true, asserts the desired state using polling. Default: false Automation 1201 AWS
|
systems-manager-ug-370
|
systems-manager-ug.pdf
| 370 |
(one hour). You can limit or extend the timeout by specifying the timeoutSeconds parameter for an aws:changeInstanceState step. Input Automation 1200 User Guide AWS Systems Manager YAML name: stopMyInstance action: aws:changeInstanceState maxAttempts: 3 timeoutSeconds: 3600 onFailure: Abort inputs: InstanceIds: - i-1234567890abcdef0 CheckStateOnly: true DesiredState: stopped JSON { "name":"stopMyInstance", "action": "aws:changeInstanceState", "maxAttempts": 3, "timeoutSeconds": 3600, "onFailure": "Abort", "inputs": { "InstanceIds": ["i-1234567890abcdef0"], "CheckStateOnly": true, "DesiredState": "stopped" } } InstanceIds The IDs of the instances. Type: StringList Required: Yes CheckStateOnly If false, sets the instance state to the desired state. If true, asserts the desired state using polling. Default: false Automation 1201 AWS Systems Manager Type: Boolean Required: No DesiredState User Guide The desired state. When set to running, this action waits for the Amazon EC2 state to be Running, the Instance Status to be OK, and the System Status to be OK before completing. Type: String Valid values: running | stopped | terminated Required: Yes Force If set, forces the instances to stop. The instances don't have an opportunity to flush file system caches or file system metadata. If you use this option, you must perform file system check and repair procedures. This option isn't recommended for EC2 instances for Windows Server. Type: Boolean Required: No AdditionalInfo Reserved. Type: String Required: No Output None aws:copyImage – Copy or encrypt an Amazon Machine Image Copies an Amazon Machine Image (AMI) from any AWS Region into the current Region. This action can also encrypt the new AMI. Input Automation 1202 AWS Systems Manager User Guide This action supports most CopyImage parameters. For more information, see CopyImage. The following example creates a copy of an AMI in the Seoul region (SourceImageID: ami-0fe10819. SourceRegion: ap-northeast-2). The new AMI is copied to the region where you initiated the Automation action. The copied AMI will be encrypted because the optional Encrypted flag is set to true. YAML name: createEncryptedCopy action: aws:copyImage maxAttempts: 3 onFailure: Abort inputs: SourceImageId: ami-0fe10819 SourceRegion: ap-northeast-2 ImageName: Encrypted Copy of LAMP base AMI in ap-northeast-2 Encrypted: true JSON { "name": "createEncryptedCopy", "action": "aws:copyImage", "maxAttempts": 3, "onFailure": "Abort", "inputs": { "SourceImageId": "ami-0fe10819", "SourceRegion": "ap-northeast-2", "ImageName": "Encrypted Copy of LAMP base AMI in ap-northeast-2", "Encrypted": true } } SourceRegion The region where the source AMI exists. Type: String Required: Yes Automation 1203 AWS Systems Manager SourceImageId The AMI ID to copy from the source Region. User Guide Type: String Required: Yes ImageName The name for the new image. Type: String Required: Yes ImageDescription A description for the target image. Type: String Required: No Encrypted Encrypt the target AMI. Type: Boolean Required: No KmsKeyId The full Amazon Resource Name (ARN) of the AWS KMS key to use when encrypting the snapshots of an image during a copy operation. For more information, see CopyImage. Type: String Required: No ClientToken A unique, case-sensitive identifier that you provide to ensure request idempotency. For more information, see CopyImage. Type: String Automation 1204 User Guide AWS Systems Manager Required: No Output ImageId The ID of the copied image. ImageState The state of the copied image. Valid values: available | pending | failed aws:createImage – Create an Amazon Machine Image Creates an Amazon Machine Image (AMI) from an instance that is either running, stopping, or stopped, and polls for the ImageState to be available. Input This action supports the following CreateImage parameters. For more information, see CreateImage. YAML name: createMyImage action: aws:createImage maxAttempts: 3 onFailure: Abort inputs: InstanceId: i-1234567890abcdef0 ImageName: AMI Created on{{global:DATE_TIME}} NoReboot: true ImageDescription: My newly created AMI JSON { "name": "createMyImage", "action": "aws:createImage", "maxAttempts": 3, Automation 1205 AWS Systems Manager User Guide "onFailure": "Abort", "inputs": { "InstanceId": "i-1234567890abcdef0", "ImageName": "AMI Created on{{global:DATE_TIME}}", "NoReboot": true, "ImageDescription": "My newly created AMI" } } InstanceId The ID of the instance. Type: String Required: Yes ImageName The name for the image. Type: String Required: Yes ImageDescription A description of the image. Type: String Required: No NoReboot A Boolean literal. By default, Amazon Elastic Compute Cloud (Amazon EC2) attempts to shut down and reboot the instance before creating the image. If the No Reboot option is set to true, Amazon EC2 doesn't shut down the instance before creating the image. When this option is used, file system integrity on the created image can't be guaranteed. If you don't want the instance to run after you create an AMI from it, first use the aws:changeInstanceState – Change or assert instance state action to stop the instance, and then use this aws:createImage action with the NoReboot option set to true. Automation 1206 User Guide AWS Systems Manager Type: Boolean Required: No BlockDeviceMappings The block devices for the instance. Type: Map Required: No Output ImageId The ID of the newly created image. Type: String ImageState The current state of the image. If the state is available, the image is successfully registered and can be used to launch an
|
systems-manager-ug-371
|
systems-manager-ug.pdf
| 371 |
If you don't want the instance to run after you create an AMI from it, first use the aws:changeInstanceState – Change or assert instance state action to stop the instance, and then use this aws:createImage action with the NoReboot option set to true. Automation 1206 User Guide AWS Systems Manager Type: Boolean Required: No BlockDeviceMappings The block devices for the instance. Type: Map Required: No Output ImageId The ID of the newly created image. Type: String ImageState The current state of the image. If the state is available, the image is successfully registered and can be used to launch an instance. Type: String aws:createStack – Create an AWS CloudFormation stack Creates an AWS CloudFormation stack from a template. For supplemental information about creating CloudFormation stacks, see CreateStack in the AWS CloudFormation API Reference. Input YAML name: makeStack action: aws:createStack maxAttempts: 1 onFailure: Abort inputs: Capabilities: Automation 1207 AWS Systems Manager - CAPABILITY_IAM User Guide StackName: myStack TemplateURL: http://s3.amazonaws.com/amzn-s3-demo-bucket/myStackTemplate TimeoutInMinutes: 5 Parameters: - ParameterKey: LambdaRoleArn ParameterValue: "{{LambdaAssumeRole}}" - ParameterKey: createdResource ParameterValue: createdResource-{{automation:EXECUTION_ID}} JSON { "name": "makeStack", "action": "aws:createStack", "maxAttempts": 1, "onFailure": "Abort", "inputs": { "Capabilities": [ "CAPABILITY_IAM" ], "StackName": "myStack", "TemplateURL": "http://s3.amazonaws.com/amzn-s3-demo-bucket/ myStackTemplate", "TimeoutInMinutes": 5, "Parameters": [ { "ParameterKey": "LambdaRoleArn", "ParameterValue": "{{LambdaAssumeRole}}" }, { "ParameterKey": "createdResource", "ParameterValue": "createdResource-{{automation:EXECUTION_ID}}" } } } Capabilities A list of values that you specify before CloudFormation can create certain stacks. Some stack templates include resources that can affect permissions in your AWS account. For those stacks, you must explicitly acknowledge their capabilities by specifying this parameter. Automation 1208 AWS Systems Manager User Guide Valid values include CAPABILITY_IAM, CAPABILITY_NAMED_IAM, and CAPABILITY_AUTO_EXPAND. CAPABILITY_IAM and CAPABILITY_NAMED_IAM If you have IAM resources, you can specify either capability. If you have IAM resources with custom names, you must specify CAPABILITY_NAMED_IAM. If you don't specify this parameter, this action returns an InsufficientCapabilities error. The following resources require you to specify either CAPABILITY_IAM or CAPABILITY_NAMED_IAM. • AWS::IAM::AccessKey • AWS::IAM::Group • AWS::IAM::InstanceProfile • AWS::IAM::Policy • AWS::IAM::Role • AWS::IAM::User • AWS::IAM::UserToGroupAddition If your stack template contains these resources, we recommend that you review all permissions associated with them and edit their permissions, if necessary. For more information, see Acknowledging IAM Resources in AWS CloudFormation Templates. CAPABILITY_AUTO_EXPAND Some template contain macros. Macros perform custom processing on templates; this can include simple actions like find-and-replace operations, all the way to extensive transformations of entire templates. Because of this, users typically create a change set from the processed template, so that they can review the changes resulting from the macros before actually creating the stack. If your stack template contains one or more macros, and you choose to create a stack directly from the processed template, without first reviewing the resulting changes in a change set, you must acknowledge this capability. For more information, see Using AWS CloudFormation Macros to Perform Custom Processing on Templates in the AWS CloudFormation User Guide. Type: array of Strings Valid Values: CAPABILITY_IAM | CAPABILITY_NAMED_IAM | CAPABILITY_AUTO_EXPAND Automation 1209 AWS Systems Manager Required: No ClientRequestToken User Guide A unique identifier for this CreateStack request. Specify this token if you set maxAttempts in this step to a value greater than 1. By specifying this token, CloudFormation knows that you aren't attempting to create a new stack with the same name. Type: String Required: No Length Constraints: Minimum length of 1. Maximum length of 128. Pattern: [a-zA-Z0-9][-a-zA-Z0-9]* DisableRollback Set to true to turn off rollback of the stack if stack creation failed. Conditional: You can specify either the DisableRollback parameter or the OnFailure parameter, but not both. Default: false Type: Boolean Required: No NotificationARNs The Amazon Simple Notification Service (Amazon SNS) topic ARNs for publishing stack- related events. You can find SNS topic ARNs using the Amazon SNS console, https:// console.aws.amazon.com/sns/v3/home. Type: array of Strings Array Members: Maximum number of 5 items. Required: No OnFailure Determines the action to take if stack creation failed. You must specify DO_NOTHING, ROLLBACK, or DELETE. Automation 1210 AWS Systems Manager User Guide Conditional: You can specify either the OnFailure parameter or the DisableRollback parameter, but not both. Default: ROLLBACK Type: String Valid Values: DO_NOTHING | ROLLBACK | DELETE Required: No Parameters A list of Parameter structures that specify input parameters for the stack. For more information, see the Parameter data type. Type: array of Parameter objects Required: No ResourceTypes The template resource types that you have permissions to work with for this create stack action. For example: AWS::EC2::Instance, AWS::EC2::*, or Custom::MyCustomInstance. Use the following syntax to describe template resource types. • For all AWS resources: AWS::* • For all custom resources: Custom::* • For a specific custom resource: Custom::logical_ID • For all resources of a particular AWS service: AWS::service_name::* • For a specific AWS resource: Automation 1211 AWS Systems Manager User Guide AWS::service_name::resource_logical_ID If the list of resource types doesn't include a resource that you're creating, the stack creation
|
systems-manager-ug-372
|
systems-manager-ug.pdf
| 372 |
data type. Type: array of Parameter objects Required: No ResourceTypes The template resource types that you have permissions to work with for this create stack action. For example: AWS::EC2::Instance, AWS::EC2::*, or Custom::MyCustomInstance. Use the following syntax to describe template resource types. • For all AWS resources: AWS::* • For all custom resources: Custom::* • For a specific custom resource: Custom::logical_ID • For all resources of a particular AWS service: AWS::service_name::* • For a specific AWS resource: Automation 1211 AWS Systems Manager User Guide AWS::service_name::resource_logical_ID If the list of resource types doesn't include a resource that you're creating, the stack creation fails. By default, CloudFormation grants permissions to all resource types. IAM uses this parameter for CloudFormation-specific condition keys in IAM policies. For more information, see Controlling Access with AWS Identity and Access Management. Type: array of Strings Length Constraints: Minimum length of 1. Maximum length of 256. Required: No RoleARN The Amazon Resource Name (ARN) of an IAM role that CloudFormation assumes to create the stack. CloudFormation uses the role's credentials to make calls on your behalf. CloudFormation always uses this role for all future operations on the stack. As long as users have permission to operate on the stack, CloudFormation uses this role even if the users don't have permission to pass it. Ensure that the role grants the least amount of privileges. If you don't specify a value, CloudFormation uses the role that was previously associated with the stack. If no role is available, CloudFormation uses a temporary session that is generated from your user credentials. Type: String Length Constraints: Minimum length of 20. Maximum length of 2048. Required: No StackName The name that is associated with the stack. The name must be unique in the Region in which you're creating the stack. Note A stack name can contain only alphanumeric characters (case sensitive) and hyphens. It must start with an alphabetic character and can't be longer than 128 characters. Automation 1212 AWS Systems Manager Type: String Required: Yes StackPolicyBody User Guide Structure containing the stack policy body. For more information, see Prevent Updates to Stack Resources. Conditional: You can specify either the StackPolicyBody parameter or the StackPolicyURL parameter, but not both. Type: String Length Constraints: Minimum length of 1. Maximum length of 16384. Required: No StackPolicyURL Location of a file containing the stack policy. The URL must point to a policy located in an S3 bucket in the same region as the stack. The maximum file size allowed for the stack policy is 16 KB. Conditional: You can specify either the StackPolicyBody parameter or the StackPolicyURL parameter, but not both. Type: String Length Constraints: Minimum length of 1. Maximum length of 1350. Required: No Tags Key-value pairs to associate with this stack. CloudFormation also propagates these tags to the resources created in the stack. You can specify a maximum number of 10 tags. Type: array of Tag objects Required: No TemplateBody Structure containing the template body with a minimum length of 1 byte and a maximum length of 51,200 bytes. For more information, see Template Anatomy. Automation 1213 AWS Systems Manager User Guide Conditional: You can specify either the TemplateBody parameter or the TemplateURL parameter, but not both. Type: String Length Constraints: Minimum length of 1. Required: No TemplateURL Location of a file containing the template body. The URL must point to a template that is located in an S3 bucket. The maximum size allowed for the template is 460,800 bytes. For more information, see Template Anatomy. Conditional: You can specify either the TemplateBody parameter or the TemplateURL parameter, but not both. Type: String Length Constraints: Minimum length of 1. Maximum length of 1024. Required: No TimeoutInMinutes The amount of time that can pass before the stack status becomes CREATE_FAILED. If DisableRollback isn't set or is set to false, the stack will be rolled back. Type: Integer Valid Range: Minimum value of 1. Required: No Outputs StackId Unique identifier of the stack. Type: String Automation 1214 AWS Systems Manager StackStatus Current status of the stack. Type: String User Guide Valid Values: CREATE_IN_PROGRESS | CREATE_FAILED | CREATE_COMPLETE | ROLLBACK_IN_PROGRESS | ROLLBACK_FAILED | ROLLBACK_COMPLETE | DELETE_IN_PROGRESS | DELETE_FAILED | DELETE_COMPLETE | UPDATE_IN_PROGRESS | UPDATE_COMPLETE_CLEANUP_IN_PROGRESS | UPDATE_COMPLETE | UPDATE_ROLLBACK_IN_PROGRESS | UPDATE_ROLLBACK_FAILED | UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS | UPDATE_ROLLBACK_COMPLETE | REVIEW_IN_PROGRESS Required: Yes StackStatusReason Success or failure message associated with the stack status. Type: String Required: No For more information, see CreateStack. Security considerations Before you can use the aws:createStack action, you must assign the following policy to the IAM Automation assume role. For more information about the assume role, see Task 1: Create a service role for Automation. { "Version":"2012-10-17", "Statement":[ { "Effect":"Allow", "Action":[ "sqs:*", "cloudformation:CreateStack", "cloudformation:DescribeStacks" ], Automation 1215 AWS Systems Manager "Resource":"*" } ] } User Guide aws:createTags – Create tags for AWS resources Creates new tags for Amazon Elastic Compute
|
systems-manager-ug-373
|
systems-manager-ug.pdf
| 373 |
UPDATE_ROLLBACK_FAILED | UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS | UPDATE_ROLLBACK_COMPLETE | REVIEW_IN_PROGRESS Required: Yes StackStatusReason Success or failure message associated with the stack status. Type: String Required: No For more information, see CreateStack. Security considerations Before you can use the aws:createStack action, you must assign the following policy to the IAM Automation assume role. For more information about the assume role, see Task 1: Create a service role for Automation. { "Version":"2012-10-17", "Statement":[ { "Effect":"Allow", "Action":[ "sqs:*", "cloudformation:CreateStack", "cloudformation:DescribeStacks" ], Automation 1215 AWS Systems Manager "Resource":"*" } ] } User Guide aws:createTags – Create tags for AWS resources Creates new tags for Amazon Elastic Compute Cloud (Amazon EC2) instances or AWS Systems Manager managed instances. Input This action supports most Amazon EC2 CreateTags and Systems Manager AddTagsToResource parameters. For more information, see CreateTags and AddTagsToResource. The following example shows how to tag an Amazon Machine Image (AMI) and an instance as production resources for a particular department. YAML name: createTags action: aws:createTags maxAttempts: 3 onFailure: Abort inputs: ResourceType: EC2 ResourceIds: - ami-9a3768fa - i-02951acd5111a8169 Tags: - Key: production Value: '' - Key: department Value: devops JSON { "name": "createTags", "action": "aws:createTags", "maxAttempts": 3, "onFailure": "Abort", Automation 1216 AWS Systems Manager User Guide "inputs": { "ResourceType": "EC2", "ResourceIds": [ "ami-9a3768fa", "i-02951acd5111a8169" ], "Tags": [ { "Key": "production", "Value": "" }, { "Key": "department", "Value": "devops" } ] } } ResourceIds The IDs of the resource(s) to be tagged. If resource type isn't “EC2”, this field can contain only a single item. Type: String List Required: Yes Tags The tags to associate with the resource(s). Type: List of Maps Required: Yes ResourceType The type of resource(s) to be tagged. If not supplied, the default value of “EC2” is used. Type: String Required: No Automation 1217 AWS Systems Manager User Guide Valid Values: EC2 | ManagedInstance | MaintenanceWindow | Parameter Output None aws:deleteImage – Delete an Amazon Machine Image Deletes the specified Amazon Machine Image (AMI) and all related snapshots. Input This action supports only one parameter. For more information, see the documentation for DeregisterImage and DeleteSnapshot. YAML name: deleteMyImage action: aws:deleteImage maxAttempts: 3 timeoutSeconds: 180 onFailure: Abort inputs: ImageId: ami-12345678 JSON { "name": "deleteMyImage", "action": "aws:deleteImage", "maxAttempts": 3, "timeoutSeconds": 180, "onFailure": "Abort", "inputs": { "ImageId": "ami-12345678" } } ImageId The ID of the image to be deleted. Automation 1218 User Guide AWS Systems Manager Type: String Required: Yes Output None aws:deleteStack – Delete an AWS CloudFormation stack Deletes an AWS CloudFormation stack. Input YAML name: deleteStack action: aws:deleteStack maxAttempts: 1 onFailure: Abort inputs: StackName: "{{stackName}}" JSON { "name":"deleteStack", "action":"aws:deleteStack", "maxAttempts":1, "onFailure":"Abort", "inputs":{ "StackName":"{{stackName}}" } } ClientRequestToken A unique identifier for this DeleteStack request. Specify this token if you plan to retry requests so that CloudFormation knows that you aren't attempting to delete a stack with the same name. You can retry DeleteStack requests to verify that CloudFormation received them. Automation 1219 AWS Systems Manager Type: String User Guide Length Constraints: Minimum length of 1. Maximum length of 128. Pattern: [a-zA-Z][-a-zA-Z0-9]* Required: No RetainResources.member.N This input applies only to stacks that are in a DELETE_FAILED state. A list of logical resource IDs for the resources you want to retain. During deletion, CloudFormation deletes the stack, but doesn't delete the retained resources. Retaining resources is useful when you can't delete a resource, such as a non-empty S3 bucket, but you want to delete the stack. Type: array of strings Required: No RoleARN The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role that CloudFormation assumes to create the stack. CloudFormation uses the role's credentials to make calls on your behalf. CloudFormation always uses this role for all future operations on the stack. As long as users have permission to operate on the stack, CloudFormation uses this role even if the users don't have permission to pass it. Ensure that the role grants the least amount of privileges. If you don't specify a value, CloudFormation uses the role that was previously associated with the stack. If no role is available, CloudFormation uses a temporary session that is generated from your user credentials. Type: String Length Constraints: Minimum length of 20. Maximum length of 2048. Required: No StackName The name or the unique stack ID that is associated with the stack. Automation 1220 AWS Systems Manager Type: String Required: Yes Security considerations User Guide Before you can use the aws:deleteStack action, you must assign the following policy to the IAM Automation assume role. For more information about the assume role, see Task 1: Create a service role for Automation. { "Version":"2012-10-17", "Statement":[ { "Effect":"Allow", "Action":[ "sqs:*", "cloudformation:DeleteStack", "cloudformation:DescribeStacks" ], "Resource":"*" } ] } aws:executeAutomation – Run another automation Runs a secondary automation by calling a secondary runbook. With this action, you can create runbooks for your most common operations, and reference those runbooks during an automation. This
|
systems-manager-ug-374
|
systems-manager-ug.pdf
| 374 |
associated with the stack. Automation 1220 AWS Systems Manager Type: String Required: Yes Security considerations User Guide Before you can use the aws:deleteStack action, you must assign the following policy to the IAM Automation assume role. For more information about the assume role, see Task 1: Create a service role for Automation. { "Version":"2012-10-17", "Statement":[ { "Effect":"Allow", "Action":[ "sqs:*", "cloudformation:DeleteStack", "cloudformation:DescribeStacks" ], "Resource":"*" } ] } aws:executeAutomation – Run another automation Runs a secondary automation by calling a secondary runbook. With this action, you can create runbooks for your most common operations, and reference those runbooks during an automation. This action can simplify your runbooks by removing the need to duplicate steps across similar runbooks. The secondary automation runs in the context of the user who initiated the primary automation. This means that the secondary automation uses the same AWS Identity and Access Management (IAM) role or user as the user who started the first automation. Important If you specify parameters in a secondary automation that use an assume role (a role that uses the iam:passRole policy), then the user or role that initiated the primary automation must have permission to pass the assume role specified in the secondary automation. For Automation 1221 AWS Systems Manager User Guide more information about setting up an assume role for Automation, see Create the service roles for Automation using the console. Input YAML name: Secondary_Automation action: aws:executeAutomation maxAttempts: 3 timeoutSeconds: 3600 onFailure: Abort inputs: DocumentName: secondaryAutomation RuntimeParameters: instanceIds: - i-1234567890abcdef0 JSON { "name":"Secondary_Automation", "action":"aws:executeAutomation", "maxAttempts":3, "timeoutSeconds":3600, "onFailure":"Abort", "inputs":{ "DocumentName":"secondaryAutomation", "RuntimeParameters":{ "instanceIds":[ "i-1234567890abcdef0" ] } } } DocumentName The name of the secondary runbook to run during the step. For runbooks in the same AWS account, specify the runbook name. For runbooks shared from a different AWS account, Automation 1222 AWS Systems Manager User Guide specify the Amazon Resource Name (ARN) of the runbook. For information about using shared runbooks, see Using shared SSM documents. Type: String Required: Yes DocumentVersion The version of the secondary runbook to run. If not specified, Automation runs the default runbook version. Type: String Required: No MaxConcurrency The maximum number of targets allowed to run this task in parallel. You can specify a number, such as 10, or a percentage, such as 10%. Type: String Required: No MaxErrors The number of errors that are allowed before the system stops running the automation on additional targets. You can specify either an absolute number of errors, for example 10, or a percentage of the target set, for example 10%. If you specify 3, for example, the system stops running the automation when the fourth error is received. If you specify 0, then the system stops running the automation on additional targets after the first error result is returned. If you run an automation on 50 resources and set MaxErrors to 10%, then the system stops running the automation on additional targets when the sixth error is received. Automations that are already running when the MaxErrors threshold is reached are allowed to complete, but some of these automations may fail as well. If you need to ensure that there won't be more failed automations than the specified MaxErrors, set MaxConcurrency to 1 so the automations proceed one at a time. Type: String Required: No Automation 1223 AWS Systems Manager RuntimeParameters User Guide Required parameters for the secondary runbook. The mapping uses the following format: {"parameter1" : "value1", "parameter2" : "value2" } Type: Map Required: No Tags Optional metadata that you assign to a resource. You can specify a maximum of five tags for an automation. Type: MapList Required: No TargetLocations A location is a combination of AWS Regions and/or AWS accounts where you want to run the automation. A minimum number of 1 item must be specified and a maximum number of 100 items can be specified. When specifying a value for this parameter, outputs aren't returned to the parent automation. If needed, you must make subsequent calls to API operations to retrieve the output from child automations. Type: MapList Required: No TargetMaps A list of key-value mappings of document parameters to target resources. Both Targets and TargetMaps can't be specified together. Type: MapList Required: No TargetParameterName The name of the parameter used as the target resource for the rate-controlled automation. Required if you specify Targets. Type: String Required: No Automation 1224 AWS Systems Manager Targets User Guide A list of key-value mappings to target resources. Required if you specify TargetParameterName. Type: MapList Required: No Output Output The output generated by the secondary automation. You can reference the output by using the following format: Secondary_Automation_Step_Name.Output Type: StringList Here is an example: - name: launchNewWindowsInstance action: 'aws:executeAutomation' onFailure: Abort inputs: DocumentName: launchWindowsInstance nextStep: getNewInstanceRootVolume - name: getNewInstanceRootVolume action: 'aws:executeAwsApi' onFailure: Abort inputs: Service: ec2 Api: DescribeVolumes Filters: - Name: attachment.device Values: - /dev/sda1
|
systems-manager-ug-375
|
systems-manager-ug.pdf
| 375 |
used as the target resource for the rate-controlled automation. Required if you specify Targets. Type: String Required: No Automation 1224 AWS Systems Manager Targets User Guide A list of key-value mappings to target resources. Required if you specify TargetParameterName. Type: MapList Required: No Output Output The output generated by the secondary automation. You can reference the output by using the following format: Secondary_Automation_Step_Name.Output Type: StringList Here is an example: - name: launchNewWindowsInstance action: 'aws:executeAutomation' onFailure: Abort inputs: DocumentName: launchWindowsInstance nextStep: getNewInstanceRootVolume - name: getNewInstanceRootVolume action: 'aws:executeAwsApi' onFailure: Abort inputs: Service: ec2 Api: DescribeVolumes Filters: - Name: attachment.device Values: - /dev/sda1 - Name: attachment.instance-id Values: - '{{launchNewWindowsInstance.Output}}' outputs: - Name: rootVolumeId Selector: '$.Volumes[0].VolumeId' Type: String Automation 1225 AWS Systems Manager User Guide nextStep: snapshotRootVolume - name: snapshotRootVolume action: 'aws:executeAutomation' onFailure: Abort inputs: DocumentName: AWS-CreateSnapshot RuntimeParameters: VolumeId: - '{{getNewInstanceRootVolume.rootVolumeId}}' Description: - 'Initial root snapshot for {{launchNewWindowsInstance.Output}}' ExecutionId The ID of the secondary automation. Type: String Status The status of the secondary automation. Type: String aws:executeAwsApi – Call and run AWS API operations Calls and runs AWS API operations. Most API operations are supported, although not all API operations have been tested. Streaming API operations, such as the GetObject operation, aren't supported. If you're not sure if an API operation you want to use is a streaming operation, review the Boto3 documentation for the service to determine if an API requires streaming inputs or outputs. We regularly update the Boto3 version used by this action. However, following the release of a new Boto3 version it can take up to a few weeks for changes to be reflected in this action. Each aws:executeAwsApi action can run up to a maximum duration of 25 seconds. For more examples of how to use this action, see Additional runbook examples. Inputs Inputs are defined by the API operation that you choose. YAML action: aws:executeAwsApi inputs: Automation 1226 AWS Systems Manager User Guide Service: The official namespace of the service Api: The API operation or method name API operation inputs or parameters: A value outputs: # These are user-specified outputs - Name: The name for a user-specified output key Selector: A response object specified by using jsonpath format Type: The data type JSON { "action":"aws:executeAwsApi", "inputs":{ "Service":"The official namespace of the service", "Api":"The API operation or method name", "API operation inputs or parameters":"A value" }, "outputs":[ These are user-specified outputs { "Name":"The name for a user-specified output key", "Selector":"A response object specified by using JSONPath format", "Type":"The data type" } ] } Service The AWS service namespace that contains the API operation that you want to run. You can view a list of supported AWS service namespaces in Available services of the AWS SDK for Python (Boto3). The namespace can be found in the Client section. For example, the namespace for Systems Manager is ssm. The namespace for Amazon Elastic Compute Cloud (Amazon EC2) is ec2. Type: String Required: Yes Api The name of the API operation that you want to run. You can view the API operations (also called methods) by choosing a service in the left navigation on the following Services Reference Automation 1227 AWS Systems Manager User Guide 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. Type: String Required: Yes API operation inputs One or more API operation inputs. You can view the available inputs (also called parameters) 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 methods for Amazon RDS are listed on the following page: Amazon RDS methods. Choose the describe_db_instances method and scroll down to see the available parameters, such as DBInstanceIdentifier, Name, and Values. YAML inputs: Service: The official namespace of the service Api: The API operation name API input 1: A value API Input 2: A value API Input 3: A value JSON "inputs":{ "Service":"The official namespace of the service", "Api":"The API operation name", "API input 1":"A value", "API Input 2":"A value", "API Input 3":"A value" } Type: Determined by chosen API operation Required: Yes Outputs Automation 1228 AWS Systems Manager User Guide Outputs are specified by the user based on the response from the chosen API operation. Name A name for the output. Type: String Required: Yes Selector The JSONPath to a specific attribute in the response object. You can view the response objects 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 methods for Amazon RDS are listed on the following page:
|
systems-manager-ug-376
|
systems-manager-ug.pdf
| 376 |
Type: Determined by chosen API operation Required: Yes Outputs Automation 1228 AWS Systems Manager User Guide Outputs are specified by the user based on the response from the chosen API operation. Name A name for the output. Type: String Required: Yes Selector The JSONPath to a specific attribute in the response object. You can view the response objects 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 methods for Amazon RDS are listed on the following page: Amazon RDS methods. Choose the describe_db_instances method and scroll down to the Response Structure section. DBInstances is listed as a response object. Type: Integer, Boolean, String, StringList, StringMap, or MapList Required: Yes Type The data type for the response element. Type: Varies Required: Yes aws:executeScript – Run a script Runs the Python or PowerShell script provided using the specified runtime and handler. Each aws:executeScript action can run up to a maximum duration of 600 seconds (10 minutes). You can limit the timeout by specifying the timeoutSeconds parameter for an aws:executeScript step. Use return statements in your function to add outputs to your output payload. For examples of defining outputs for your aws:executeScript action, see Example 2: Scripted runbook. You can also send the output from aws:executeScript actions in your runbooks to the Amazon CloudWatch Logs log group you specify. For more information, see Logging Automation action output with CloudWatch Logs. Automation 1229 AWS Systems Manager User Guide If you want to send output from aws:executeScript actions to CloudWatch Logs, or if the scripts you specify for aws:executeScript actions call AWS API operations, an AWS Identity and Access Management (IAM) service role (or assume role) is always required to run the runbook. The aws:executeScript action contains the following preinstalled PowerShell Core modules: • Microsoft.PowerShell.Host • Microsoft.PowerShell.Management • Microsoft.PowerShell.Security • Microsoft.PowerShell.Utility • PackageManagement • PowerShellGet To use PowerShell Core modules that aren't preinstalled, your script must install the module with the -Force flag, as shown in the following command. The AWSPowerShell.NetCore module isn't supported. Replace ModuleName with the module you want to install. Install-Module ModuleName -Force To use PowerShell Core cmdlets in your script, we recommend using the AWS.Tools modules, as shown in the following commands. Replace each example resource placeholder with your own information. • Amazon S3 cmdlets. Install-Module AWS.Tools.S3 -Force Get-S3Bucket -BucketName amzn-s3-demo-bucket • Amazon EC2 cmdlets. Install-Module AWS.Tools.EC2 -Force Get-EC2InstanceStatus -InstanceId instance-id • Common, or service independent AWS Tools for Windows PowerShell cmdlets. Install-Module AWS.Tools.Common -Force Get-AWSRegion Automation 1230 AWS Systems Manager User Guide If your script initializes new objects in addition to using PowerShell Core cmdlets, you must also import the module as shown in the following command. Install-Module AWS.Tools.EC2 -Force Import-Module AWS.Tools.EC2 $tag = New-Object Amazon.EC2.Model.Tag $tag.Key = "Tag" $tag.Value = "TagValue" New-EC2Tag -Resource i-02573cafcfEXAMPLE -Tag $tag For examples of installing and importing AWS.Tools modules, and using PowerShell Core cmdlets in runbooks, see Visual design experience for Automation runbooks. Input Provide the information required to run your script. Replace each example resource placeholder with your own information. Note The attachment for a Python script can be a .py file or a .zip file that contains the script. PowerShell scripts must be stored in .zip files. YAML action: "aws:executeScript" inputs: Runtime: runtime Handler: "functionName" InputPayload: scriptInput: '{{parameterValue}}' Script: |- def functionName(events, context): ... Attachment: "scriptAttachment.zip" JSON { Automation 1231 AWS Systems Manager User Guide "action": "aws:executeScript", "inputs": { "Runtime": "runtime", "Handler": "functionName", "InputPayload": { "scriptInput": "{{parameterValue}}" }, "Attachment": "scriptAttachment.zip" } } Runtime The runtime language to be used for running the provided script. aws:executeScript supports Python 3.7 (python3.7), Python 3.8 (python3.8), Python 3.9 (python3.9)Python 3.10 (python3.10), Python 3.11 (python3.11) PowerShell Core 6.0 (dotnetcore2.1), and PowerShell 7.0 (dotnetcore3.1) scripts. Supported values: python3.7 | python3.8 | python3.9 | python3.10 | python3.11 | PowerShell Core 6.0 | PowerShell 7.0 Type: String Required: Yes Note For python runtimes, the environment provides 512MB of memory and 512MB of disk space. For PowerShell runtimes, the environment provides 1024MB of memory and 512MB of disk space. Handler The name of your function. You must ensure the function defined in the handler has two parameters, events and context. The PowerShell runtime does not support this parameter. Type: String Required: Yes (Python) | Not supported (PowerShell) Automation 1232 AWS Systems Manager InputPayload User Guide A JSON or YAML object that will be passed to the first parameter of the handler. This can be used to pass input data to the script. Type: String Required: No Python description: Tag an instance 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
|
systems-manager-ug-377
|
systems-manager-ug.pdf
| 377 |
and context. The PowerShell runtime does not support this parameter. Type: String Required: Yes (Python) | Not supported (PowerShell) Automation 1232 AWS Systems Manager InputPayload User Guide A JSON or YAML object that will be passed to the first parameter of the handler. This can be used to pass input data to the script. Type: String Required: No Python description: Tag an instance 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.' InstanceId: type: String description: (Required) The ID of the EC2 instance you want to tag. mainSteps: - name: tagInstance action: 'aws:executeScript' inputs: Runtime: "python3.11" Handler: tagInstance InputPayload: instanceId: '{{InstanceId}}' Script: |- def tagInstance(events,context): import boto3 #Initialize client ec2 = boto3.client('ec2') instanceId = events['instanceId'] tag = { "Key": "Env", "Value": "ExamplePython" } print(f"Adding tag {tag} to instance id {instanceId}") Automation 1233 AWS Systems Manager User Guide ec2.create_tags( Resources=[instanceId], Tags=[tag] ) return tag outputs: - Type: String Name: TagKey Selector: $.Payload.Key outputs: - tagInstance.TagKey PowerShell description: Tag an instance 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. InstanceId: type: String description: (Required) The ID of the EC2 instance you want to tag. mainSteps: - name: tagInstance action: aws:executeScript isEnd: true inputs: Runtime: PowerShell 7.0 InputPayload: instanceId: '{{InstanceId}}' Script: |- Install-Module AWS.Tools.EC2 -Force Import-Module AWS.Tools.EC2 $input = $env:InputPayload | ConvertFrom-Json $tag = New-Object Amazon.EC2.Model.Tag $tag.Key = "Env" Automation 1234 AWS Systems Manager User Guide $tag.Value = "ExamplePowerShell" Write-Information "Adding tag key: $($tag.Key) and value: $($tag.Value) to instance id $($input.instanceId)" New-EC2Tag -Resource $input.instanceId -Tag $tag return $tag outputs: - Type: String Name: TagKey Selector: $.Payload.Key outputs: - tagInstance.TagKey Script An embedded script that you want to run during the automation. Type: String Required: No (Python) | Yes (PowerShell) Attachment The name of a standalone script file or .zip file that can be invoked by the action. Specify the same value as the Name of the document attachment file you specify in the Attachments request parameter. For more information, see Attachments in the AWS Systems Manager API Reference. If you're providing a script using an attachment, you must also define a files section in the top-level elements of your runbook. For more information, see Schema version 0.3. To invoke a file for Python, use the filename.method_name format in Handler. Note The attachment for a Python script can be a .py file or a .zip file that contains the script. PowerShell scripts must be stored in .zip files. When including Python libraries in your attachment, we recommend adding an empty __init__.py file in each module directory. This allows you to import the modules from the Automation 1235 AWS Systems Manager User Guide library in your attachment within your script content. For example: from library import module Type: String Required: No Output Payload The JSON representation of the object returned by your function. Up to 100KB is returned. If you output a list, a maximum of 100 items is returned. aws:executeStateMachine – Run an AWS Step Functions state machine Runs an AWS Step Functions state machine. Input This action supports most parameters for the Step Functions StartExecution API operation. Required AWS Identity and Access Management (IAM) permissions • states:DescribeExecution • states:StartExecution • states:StopExecution YAML name: executeTheStateMachine action: aws:executeStateMachine inputs: stateMachineArn: StateMachine_ARN input: '{"parameters":"values"}' name: name JSON { Automation 1236 AWS Systems Manager User Guide "name": "executeTheStateMachine", "action": "aws:executeStateMachine", "inputs": { "stateMachineArn": "StateMachine_ARN", "input": "{\"parameters\":\"values\"}", "name": "name" } } stateMachineArn The Amazon Resource Name (ARN) of the Step Functions state machine. Type: String Required: Yes name The name of the execution. Type: String Required: No input A string that contains the JSON input data for the execution. Type: String Required: No Outputs The following outputs are predefined for this action. executionArn The ARN of the execution. Type: String Automation 1237 AWS Systems Manager input User Guide The string that contains the JSON input data of the execution. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding.. Type: String name The name of the execution. Type: String output The JSON output data of the execution. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String startDate The date the execution is started. Type: String stateMachineArn The ARN of the executed stated machine. Type: String status The current status of the execution. Type: String stopDate If the execution has already ended, the date the execution stopped. Type: String aws:invokeWebhook – Invoke an
|
systems-manager-ug-378
|
systems-manager-ug.pdf
| 378 |
data of the execution. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding.. Type: String name The name of the execution. Type: String output The JSON output data of the execution. Length constraints apply to the payload size, and are expressed as bytes in UTF-8 encoding. Type: String startDate The date the execution is started. Type: String stateMachineArn The ARN of the executed stated machine. Type: String status The current status of the execution. Type: String stopDate If the execution has already ended, the date the execution stopped. Type: String aws:invokeWebhook – Invoke an Automation webhook integration Invokes the specified Automation webhook integration. For information about creating Automation integrations, see Creating webhook integrations for Automation. Automation 1238 AWS Systems Manager Note User Guide To use the aws:invokeWebhook action, your user or service role must allow the following actions: • ssm:GetParameter • kms:Decrypt Permission for the AWS Key Management Service (AWS KMS) Decrypt operation is only required if you use a customer managed key to encrypt the parameter for your integration. Input Provide the information for the Automation integration you want to invoke. YAML action: "aws:invokeWebhook" inputs: IntegrationName: "exampleIntegration" Body: "Request body" JSON { "action": "aws:invokeWebhook", "inputs": { "IntegrationName": "exampleIntegration", "Body": "Request body" } } IntegrationName The name of the Automation integration. For example, exampleIntegration. The integration you specify must already exist. Type: String Automation 1239 AWS Systems Manager Required: Yes Body User Guide The payload you want to send when your webhook integration is invoked. Type: String Required: No Output Response The text received from the webhook provider response. ResponseCode The HTTP status code received from the webhook provider response. aws:invokeLambdaFunction – Invoke an AWS Lambda function Invokes the specified AWS Lambda function. Note Each aws:invokeLambdaFunction action can run up to a maximum duration of 300 seconds (5 minutes). You can limit the timeout by specifying the timeoutSeconds parameter for an aws:invokeLambdaFunction step. Input This action supports most invoked parameters for the Lambda service. For more information, see Invoke. YAML name: invokeMyLambdaFunction action: aws:invokeLambdaFunction maxAttempts: 3 Automation 1240 User Guide AWS Systems Manager timeoutSeconds: 120 onFailure: Abort inputs: FunctionName: MyLambdaFunction JSON { "name": "invokeMyLambdaFunction", "action": "aws:invokeLambdaFunction", "maxAttempts": 3, "timeoutSeconds": 120, "onFailure": "Abort", "inputs": { "FunctionName": "MyLambdaFunction" } } FunctionName The name of the Lambda function. This function must exist. Type: String Required: Yes Qualifier The function version or alias name. Type: String Required: No InvocationType The invocation type. The default value is RequestResponse. Type: String Valid values: Event | RequestResponse | DryRun Required: No Automation 1241 AWS Systems Manager LogType User Guide If the default value is Tail, the invocation type must be RequestResponse. Lambda returns the last 4 KB of log data produced by your Lambda function, base64-encoded. Type: String Valid values: None | Tail Required: No ClientContext The client-specific information. Required: No InputPayload A YAML or JSON object that is passed to the first parameter of the handler. You can use this input to pass data to the function. This input provides more flexibility and support than the legacy Payload input. If you define both InputPayload and Payload for the action, InputPayload takes precedence and the Payload value is not used. Type: StringMap Required: No Payload A JSON string that's passed to the first parameter of the handler. This can be used to pass input data to the function. We recommend using InputPayload input for added functionality. Type: String Required: No Output StatusCode The HTTP status code. Automation 1242 AWS Systems Manager FunctionError User Guide If present, it indicates that an error occurred while executing the function. Error details are included in the response payload. LogResult The base64-encoded logs for the Lambda function invocation. Logs are present only if the invocation type is RequestResponse, and the logs were requested. Payload The JSON representation of the object returned by the Lambda function. Payload is present only if the invocation type is RequestResponse. The following is a portion from the AWS-PatchInstanceWithRollback runbook demonstrating how to reference outputs from the aws:invokeLambdaFunction action. YAML - name: IdentifyRootVolume action: aws:invokeLambdaFunction inputs: FunctionName: "IdentifyRootVolumeLambda-{{automation:EXECUTION_ID}}" Payload: '{"InstanceId": "{{InstanceId}}"}' - name: PrePatchSnapshot action: aws:executeAutomation inputs: DocumentName: "AWS-CreateSnapshot" RuntimeParameters: VolumeId: "{{IdentifyRootVolume.Payload}}" Description: "ApplyPatchBaseline restoration case contingency" JSON { "name": "IdentifyRootVolume", "action": "aws:invokeLambdaFunction", "inputs": { "FunctionName": "IdentifyRootVolumeLambda-{{automation:EXECUTION_ID}}", "Payload": "{\"InstanceId\": \"{{InstanceId}}\"}" } }, Automation 1243 User Guide AWS Systems Manager { "name": "PrePatchSnapshot", "action": "aws:executeAutomation", "inputs": { "DocumentName": "AWS-CreateSnapshot", "RuntimeParameters": { "VolumeId": "{{IdentifyRootVolume.Payload}}", "Description": "ApplyPatchBaseline restoration case contingency" } } } aws:loop – Iterate over steps in an automation This action iterates over a subset of steps in an automation runbook. You can choose a do while or for each style loop. To construct a do while loop, use the LoopCondition input parameter. To construct a for each loop, use the Iterators and IteratorDataType input parameters. When using an aws:loop action, only specify
|
systems-manager-ug-379
|
systems-manager-ug.pdf
| 379 |
"aws:invokeLambdaFunction", "inputs": { "FunctionName": "IdentifyRootVolumeLambda-{{automation:EXECUTION_ID}}", "Payload": "{\"InstanceId\": \"{{InstanceId}}\"}" } }, Automation 1243 User Guide AWS Systems Manager { "name": "PrePatchSnapshot", "action": "aws:executeAutomation", "inputs": { "DocumentName": "AWS-CreateSnapshot", "RuntimeParameters": { "VolumeId": "{{IdentifyRootVolume.Payload}}", "Description": "ApplyPatchBaseline restoration case contingency" } } } aws:loop – Iterate over steps in an automation This action iterates over a subset of steps in an automation runbook. You can choose a do while or for each style loop. To construct a do while loop, use the LoopCondition input parameter. To construct a for each loop, use the Iterators and IteratorDataType input parameters. When using an aws:loop action, only specify either the Iterators or LoopCondition input parameter. The maximum number of iterations is 100. The onCancel property can only be used for steps defined within a loop. The onCancel property isn't supported for the aws:loop action. The onFailure property can be used for an aws:loop action, however it will only be used if an unexpected error occurs causing the step to fail. If you define onFailure properties for the steps within a loop, the aws:loop action inherits those properties and reacts accordingly when a failure occurs. Examples The following are examples of how to construct the different types of loop actions. do while name: RepeatMyLambdaFunctionUntilOutputIsReturned action: aws:loop inputs: Steps: - name: invokeMyLambda action: aws:invokeLambdaFunction inputs: FunctionName: LambdaFunctionName outputs: Automation 1244 AWS Systems Manager User Guide - Name: ShouldRetry Selector: $.Retry Type: Boolean LoopCondition: Variable: "{{ invokeMyLambda.ShouldRetry }}" BooleanEquals: true MaxIterations: 3 for each name: stopAllInstancesWithWaitTime action: aws:loop inputs: Iterators: "{{ DescribeInstancesStep.InstanceIds }}" IteratorDataType: "String" Steps: - name: stopOneInstance action: aws:changeInstanceState inputs: InstanceIds: - "{{stopAllInstancesWithWaitTime.CurrentIteratorValue}}" CheckStateOnly: false DesiredState: stopped - name: wait10Seconds action: aws:sleep inputs: Duration: PT10S Input The input is as follows. Iterators The list of items for the steps to iterate over. The maximum number of iterators is 100. Type: StringList Required: No Automation 1245 AWS Systems Manager IteratorDataType User Guide An optional parameter to specify the data type of the Iterators. A value for this parameter can be provided along with the Iterators input parameter. If you don’t specify a value for this parameter and Iterators, then you must specify a value for the LoopCondition parameter. Type: String Valid values: Boolean | Integer | String | StringMap Default: String Required: No LoopCondition Consists of a Variable and an operator condition to evaluate. If you don’t specify a value for this parameter, then you must specify values for the Iterators and IteratorDataType parameters. You can use complex operator evaluations by using a combination of And, Not, and Or operators. The condition is evaluated after the steps in the loop complete. If the condition is true and the MaxIterations value has not been reached, the steps in the loop run again. The operator conditions are as follows: String operations • StringEquals • EqualsIgnoreCase • StartsWith • EndsWith • Contains Numeric operations • NumericEquals • NumericGreater • NumericLesser • NumericGreaterOrEquals • NumericLesser • NumericLesserOrEquals Automation 1246 AWS Systems Manager Boolean operation • BooleanEquals Type: StringMap Required: No MaxIterations User Guide The maximum number of times the steps in the loop run. Once the value specified for this input is reached, the loop stops running even if the LoopCondition is still true or if there are objects remaining in the Iterators parameter. Type: Integer Valid values: 1 - 100 Required: No Steps The list of steps to run in the loop. These function like a nested runbook. Within these steps you can access the current iterator value for a for each loop using the syntax {{loopStepName.CurrentIteratorValue}}. You can also access an integer value of the current iteration for both loop types using the syntax {{loopStepName.CurrentIteration}}. Type: List of steps Required: Yes Output CurrentIteration The current loop iteration as an integer. Iteration values start at 1. Type: Integer CurrentIteratorValue The value of the current iterator as a string. This output is only present in for each loops. Automation 1247 AWS Systems Manager Type: String aws:pause – Pause an automation User Guide This action pauses the automation. Once paused, the automation status is Waiting. To continue the automation, use the SendAutomationSignal API operation with the Resume signal type. We recommend using the aws:sleep or aws:approve action for more granular control of your workflows. Note The default timeout for this action is 7 days (604800 seconds) and the maximum value is 30 days (2592000 seconds). You can limit or extend the timeout by specifying the timeoutSeconds parameter for an aws:pause step. Input The input is as follows. YAML name: pauseThis action: aws:pause timeoutSeconds: 1209600 inputs: {} JSON { "name": "pauseThis", "action": "aws:pause", "timeoutSeconds": "1209600", "inputs": {} } Output None Automation 1248 AWS Systems Manager User Guide aws:runCommand – Run a command on a managed instance Runs the specified commands. Note Automation only supports output of one AWS Systems Manager Run Command action. A runbook can
|
systems-manager-ug-380
|
systems-manager-ug.pdf
| 380 |
The default timeout for this action is 7 days (604800 seconds) and the maximum value is 30 days (2592000 seconds). You can limit or extend the timeout by specifying the timeoutSeconds parameter for an aws:pause step. Input The input is as follows. YAML name: pauseThis action: aws:pause timeoutSeconds: 1209600 inputs: {} JSON { "name": "pauseThis", "action": "aws:pause", "timeoutSeconds": "1209600", "inputs": {} } Output None Automation 1248 AWS Systems Manager User Guide aws:runCommand – Run a command on a managed instance Runs the specified commands. Note Automation only supports output of one AWS Systems Manager Run Command action. A runbook can include multiple Run Command actions, but output is supported for only one action at a time. Input This action supports most send command parameters. For more information, see SendCommand. YAML - name: checkMembership action: 'aws:runCommand' inputs: DocumentName: AWS-RunPowerShellScript InstanceIds: - '{{InstanceIds}}' Parameters: commands: - (Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain JSON { "name": "checkMembership", "action": "aws:runCommand", "inputs": { "DocumentName": "AWS-RunPowerShellScript", "InstanceIds": [ "{{InstanceIds}}" ], "Parameters": { "commands": [ "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain" ] Automation 1249 AWS Systems Manager } } } DocumentName User Guide If the Command type document is owned by you or AWS, specify the name of the document. If you're using a document shared with you by a different AWS account, specify the Amazon Resource Name (ARN) of the document. For more information about using shared documents, see Using shared SSM documents. Type: String Required: Yes InstanceIds The instance IDs where you want the command to run. You can specify a maximum of 50 IDs. You can also use the pseudo parameter {{RESOURCE_ID}} in place of instance IDs to run the command on all instances in the target group. For more information about pseudo parameters, see Using pseudo parameters when registering maintenance window tasks. Another alternative is to send commands to a fleet of instances by using the Targets parameter. The Targets parameter accepts Amazon Elastic Compute Cloud (Amazon EC2) tags. For more information about how to use the Targets parameter, see Run commands at scale. Type: StringList Required: No (If you don't specify InstanceIds or use the {{RESOURCE_ID}} pseudo parameter, then you must specify the Targets parameter.) Targets An array of search criteria that targets instances by using a Key,Value combination that you specify. Targets is required if you don't provide one or more instance IDs in the call. For more information about how to use the Targets parameter, see Run commands at scale. Type: MapList (The schema of the map in the list must match the object.) For information, see Target in the AWS Systems Manager API Reference. Automation 1250 AWS Systems Manager User Guide Required: No (If you don't specify Targets, then you must specify InstanceIds or use the {{RESOURCE_ID}} pseudo parameter.) Following is an example. YAML - name: checkMembership action: aws:runCommand inputs: DocumentName: AWS-RunPowerShellScript Targets: - Key: tag:Stage Values: - Gamma - Beta - Key: tag-key Values: - Suite Parameters: commands: - (Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain JSON { "name": "checkMembership", "action": "aws:runCommand", "inputs": { "DocumentName": "AWS-RunPowerShellScript", "Targets": [ { "Key": "tag:Stage", "Values": [ "Gamma", "Beta" ] }, { "Key": "tag:Application", "Values": [ "Suite" ] } Automation 1251 AWS Systems Manager User Guide ], "Parameters": { "commands": [ "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain" ] } } } Parameters The required and optional parameters specified in the document. Type: Map Required: No CloudWatchOutputConfig Configuration options for sending command output to Amazon CloudWatch Logs. For more information about sending command output to CloudWatch Logs, see Configuring Amazon CloudWatch Logs for Run Command. Type: StringMap (The schema of the map must match the object. For more information, see CloudWatchOutputConfig in the AWS Systems Manager API Reference). Required: No Following is an example. YAML - name: checkMembership action: aws:runCommand inputs: DocumentName: AWS-RunPowerShellScript InstanceIds: - "{{InstanceIds}}" Parameters: commands: - "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain" CloudWatchOutputConfig: CloudWatchLogGroupName: CloudWatchGroupForSSMAutomationService Automation 1252 AWS Systems Manager User Guide CloudWatchOutputEnabled: true JSON { "name": "checkMembership", "action": "aws:runCommand", "inputs": { "DocumentName": "AWS-RunPowerShellScript", "InstanceIds": [ "{{InstanceIds}}" ], "Parameters": { "commands": [ "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain" ] }, "CloudWatchOutputConfig" : { "CloudWatchLogGroupName": "CloudWatchGroupForSSMAutomationService", "CloudWatchOutputEnabled": true } } } Comment User-defined information about the command. Type: String Required: No DocumentHash The hash for the document. Type: String Required: No DocumentHashType The type of the hash. Automation 1253 User Guide AWS Systems Manager Type: String Valid values: Sha256 | Sha1 Required: No NotificationConfig The configurations for sending notifications. Required: No OutputS3BucketName The name of the S3 bucket for command output responses. Your managed node must have permissions for the S3 bucket to successfully log output. Type: String Required: No OutputS3KeyPrefix The prefix. Type: String Required: No ServiceRoleArn The ARN of the AWS Identity and Access Management (IAM) role. Type: String Required: No TimeoutSeconds The amount of time in seconds to wait for a command to deliver to the AWS Systems Manager SSM Agent on an instance. If the command
|
systems-manager-ug-381
|
systems-manager-ug.pdf
| 381 |
Guide AWS Systems Manager Type: String Valid values: Sha256 | Sha1 Required: No NotificationConfig The configurations for sending notifications. Required: No OutputS3BucketName The name of the S3 bucket for command output responses. Your managed node must have permissions for the S3 bucket to successfully log output. Type: String Required: No OutputS3KeyPrefix The prefix. Type: String Required: No ServiceRoleArn The ARN of the AWS Identity and Access Management (IAM) role. Type: String Required: No TimeoutSeconds The amount of time in seconds to wait for a command to deliver to the AWS Systems Manager SSM Agent on an instance. If the command isn't received by the SSM Agent on the instance before the value specified is reached, then the status of the command changes to Delivery Timed Out. Type: Integer Automation 1254 User Guide AWS Systems Manager Required: No Valid values: 30-2592000 Output CommandId The ID of the command. Status The status of the command. ResponseCode The response code of the command. If the document you run has more than 1 step, a value isn't returned for this output. Output The output of the command. If you target a tag or multiple instances with your command, no output value is returned. You can use the GetCommandInvocation and ListCommandInvocations API operations to retrieve output for individual instances. aws:runInstances – Launch an Amazon EC2 instance Launches a new Amazon Elastic Compute Cloud (Amazon EC2) instance. Input The action supports most API parameters. For more information, see the RunInstances API documentation. YAML name: launchInstance action: aws:runInstances maxAttempts: 3 timeoutSeconds: 1200 onFailure: Abort inputs: ImageId: ami-12345678 Automation 1255 AWS Systems Manager User Guide InstanceType: t2.micro MinInstanceCount: 1 MaxInstanceCount: 1 IamInstanceProfileName: myRunCmdRole TagSpecifications: - ResourceType: instance Tags: - Key: LaunchedBy Value: SSMAutomation - Key: Category Value: HighAvailabilityFleetHost JSON { "name":"launchInstance", "action":"aws:runInstances", "maxAttempts":3, "timeoutSeconds":1200, "onFailure":"Abort", "inputs":{ "ImageId":"ami-12345678", "InstanceType":"t2.micro", "MinInstanceCount":1, "MaxInstanceCount":1, "IamInstanceProfileName":"myRunCmdRole", "TagSpecifications":[ { "ResourceType":"instance", "Tags":[ { "Key":"LaunchedBy", "Value":"SSMAutomation" }, { "Key":"Category", "Value":"HighAvailabilityFleetHost" } ] } ] } } Automation 1256 User Guide AWS Systems Manager AdditionalInfo Reserved. Type: String Required: No BlockDeviceMappings The block devices for the instance. Type: MapList Required: No ClientToken The identifier to ensure idempotency of the request. Type: String Required: No DisableApiTermination Turns on or turns off instance API termination. Type: Boolean Required: No EbsOptimized Turns on or turns off Amazon Elastic Block Store (Amazon EBS) optimization. Type: Boolean Required: No IamInstanceProfileArn The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) instance profile for the instance. Automation 1257 User Guide AWS Systems Manager Type: String Required: No IamInstanceProfileName The name of the IAM instance profile for the instance. Type: String Required: No ImageId The ID of the Amazon Machine Image (AMI). Type: String Required: Yes InstanceInitiatedShutdownBehavior Indicates whether the instance stops or terminates on system shutdown. Type: String Required: No InstanceType The instance type. Note If an instance type value isn't provided, the m1.small instance type is used. Type: String Required: No KernelId The ID of the kernel. Automation 1258 AWS Systems Manager Type: String Required: No KeyName The name of the key pair. Type: String Required: No MaxInstanceCount The maximum number of instances to be launched. Type: String Required: No MetadataOptions The metadata options for the instance. For more information, see InstanceMetadataOptionsRequest. Type: StringMap Required: No MinInstanceCount The minimum number of instances to be launched. Type: String Required: No Monitoring Turns on or turns off detailed monitoring. Type: Boolean Required: No Automation User Guide 1259 AWS Systems Manager NetworkInterfaces The network interfaces. Type: MapList Required: No Placement The placement for the instance. Type: StringMap Required: No PrivateIpAddress The primary IPv4 address. Type: String Required: No RamdiskId The ID of the RAM disk. Type: String Required: No SecurityGroupIds The IDs of the security groups for the instance. Type: StringList Required: No SecurityGroups The names of the security groups for the instance. Type: StringList Required: No Automation User Guide 1260 AWS Systems Manager SubnetId The subnet ID. Type: String Required: No TagSpecifications User Guide The tags to apply to the resources during launch. You can only tag instances and volumes at launch. The specified tags are applied to all instances or volumes that are created during launch. To tag an instance after it has been launched, use the aws:createTags – Create tags for AWS resources action. Type: MapList (For more information, see TagSpecification.) Required: No UserData A script provided as a string literal value. If a literal value is entered, then it must be Base64- encoded. Type: String Required: No Output InstanceIds The IDs of the instances. InstanceStates The current state of the instance. aws:sleep – Delay an automation Delays an automation for a specified amount of time. This action uses the International Organization for Standardization (ISO) 8601 date and time format. For more information about this date and time format, see ISO 8601. Automation 1261 AWS Systems Manager Input You
|
systems-manager-ug-382
|
systems-manager-ug.pdf
| 382 |
tags for AWS resources action. Type: MapList (For more information, see TagSpecification.) Required: No UserData A script provided as a string literal value. If a literal value is entered, then it must be Base64- encoded. Type: String Required: No Output InstanceIds The IDs of the instances. InstanceStates The current state of the instance. aws:sleep – Delay an automation Delays an automation for a specified amount of time. This action uses the International Organization for Standardization (ISO) 8601 date and time format. For more information about this date and time format, see ISO 8601. Automation 1261 AWS Systems Manager Input You can delay an automation for a specified duration. User Guide YAML name: sleep action: aws:sleep inputs: Duration: PT10M JSON { "name":"sleep", "action":"aws:sleep", "inputs":{ "Duration":"PT10M" } } You can also delay an automation until a specified date and time. If the specified date and time has passed, the action proceeds immediately. YAML name: sleep action: aws:sleep inputs: Timestamp: '2020-01-01T01:00:00Z' JSON { "name": "sleep", "action": "aws:sleep", "inputs": { "Timestamp": "2020-01-01T01:00:00Z" } } Automation 1262 AWS Systems Manager Note Automation supports a maximum delay of 604799 seconds (7 days). User Guide Duration An ISO 8601 duration. You can't specify a negative duration. Type: String Required: No Timestamp An ISO 8601 timestamp. If you don't specify a value for this parameter, then you must specify a value for the Duration parameter. Type: String Required: No Output None aws:updateVariable – Updates a value for a runbook variable This action updates a value for a runbook variable. The data type of the value must match the data type of the variable you want to update. Data type conversions aren't supported. The onCancel property isn't supported for the aws:updateVariable action. Input The input is as follows. YAML name: updateStringList Automation 1263 AWS Systems Manager User Guide action: aws:updateVariable inputs: Name: variable:variable name Value: - "1" - "2" JSON { "name": "updateStringList", "action": "aws:updateVariable", "inputs": { "Name": "variable:variable name", "Value": ["1","2"] } } Name The name of the variable whose value you want to update. You must use the format variable:variable name Type: String Required: Yes Value The new value to assign to the variable. The value must match the data type of the variable. Data type conversions aren't supported. Type: Boolean | Integer | MapList | String | StringList | StringMap Required: Yes Constraints: • MapList can contain a maximum number of 200 items. • Key lengths can be a minimum length of 1 and a maximum length of 50. • StringList can be a minimum number of 0 items and a maximum number of 50 items. Automation 1264 AWS Systems Manager User Guide • String lengths can be a minimum length of 1 and a maximum length of 512. Output None aws:waitForAwsResourceProperty – Wait on an AWS resource property The aws:waitForAwsResourceProperty action allows your automation to wait for a specific resource state or event state before continuing the automation. For more examples of how to use this action, see Additional runbook examples. Note The default timeout value for this action is 3600 seconds (one hour). You can limit or extend the timeout by specifying the timeoutSeconds parameter for an aws:waitForAwsResourceProperty step. For more information and examples of how to use this action, see Handling timeouts in runbooks. Input Inputs are defined by the API operation that you choose. YAML action: aws:waitForAwsResourceProperty inputs: Service: The official namespace of the service Api: The API operation or method name API operation inputs or parameters: A value PropertySelector: Response object DesiredValues: - Desired property value JSON { Automation 1265 AWS Systems Manager User Guide "action": "aws:waitForAwsResourceProperty", "inputs": { "Service":"The official namespace of the service", "Api":"The API operation or method name", "API operation inputs or parameters":"A value", "PropertySelector": "Response object", "DesiredValues": [ "Desired property value" ] } } Service The AWS service namespace that contains the API operation that you want to run. For example, the namespace for AWS Systems Manager is ssm. The namespace for Amazon Elastic Compute Cloud (Amazon EC2) is ec2. You can view a list of supported AWS service namespaces in the Available Services section of the AWS CLI Command Reference. Type: String Required: Yes Api The name of the API operation that you want to run. 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. Type: String Required: Yes API operation inputs One or more API operation inputs. You can view the available inputs (also called parameters) by choosing a service in the left navigation on the following Services Reference page. Choose a method in
|
systems-manager-ug-383
|
systems-manager-ug.pdf
| 383 |
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. Type: String Required: Yes API operation inputs One or more API operation inputs. You can view the available inputs (also called parameters) 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 methods for Amazon RDS are listed on the following page: Amazon RDS methods. Choose Automation 1266 AWS Systems Manager User Guide the describe_db_instances method and scroll down to see the available parameters, such as DBInstanceIdentifier, Name, and Values. YAML inputs: Service: The official namespace of the service Api: The API operation name API input 1: A value API Input 2: A value API Input 3: A value JSON "inputs":{ "Service":"The official namespace of the service", "Api":"The API operation name", "API input 1":"A value", "API Input 2":"A value", "API Input 3":"A value" } Type: Determined by chosen API operation Required: Yes PropertySelector The JSONPath to a specific attribute in the response object. You can view the response objects 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 methods for Amazon RDS are listed on the following page: Amazon RDS methods. Choose the describe_db_instances method and scroll down to the Response Structure section. DBInstances is listed as a response object. Type: String Required: Yes DesiredValues The expected status or state on which to continue the automation. Type: MapList, StringList Automation 1267 AWS Systems Manager Required: Yes Automation system variables User Guide AWS Systems Manager Automation runbooks use the following variables. For an example of how these variables are used, view the JSON source of the AWS-UpdateWindowsAmi runbook. To view the JSON source of the AWS-UpdateWindowsAmi runbook 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- 2. 3. manager/. In the navigation pane, choose Documents. In the document list, use either the Search bar or the numbers to the right of the Search bar to choose the runbook AWS-UpdateWindowsAmi. 4. Choose the Content tab. System variables Automation runbooks support the following system variables. Variable Details global:ACCOUNT_ID global:DATE global:DATE_TIME The AWS account ID of the user or role in which Automation runs. The date (at run time) in the format yyyy-MM- dd. The date and time (at run time) in the format yyyy-MM-dd_HH.mm.ss. global:AWS_PARTITION The partition that the resource is in. For standard AWS Regions, the partition is aws. For resources in other partitions, the partition is aws-partitionname . For example, the partition for resources in the AWS GovCloud (US-West) Region is aws-us-gov . Automation 1268 AWS Systems Manager Variable global:REGION Automation variables User Guide Details The Region that the runbook is run in. For example, us-east-2. Automation runbooks support the following automation variables. Variable Details automation:EXECUTION_ID The unique identifier assigned to the current automation. For example, 1a2b3c-1a 2b3c-1a2b3c-1a2b3c1a2b3c1a2b3c . Topics • Terminology • Supported scenarios • Unsupported scenarios Terminology The following terms describe how variables and parameters are resolved. Term Definition Example Constant ARN Runbook parameter A valid Amazon Resource Name (ARN) without variables . arn:aws:iam::12345 6789012:role/roleN ame A parameter defined at the runbook level (for example, instanceId ). The parameter is used in a basic string replace. Its value { "description": "Create Image Demo", "version": "0.3", Automation 1269 AWS Systems Manager User Guide Term Definition Example is supplied at Start Execution "assumeRole": time. "Your_Automation_As sume_Role_ARN ", "parameters":{ "instanceId": { "type": "String", "description": "Instance to create image from" } } Automation 1270 AWS Systems Manager User Guide Term Definition Example System variable A general variable substitut ed into the runbook when "activities": [ { any part of the runbook is "id": "copyImag evaluated. e", "activityType": "AWS-CopyImage", "maxAttempts": 1, "onFailure": "Continue", "inputs": { "ImageName": "{{imageName}}", "SourceIm ageId": "{{source ImageId}}", "SourceRe gion": "{{source Region}}", "Encrypted": true, "ImageDes cription": "Test CopyImage Description created on {{global: DATE}} " } } ] Automation 1271 AWS Systems Manager User Guide Term Definition Example Automation variable A variable relating to the automation substituted into { "name": "runFixed the runbook when any part of Cmds", the runbook is evaluated. "action": "aws:runC ommand", "maxAttempts": 1, "onFailure": "Continue", "inputs": { "DocumentName": "AWS-RunPowerShell Script", "InstanceIds": [ "{{Launch Instance.InstanceI ds}}" ], "Parameters": { "commands": [ "dir", "date", "“{{outpu tFormat}}” -f “left”,”r ight”,”{{global:DA TE}}”,” {{automat ion:EXECUTION_ID}} ] ” } } } Automation 1272 AWS Systems Manager User Guide Term Definition Example Systems Manager Parameter A variable defined within AWS
|
systems-manager-ug-384
|
systems-manager-ug.pdf
| 384 |
"Test CopyImage Description created on {{global: DATE}} " } } ] Automation 1271 AWS Systems Manager User Guide Term Definition Example Automation variable A variable relating to the automation substituted into { "name": "runFixed the runbook when any part of Cmds", the runbook is evaluated. "action": "aws:runC ommand", "maxAttempts": 1, "onFailure": "Continue", "inputs": { "DocumentName": "AWS-RunPowerShell Script", "InstanceIds": [ "{{Launch Instance.InstanceI ds}}" ], "Parameters": { "commands": [ "dir", "date", "“{{outpu tFormat}}” -f “left”,”r ight”,”{{global:DA TE}}”,” {{automat ion:EXECUTION_ID}} ] ” } } } Automation 1272 AWS Systems Manager User Guide Term Definition Example Systems Manager Parameter A variable defined within AWS Systems Manager description: Launch new Parameter Store. It can't be Windows test instance directly referenced in step input. Permissions might be required to access the parameter. schemaVersion: '0.3' assumeRole: '{{Automa tionAssumeRole}}' parameters: AutomationAssumeRo le: type: String default: '' 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. LatestAmi: type: String default: >- {{ssm:/aws/ service/ami-wind ows-latest/Windows _Server-2016-English- Full-Base}} description: The latest Windows Server 2016 AMI queried from the public parameter. mainSteps: - name: launchIns tance action: 'aws:runI nstances' maxAttempts: 3 Automation 1273 AWS Systems Manager User Guide Term Definition Example timeoutSeconds: 1200 onFailure: Abort inputs: ImageId: '{{Latest Ami}}' ... Supported scenarios Scenario Comments Example Constant ARN assumeRole at creation. An authorization check is performed to verify that the calling user is permitted to pass the given assumeRole . Runbook parameter supplied for AssumeRole when the automation is started. Must be defined in the parameter list of the runbook. { "description": "Test all Automation resolvable parameter s", "schemaVersion": "0.3", "assumeRo le": "arn:aws: iam::123456789012: role/roleName" "parameters": { , ... { "description": "Test all Automation resolvable parameter s", "schemaVersion": "0.3", "assumeRo le": "{{dynamicARN}}" , "parameters": { ... Automation 1274 AWS Systems Manager User Guide Scenario Comments Example Value supplied for runbook parameter at start. Customer supplies the value to use for a parameter. Any inputs supplied at start time need to be defined in the parameter list of the runbook. ... "parameters": { "amiId": { "type": "String", "default": "ami-12345678 ", "description": "list of commands to run as part of first step" }, ... Inputs to Start Automatio n Execution include : {"amiId" : ["ami-12345 678 "] } Automation 1275 AWS Systems Manager User Guide Scenario Comments Example Systems Manager Parameter referenced within runbook The variable exists within the customer's account, or is a ... content. publicly accessibly parameter parameters: , and the AssumeRole for the runbook has access to the variable. A check is performed at create time to confirm the AssumeRole has access. The parameter can't be directly referenced in step input. LatestAmi: type: String default: >- {{ssm:/aws/ service/ami-wind ows-latest/Windows _Server-2016-English- Full-Base}} description: The latest Windows Server 2016 AMI queried from the public parameter. mainSteps: - name: launchIns tance action: 'aws:runI nstances' maxAttempts: 3 timeoutSeconds: 1200 onFailure: Abort inputs: ImageId: '{{Latest Ami}}' ... Automation 1276 AWS Systems Manager User Guide Scenario Comments Example System variable referenced within step definition A system variable is substitut ed into the runbook when ... "mainSteps": [ the automation is started. { The value injected into the runbook is relative to when the substitution occurs. That is, the value of a time variable "name": "RunSomeC ommands", "action": "aws:runCommand", "maxAttempts": 1, injected at step 1 is different "onFailure": from the value injected at step 3 because of the time it takes to run the steps between. System variables don't need to be set in the parameter list of the runbook. "Continue", "inputs": { "DocumentName": "AWS:RunPowerShell", "InstanceIds": ["{{LaunchInstance .InstanceIds}}"], "Parameters": { "commands " : [ "echo {The time is now {{global:DATE_TIME }}}" ] } } }, ... Automation 1277 AWS Systems Manager User Guide Scenario Comments Example Automation variable referenced within step Automation variables don't need to be set in ... "mainSteps": [ definition. the parameter list of the { runbook. The only supported "name": "invokeLa Automation variable is automation:EXECUTION_ID. mbdaFunction", "action": "aws:invokeLambdaF unction", "maxAttempts": 1, "onFailure": "Continue", "inputs": { "FunctionName": "Hello-World-Lambd aFunction", "Payload" : "{ "executionId" : "{{automation:EXEC UTION_ID}}" }" } } ... Automation 1278 AWS Systems Manager User Guide Scenario Comments Example Refer to output from previous step within next step definitio This is parameter redirection. The output of a previous step ... "mainSteps": [ n. is referenced using the syntax { {{stepName.OutputN ame}} . This syntax can't be used by the customer for runbook parameters. This is "name": "LaunchIn stance", "action": "aws:runInstances", "maxAttempts": 1, resolved when the referring "onFailure": step runs. The parameter isn't "Continue", listed in the parameters of the runbook. "inputs": { "ImageId": "{{amiId}}", "MinInsta nceCount": 1, "MaxInsta nceCount": 2 } }, { "name":"c hangeState", "action": "aws:changeInstanc eState", "maxAttempts": 1, "onFailure": "Continue", "inputs": { "InstanceIds": ["{{LaunchInstance .InstanceIds}}"], "DesiredState": "terminated" }
|
systems-manager-ug-385
|
systems-manager-ug.pdf
| 385 |
to output from previous step within next step definitio This is parameter redirection. The output of a previous step ... "mainSteps": [ n. is referenced using the syntax { {{stepName.OutputN ame}} . This syntax can't be used by the customer for runbook parameters. This is "name": "LaunchIn stance", "action": "aws:runInstances", "maxAttempts": 1, resolved when the referring "onFailure": step runs. The parameter isn't "Continue", listed in the parameters of the runbook. "inputs": { "ImageId": "{{amiId}}", "MinInsta nceCount": 1, "MaxInsta nceCount": 2 } }, { "name":"c hangeState", "action": "aws:changeInstanc eState", "maxAttempts": 1, "onFailure": "Continue", "inputs": { "InstanceIds": ["{{LaunchInstance .InstanceIds}}"], "DesiredState": "terminated" } } ... Automation 1279 AWS Systems Manager Unsupported scenarios User Guide Scenario Comment Example Systems Manager Parameter Not supported. supplied for assumeRole at create ... { "description": "Test all Automation resolvable parameter s", "schemaVersion": "0.3", "assumeRole": "{{ssm:administrato rRoleARN}} ", "parameters": { ... Systems Manager Parameter directly referenced in step input. Returns InvalidDo cumentContent at create time. exception ... mainSteps: - name: launchIns tance action: 'aws:runI nstances' maxAttempts: 3 timeoutSeconds: 1200 onFailure: Abort inputs: ImageId: '{{ssm:/ aws/service/ami-win dows-latest/Window s_Server-2016-Engl ish-Full-Base}}' ... Automation 1280 AWS Systems Manager User Guide Scenario Comment Example Variable step definition The definition of a step in the runbook is constructed by ... variables. "mainSteps": [ { "name": "LaunchIn stance", "action": "aws:runInstances", "{{attempt Model}} ": 1, "onFailure": "Continue", "inputs": { "ImageId": "ami-12345678 ", "MinInsta nceCount": 1, "MaxInsta nceCount": 2 } ... User supplies input : { "attemptModel" : "minAttempts " } Automation 1281 AWS Systems Manager User Guide Scenario Comment Example Cross referencing runbook parameters The user supplies an input parameter at start time, which is a reference to another parameter in the runbook. ... "parameters": { "amiId": { "type": "String", "default": "ami-7f2e6015 ", "description": "list of commands to run as part of first step" }, "alternateAmiId": { "type": "String", "description": "The alternate AMI to try if this first fails". "default" : "{{amiId} }" }, ... Automation 1282 AWS Systems Manager User Guide Scenario Comment Example Multi-level expansion The runbook defines a variable that evaluates to the ... "parameters": { name of a variable. This sits "firstParameter ": { within the variable delimiters "type": "String", (that is {{ }}) and is expanded to the value of that variable/ parameter. "default": "param2", "description": "The parameter to reference" }, "secondParameter ": { "type": "String", "default" : "echo {Hello world}", "description": "What to run" } }, "mainSteps": [{ "name": "runFixed Cmds", "action": "aws:runCommand", "maxAttempts": 1, "onFailure": "Continue", "inputs": { "DocumentName": "AWS-RunPowerShell Script", "InstanceIds" : "{{LaunchInstance. InstanceIds}}", "Parameters": { "commands ": [ "{{ {{firstPa rameter}} }}"] } Automation 1283 AWS Systems Manager User Guide Scenario Comment Example ... Note: The customer intention here would be to run a command of "echo {Hello world}" Automation 1284 AWS Systems Manager User Guide Scenario Comment Example Referencing output from a runbook step that is a The user references the output from a preceding different variable type runbook step within a subsequent step. The output is a variable type that doesn't meet the requirements of the action in the subsequent step. ... mainSteps: - name: getImageId action: aws:execu teAwsApi inputs: Service: ec2 Api: DescribeImages Filters: - Name: "name" Values: - "{{ImageName}}" outputs: - Name: ImageIdList Selector: "$.Images " Type: "StringList" - name: copyMyImages action: aws:copyImage maxAttempts: 3 onFailure: Abort inputs: SourceImageId: {{getImageId.Image IdList}} SourceRegion: ap- northeast-2 ImageName: Encrypted Copies of LAMP base AMI in ap- northeast-2 Encrypted: true ... Note: You must provide the type required by the Automation action. In this case, aws:copyI mage requires a "String" type variable but the preceding step Automation 1285 AWS Systems Manager User Guide Scenario Comment Example outputs a "StringList" type variable. Creating your own runbooks An Automation runbook defines the actions that Systems Manager performs on your managed instances and other AWS resources when an automation runs. Automation is a tool in AWS Systems Manager. A runbook contains one or more steps that run in sequential order. Each step is built around a single action. Output from one step can be used as input in a later step. The process of running these actions and their steps is called the automation. Action types supported for runbooks let you automate a wide variety of operations in your AWS environment. For example, using the executeScript action type, you can embed a python or PowerShell script directly in your runbook. (When you create a custom runbook, you can add your script inline, or attach it from an S3 bucket or from your local machine.) You can automate management of your AWS CloudFormation resources by using the createStack and deleteStack action types. In addition, using the executeAwsApi action type, a step can run any API operation in any AWS service, including creating or deleting AWS resources, starting other processes, initiating notifications, and many more. For a list of all 20 supported action
|
systems-manager-ug-386
|
systems-manager-ug.pdf
| 386 |
For example, using the executeScript action type, you can embed a python or PowerShell script directly in your runbook. (When you create a custom runbook, you can add your script inline, or attach it from an S3 bucket or from your local machine.) You can automate management of your AWS CloudFormation resources by using the createStack and deleteStack action types. In addition, using the executeAwsApi action type, a step can run any API operation in any AWS service, including creating or deleting AWS resources, starting other processes, initiating notifications, and many more. For a list of all 20 supported action types for Automation, see Systems Manager Automation actions reference. AWS Systems Manager Automation provides several runbooks with pre-defined steps 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). You can also create your own runbooks and share them with other AWS accounts, or make them public for all Automation users. Runbooks are written using YAML or JSON. Using the Document Builder in the Systems Manager Automation console, however, you can create a runbook without having to author in native JSON or YAML. Automation 1286 AWS Systems Manager Important User Guide If you run an automation workflow that invokes other services by using an AWS Identity and Access Management (IAM) service role, be aware that the service role must be configured with permission to invoke those services. This requirement applies to all AWS Automation runbooks (AWS-* runbooks) such as the AWS-ConfigureS3BucketLogging, AWS-CreateDynamoDBBackup, and AWS-RestartEC2Instance runbooks, to name a few. This requirement also applies to any custom Automation 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, configure the service role with permission to invoke those services. You can give permissions to other AWS services by adding an IAM inline policy to the role. For more information, see (Optional) Add an Automation inline policy or customer managed policy to invoke other AWS services. For information about the actions that you can specify in a runbook, see Systems Manager Automation actions reference. For information about using the AWS Toolkit for Visual Studio Code to create runbooks, see Working with Systems Manager Automation documents in the AWS Toolkit for Visual Studio Code User Guide. For information about using the visual designer to create a custom runbook, see Visual design experience for Automation runbooks. Contents • Visual design experience for Automation runbooks • Before you begin • Overview of the visual design experience interface • Actions browser • Canvas • Form • Keyboard shortcuts • Using the visual design experience • Create a runbook workflow Automation 1287 AWS Systems Manager User Guide • Design a runbook • Update your runbook • Export your runbook • Configuring inputs and outputs for your actions • Provide input data for an action • Define output data for an action • Error handling with the visual design experience • Retry action on error • Timeouts • Failed actions • Canceled actions • Critical actions • Ending actions • Tutorial: Create a runbook using the visual design experience • 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 • Authoring Automation runbooks • Identify your use case • Set up your development environment • Develop runbook content • Example 1: Creating parent-child runbooks • Create the child runbook • Create the parent runbook • Example 2: Scripted runbook • Additional runbook examples • Deploy VPC architecture and Microsoft Active Directory domain controllers Automation 1288 • Restore a root volume from the latest snapshot AWS Systems Manager User Guide • Create an AMI and cross-Region copy • Creating input parameters that populate AWS resources • Using Document Builder to create runbooks • Create a runbook using Document Builder • Create a runbook that runs scripts • Using scripts in runbooks • Permissions for using runbooks • Adding scripts to runbooks • Script constraints for runbooks • Using conditional statements in runbooks • Working with the aws:branch action • Creating an aws:branch step in a runbook • About creating the output variable • Example aws:branch runbooks • Creating complex branching automations with operators • Examples of how to use conditional options • Using action outputs as inputs • Using JSONPath in runbooks • Creating webhook integrations for Automation • Creating integrations (console) • Creating integrations (command line) • Creating webhooks for integrations • Handling timeouts in runbooks Visual design experience for Automation runbooks AWS Systems Manager Automation provides a low-code visual design experience that helps you create automation runbooks. The visual design experience
|
systems-manager-ug-387
|
systems-manager-ug.pdf
| 387 |
Working with the aws:branch action • Creating an aws:branch step in a runbook • About creating the output variable • Example aws:branch runbooks • Creating complex branching automations with operators • Examples of how to use conditional options • Using action outputs as inputs • Using JSONPath in runbooks • Creating webhook integrations for Automation • Creating integrations (console) • Creating integrations (command line) • Creating webhooks for integrations • Handling timeouts in runbooks Visual design experience for Automation runbooks AWS Systems Manager Automation provides a low-code visual design experience that helps you create automation runbooks. The visual design experience provides a drag-and-drop interface with the option to add your own code so you can create and edit runbooks more easily. With the visual design experience, you can do the following: • Control conditional statements. Automation 1289 AWS Systems Manager User Guide • Control how input and output is filtered or transformed for each action. • Configure error handling. • Prototype new runbooks. • Use your prototype runbooks as the starting point for local development with the AWS Toolkit for Visual Studio Code. When you create or edit a runbook, you can access the visual design experience from the Automation console. As you create a runbook, the visual design experience validates your work and auto-generates code. You can review the generated code, or export it for local development. When you're finished, you can save your runbook, run it, and examine the results in the Systems Manager Automation console. Before you begin To use the visual design experience, you need an AWS account, and credentials that provide the correct permissions for any resources that you want to use. In the visual design experience, Automation integrates with Amazon CodeGuru Security to help you detect security policy violations and vulnerabilities in your Python scripts. To use this feature for aws:executeScript actions, your AWS Identity and Access Management (IAM) policy must include the following permissions: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "codeguru-security:CreateUploadUrl", "codeguru-security:CreateScan", "codeguru-security:GetScan", "codeguru-security:GetFindings" ] } ] } Topics • Overview of the visual design experience interface Automation 1290 AWS Systems Manager User Guide • Using the visual design experience • Configuring inputs and outputs for your actions • Error handling with the visual design experience • Tutorial: Create a runbook using the visual design experience Overview of the visual design experience interface The visual design experience for Systems Manager Automation is a low-code visual workflow designer that helps you create automation runbooks. Get to know the visual design experience with an overview of the interface components: • The Actions browser contains the Actions, AWS APIs, and Runbooks tabs. • The canvas is where you drag and drop actions into your workflow graph, change the order of actions, and select actions to configure or view. • The Form panel is where you can view and edit the properties of any action that you selected on the canvas. Select the Content toggle to view the YAML or JSON for your runbook, with the currently selected action highlighted. Info links open a panel with contextual information when you need help. These panels also include links to related topics in the Systems Manager Automation documentation. Automation 1291 AWS Systems Manager Actions browser User Guide From the Actions browser, you can select actions to drag and drop into your workflow graph. You can search all actions using the search field at the top of the Actions browser. The Actions browser contains the following tabs: • The Actions tab provides a list of automation actions that you can drag and drop into your runbook's workflow graph in the canvas. • The AWS APIs tab provides a list of AWS APIs that you can drag and drop into your runbook's workflow graph in the canvas. • The Runbooks tab provides several ready-to-use, reusable runbooks as building blocks that you can use for a variety of use cases. For example, you can use runbooks to perform common remediation tasks on Amazon EC2 instances in your workflow without having to re-create the same actions. Canvas After you choose an action to add to your automation, drag it to the canvas and drop it into your workflow graph. 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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.