id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
systems-manager-ug-688
systems-manager-ug.pdf
688
Red Hat Enterprise Linux (RHEL) 7.x, 8.x, and 9.x sudo status amazon-ss sudo start amazon-ss m-agent m-agent sudo systemctl status sudo systemctl enable amazon-ssm-agent amazon-ssm-agent sudo systemctl start amazon-ssm-agent Checking SSM Agent status and starting the agent 2374 AWS Systems Manager Operating system Command to check SSM Agent status Command to start SSM Agent User Guide SUSE Linux Enterprise Server (SLES) sudo systemctl status sudo systemctl enable amazon-ssm-agent amazon-ssm-agent sudo systemctl start amazon-ssm-agent Ubuntu Server 14.04 (all) and 16.04 (32-bit) sudo status amazon-ss sudo start amazon-ss m-agent m-agent Ubuntu Server 16.04 64- bit instances (deb package installation) sudo systemctl status sudo systemctl enable amazon-ssm-agent amazon-ssm-agent sudo systemctl start amazon-ssm-agent Ubuntu Server 16.04, 18.04, and 20.04 LTS, 20.10 STR 64- sudo systemctl status sudo snap start snap.amazon-ssm-ag amazon-ssm-agent bit, 22.04 LTS (Snap package ent.amazon-ssm-age installation), and 23.04 nt.service Windows Server Run in PowerShell: Get-Service AmazonSSM Agent Run in PowerShell Administr ator mode: Start-Service AmazonSSMAgent More info • Working with SSM Agent on EC2 instances for Linux • Working with SSM Agent on EC2 instances for Windows Server • Checking the SSM Agent version number Checking SSM Agent status and starting the agent 2375 AWS Systems Manager User Guide Checking the SSM Agent version number Certain AWS Systems Manager functionalities have prerequisites that include a minimum Systems Manager Agent (SSM Agent) version be installed on your managed nodes. You can get the currently installed SSM Agent version on your managed nodes using the Systems Manager console, or by logging in to your managed nodes. Note To view details about earlier versions, see the SSM Agent release notes on GitHub. The following procedures describe how to get the currently installed SSM Agent version on your managed nodes. To check the version number of SSM Agent installed on a managed node 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. In the navigation pane, choose Fleet Manager. In the SSM Agent version column, note the Agent version number. 2. 3. To get the currently installed SSM Agent version from within the operating system Choose from the following tabs to get the currently installed SSM Agent version from within an operating system. Amazon Linux 1, Amazon Linux 2, and Amazon Linux 2023 Note This command varies depending on the package manager for your operating system. 1. Log in to your managed node. 2. Run the following command. yum info amazon-ssm-agent Checking the SSM Agent version number 2376 AWS Systems Manager User Guide This command returns output similar to the following. Loaded plugins: extras_suggestions, langpacks, priorities, update-motd Installed Packages Name : amazon-ssm-agent Arch : x86_64 Version : 3.0.655.0 CentOS 1. Log in to your managed node. 2. Run the following command for CentOS 6 and 7. yum info amazon-ssm-agent This command returns output similar to the following. Loaded plugins: extras_suggestions, langpacks, priorities, update-motd Installed Packages Name : amazon-ssm-agent Arch : x86_64 Version : 3.0.655.0 Debian Server 1. Log in to your managed node. 2. Run the following command. apt list amazon-ssm-agent This command returns output similar to the following. apt list amazon-ssm-agent Listing... Done amazon-ssm-agent/now 3.0.655.0-1 amd64 [installed,local] 3.0.655.0 is the version of SSM agent Checking the SSM Agent version number 2377 User Guide AWS Systems Manager macOS 1. Log in to your managed node. 2. Run the following command. pkgutil --pkg-info com.amazon.aws.ssm RHEL 1. Log in to your managed node. 2. Run the following command for RHEL 6, 7, 8, and 9. yum info amazon-ssm-agent This command returns output similar to the following. Loaded plugins: extras_suggestions, langpacks, priorities, update-motd Installed Packages Name : amazon-ssm-agent Arch : x86_64 Version : 3.0.655.0 Run the following command for the DNF package utility. dnf info amazon-ssm-agent SLES 1. Log in to your managed node. 2. Run the following command for SLES 12 and 15. zypper info amazon-ssm-agent This command returns output similar to the following. Loading repository data... Reading installed packages... Checking the SSM Agent version number 2378 AWS Systems Manager User Guide Information for package amazon-ssm-agent: ----------------------------------------- Repository : @System Name : amazon-ssm-agent Version : 3.0.655.0-1 Ubuntu Server Note To check if your Ubuntu Server 16.04 instance uses deb or Snap packages, see Manually installing SSM Agent on Ubuntu Server instances. 1. Log in to your managed node. 2. Run the following command for Ubuntu Server 16.04 and 14.04 64-bit (with deb installer package). apt list amazon-ssm-agent This command returns output similar to the following. apt list amazon-ssm-agent Listing... Done amazon-ssm-agent/now 3.0.655.0-1 amd64 [installed,local] 3.0.655.0 is the version of SSM agent Run the following command for Ubuntu Server 22.04 LTS, 20.10 STR and 20.04, 18.04, and 16.04 LTS 64-bit instances (with Snap package). sudo snap list amazon-ssm-agent This command returns output similar to the following. snap list amazon-ssm-agent Name Version Rev Tracking Publisher Notes amazon-ssm-agent 3.0.529.0 3552 latest/stable/… aws# classic- Checking the SSM Agent version number 2379
systems-manager-ug-689
systems-manager-ug.pdf
689
node. 2. Run the following command for Ubuntu Server 16.04 and 14.04 64-bit (with deb installer package). apt list amazon-ssm-agent This command returns output similar to the following. apt list amazon-ssm-agent Listing... Done amazon-ssm-agent/now 3.0.655.0-1 amd64 [installed,local] 3.0.655.0 is the version of SSM agent Run the following command for Ubuntu Server 22.04 LTS, 20.10 STR and 20.04, 18.04, and 16.04 LTS 64-bit instances (with Snap package). sudo snap list amazon-ssm-agent This command returns output similar to the following. snap list amazon-ssm-agent Name Version Rev Tracking Publisher Notes amazon-ssm-agent 3.0.529.0 3552 latest/stable/… aws# classic- Checking the SSM Agent version number 2379 AWS Systems Manager User Guide 3.0.529.0 is the version of SSM agent Windows 1. Log in to your managed node. 2. Run the following PowerShell command. & "C:\Program Files\Amazon\SSM\amazon-ssm-agent.exe" -version This command returns output similar to the following. SSM Agent version: 3.1.804.0 We recommend using the latest version of the SSM Agent so you can benefit from new or updated capabilities. To ensure your managed instances are always running the most up-to-date version of the SSM Agent, you can automate the process of updating the SSM Agent. For more information, see Automating updates to SSM Agent. Viewing SSM Agent logs AWS Systems Manager Agent (SSM Agent) writes information about executions, commands, scheduled actions, errors, and health statuses to log files on each managed node. You can view log files by manually connecting to a managed node, or you can automatically send logs to Amazon CloudWatch Logs. For more information about sending logs to CloudWatch Logs, see Logging and monitoring in AWS Systems Manager. You can view SSM Agent logs on managed nodes in the following locations. Linux and macOS /var/log/amazon/ssm/ Windows %PROGRAMDATA%\Amazon\SSM\Logs\ Viewing SSM Agent logs 2380 AWS Systems Manager User Guide For Linux managed nodes, the SSM Agent stderr and stdout files are written to the following directory: /var/lib/amazon/ssm/. For Windows managed nodes, the SSM Agent stderr and stdout files are written to the following directory: %PROGRAMDATA%\Amazon\SSM\InstanceData\. For information about allowing SSM Agent debug logging, see Allowing SSM Agent debug logging. For more information about cihub/seelog configuration, see the Seelog Wiki on GitHub. For examples of cihub/seelog configurations, see the cihub/seelog examples repository on GitHub. Allowing SSM Agent debug logging Use the following procedure to allow SSM Agent debug logging on your managed nodes. Linux and macOS To allow SSM Agent debug logging on Linux and macOS managed nodes 1. Either use Session Manager, a tool in AWS Systems Manager, to connect to the managed node where you want to allow debug logging, or log on to the managed node. For more information, see Working with Session Manager. 2. Locate the seelog.xml.template file. Linux: On most Linux managed node types, the file is located in the directory /etc/amazon/ ssm/seelog.xml.template. On Ubuntu Server 20.10 STR & 20.04, 18.04, and 16.04 LTS, the file is located in the directory /snap/amazon-ssm-agent/current/seelog.xml.template. Copy this file from the /snap/amazon-ssm-agent/current/ directory to the /etc/amazon/ssm/ directory before making any changes. macOS: On macOS instance types, the file is located in the directory /opt/aws/ssm/ seelog.xml.template. 3. Change the file name from seelog.xml.template to seelog.xml. Allowing SSM Agent debug logging 2381 AWS Systems Manager User Guide Note On Ubuntu Server 20.10 STR & 20.04, 18.04, and 16.04 LTS, the file seelog.xml must be created in the directory /etc/amazon/ssm/. You can create this directory and file by running the following commands. sudo mkdir -p /etc/amazon/ssm sudo cp -p /snap/amazon-ssm-agent/current/seelog.xml.template /etc/ amazon/ssm/seelog.xml 4. Edit the seelog.xml file to change the default logging behavior. Change the value of minlevel from info to debug, as shown in the following example. <seelog type="adaptive" mininterval="2000000" maxinterval="100000000" critmsgcount="500" minlevel="debug"> 5. (Optional) Restart SSM Agent using the following command. Linux: sudo service amazon-ssm-agent restart macOS: sudo /opt/aws/ssm/bin/amazon-ssm-agent restart Windows To allow SSM Agent debug logging on Windows Server managed nodes 1. Either use Session Manager to connect to the managed node where you want to allow debug logging, or log on to the managed nodes. For more information, see Working with Session Manager. 2. Make a copy of the seelog.xml.template file. Change the name of the copy to seelog.xml. The file is located in the following directory. Allowing SSM Agent debug logging 2382 AWS Systems Manager User Guide %PROGRAMFILES%\Amazon\SSM\seelog.xml.template 3. Edit the seelog.xml file to change the default logging behavior. Change the value of minlevel from info to debug, as shown in the following example. <seelog type="adaptive" mininterval="2000000" maxinterval="100000000" critmsgcount="500" minlevel="debug"> 4. Locate the following entry. filename="{{LOCALAPPDATA}}\Amazon\SSM\Logs\{{EXECUTABLENAME}}.log" Change this entry to use the following path. filename="C:\ProgramData\Amazon\SSM\Logs\{{EXECUTABLENAME}}.log" 5. Locate the following entry. filename="{{LOCALAPPDATA}}\Amazon\SSM\Logs\errors.log" Change this entry to use the following path. filename="C:\ProgramData\Amazon\SSM\Logs\errors.log" 6. Restart SSM Agent using the following PowerShell command in Administrator mode. Restart-Service AmazonSSMAgent Restricting access to root-level commands through SSM Agent AWS Systems Manager Agent (SSM Agent) runs on Amazon Elastic Compute Cloud (Amazon
systems-manager-ug-690
systems-manager-ug.pdf
690
User Guide %PROGRAMFILES%\Amazon\SSM\seelog.xml.template 3. Edit the seelog.xml file to change the default logging behavior. Change the value of minlevel from info to debug, as shown in the following example. <seelog type="adaptive" mininterval="2000000" maxinterval="100000000" critmsgcount="500" minlevel="debug"> 4. Locate the following entry. filename="{{LOCALAPPDATA}}\Amazon\SSM\Logs\{{EXECUTABLENAME}}.log" Change this entry to use the following path. filename="C:\ProgramData\Amazon\SSM\Logs\{{EXECUTABLENAME}}.log" 5. Locate the following entry. filename="{{LOCALAPPDATA}}\Amazon\SSM\Logs\errors.log" Change this entry to use the following path. filename="C:\ProgramData\Amazon\SSM\Logs\errors.log" 6. Restart SSM Agent using the following PowerShell command in Administrator mode. Restart-Service AmazonSSMAgent Restricting access to root-level commands through SSM Agent AWS Systems Manager Agent (SSM Agent) runs on Amazon Elastic Compute Cloud (Amazon EC2) instances and other machine types in hybrid and multicloud environments using root permissions (Linux) or SYSTEM permissions (Windows Server). Because these are the highest level of system access permissions, any trusted entity that has been granted permission to send commands to SSM Agent has root or SYSTEM permissions. (In AWS, a trusted entity that can perform actions and access resources in AWS is called a principal. A principal can be an AWS account root user, user, or a role.) This level of access is required for a principal to send authorized Systems Manager commands to SSM Agent, but also makes it possible for a principal to run malicious code by exploiting any potential vulnerabilities in SSM Agent. Restricting access to root-level commands through SSM Agent 2383 AWS Systems Manager User Guide In particular, permissions to run the commands SendCommand and StartSession should be carefully restricted. A good first step is to grant permissions for each command only to select principals in your organization. However, we recommend tightening your security posture even further by restricting which managed nodes a principal can run these commands on. This can be done in the IAM policy assigned to the principal. In the IAM policy, you can include a condition that limits the user to running commands only on managed nodes that are tagged with specific tags or a combination of tags. For example, say you have two fleets of servers, one for testing, one for production. In the IAM policy applied to junior engineers, you specify that they can run commands only on instances tagged with ssm:resourceTag/testServer. But, for a smaller group of lead engineers, who should have access to all instances, you grant access to instances tagged with both ssm:resourceTag/testServer and ssm:resourceTag/productionServer. Using this approach, if junior engineers attempt to run a command on a production instance, they will be denied access because their assigned IAM policy doesn't provide explicit access to instances tagged with ssm:resourceTag/productionServer. For more information and examples, see the following topics: • Restricting Run Command access based on tags • Restrict session access based on instance tags Automating updates to SSM Agent AWS releases a new version of AWS Systems Manager Agent (SSM Agent) when we add or update Systems Manager tools. If your managed nodes use an older version of the agent, then you can't use the new tools or benefit from the updated tools. For these reasons, we recommend that you automate the process of updating SSM Agent on your managed nodes using any of the following methods. Agent updates on the Bottlerocket operating system SSM Agent on the Bottlerocket operating system can't be updated using the Systems Manager Command document AWS-UpdateSSMAgent. Updates are managed within the Bottlerocket control container. For more information, see Bottlerocket Control Container and Bottlerocket update operator on GitHub. macOS version requirement Automating updates to SSM Agent 2384 AWS Systems Manager User Guide If an instance is running macOS version 11.0 (Big Sur) or later, the instance must have the SSM Agent version 3.1.941.0 or higher to run the AWS-UpdateSSMAgent document. If the instance is running a version of SSM Agent released before 3.1.941.0, update your SSM Agent to run the AWS-UpdateSSMAgent by running brew update and brew upgrade amazon-ssm-agent commands. Method Details One-click automated update on all managed nodes (Recommended) You can configure all managed nodes in your AWS account to automatically check for and Global or selective update download new versions of SSM Agent. To do this, choose Auto update SSM Agent on the Settings tab in Fleet Manager, as described later in this topic. You can use State Manager, a tool in AWS Systems Manager, to create an association that automatically downloads and installs SSM Agent on your managed nodes. If you want to limit the disruption to your workloads, you can create a Systems Manager maintenance window to perform the installation during designated time periods. Both methods allow you to create either a global update configura tion for all of your managed nodes or selective ly choose which instances get updated. For information about creating a State Manager association, see Walkthrough: Automatically update SSM Agent with the AWS CLI. For information about creating a maintenance window, see Tutorial:
systems-manager-ug-691
systems-manager-ug.pdf
691
a tool in AWS Systems Manager, to create an association that automatically downloads and installs SSM Agent on your managed nodes. If you want to limit the disruption to your workloads, you can create a Systems Manager maintenance window to perform the installation during designated time periods. Both methods allow you to create either a global update configura tion for all of your managed nodes or selective ly choose which instances get updated. For information about creating a State Manager association, see Walkthrough: Automatically update SSM Agent with the AWS CLI. For information about creating a maintenance window, see Tutorial: Create a maintenance window for patching using the console. Global or selective update for new environme nts If you're getting started with Systems Manager, we recommend that you use the Update Systems Manager (SSM) Agent every two weeks option in Quick Setup, a tool in Automating updates to SSM Agent 2385 AWS Systems Manager Method User Guide Details AWS Systems Manager. Quick Setup allows you to create either a global update configura tion for all of your managed nodes or selective ly choose which managed nodes get updated. For more information, see Set up Amazon EC2 host management using Quick Setup. If you prefer to update SSM Agent on your managed nodes manually, you can subscribe to notifications that AWS publishes when a new version of the agent is released. For information, see Subscribing to SSM Agent notifications. After you subscribe to notifications, you can use Run Command to manually update one or more managed nodes with the latest version. For more information, see Updating the SSM Agent using Run Command. Automatically updating SSM Agent You can configure Systems Manager to automatically update SSM Agent on all Linux-based and Windows-based managed nodes in your AWS account. If you turn on this option, then Systems Manager automatically checks every two weeks for a new version of the agent. If there is a new version, then Systems Manager automatically updates the agent to the latest released version using the SSM document AWS-UpdateSSMAgent. We encourage you to choose this option to ensure that your managed nodes are always running the most up-to-date version of SSM Agent. Note If you use a yum command to update SSM Agent on a managed node after the agent has been installed or updated using the SSM document AWS-UpdateSSMAgent, you might see the following message: "Warning: RPMDB altered outside of yum." This message is expected and can be safely ignored. To automatically update SSM Agent 1. Open the AWS Systems Manager console at https://console.aws.amazon.com/systems- manager/. 2. In the navigation pane, choose Fleet Manager. Automatically updating SSM Agent 2386 AWS Systems Manager 3. Choose the Settings tab. 4. In the Agent auto update area, choose Auto update SSM Agent. User Guide To change the version of SSM Agent your fleet updates to, choose Edit under Agent auto update on the Settings tab. Then enter the version number of SSM Agent you want to update to in Version under Parameters. If not specified, the agent updates to the latest version. To stop automatically deploying updated versions of SSM Agent to all managed nodes in your account, choose Delete under Agent auto update on the Settings tab. This action deletes the State Manager association that automatically updates SSM Agent on your managed nodes. Subscribing to SSM Agent notifications Amazon Simple Notification Service (Amazon SNS) can notify you when new versions of AWS Systems Manager Agent (SSM Agent) are released. Use the following procedure to subscribe to these notifications. Tip You can also subscribe to notifications by watching the SSM Agent Release Notes page on GitHub. To subscribe to SSM Agent notifications 1. Open the Amazon SNS console at https://console.aws.amazon.com/sns/v3/home. 2. From the Region selector in the navigation bar, choose US East (N. Virginia), if it isn't selected already. You must select this AWS Region because the Amazon SNS notifications for SSM Agent that you're subscribing to are generated from this Region only. 3. In the navigation pane, choose Subscriptions. 4. Choose Create subscription. 5. For Create subscription, do the following: a. For Topic ARN, use the following Amazon Resource Name (ARN): arn:aws:sns:us-east-1:720620558202:SSM-Agent-Update Subscribing to SSM Agent notifications 2387 AWS Systems Manager User Guide b. c. For Protocol, choose Email or SMS. For Endpoint, depending on whether you chose Email or SMS in the previous step, enter an email address or an area code and number to receive notifications. d. Choose Create subscription. 6. If you chose Email, you will receive an email message asking you to confirm your subscription. Open the message, and follow the directions to complete your subscription. Whenever a new version of SSM Agent is released, we send notifications to subscribers. If you no longer want to receive these notifications, use the following procedure to unsubscribe. To unsubscribe
systems-manager-ug-692
systems-manager-ug.pdf
692
User Guide b. c. For Protocol, choose Email or SMS. For Endpoint, depending on whether you chose Email or SMS in the previous step, enter an email address or an area code and number to receive notifications. d. Choose Create subscription. 6. If you chose Email, you will receive an email message asking you to confirm your subscription. Open the message, and follow the directions to complete your subscription. Whenever a new version of SSM Agent is released, we send notifications to subscribers. If you no longer want to receive these notifications, use the following procedure to unsubscribe. To unsubscribe from SSM Agent notifications 1. Open the Amazon SNS console. 2. 3. In the navigation pane, choose Subscriptions. Select the subscription, and then choose Delete. When prompted for confirmation, choose Delete. Troubleshooting SSM Agent If you experience problems running operations on your managed nodes, there might be a problem with AWS Systems Manager Agent (SSM Agent). Use the following information to help you view SSM Agent log files and troubleshoot the agent. Topics • SSM Agent is out of date • Troubleshoot issues using SSM Agent log files • Agent log files don't rotate (Windows) • Unable to connect to SSM endpoints • Verify your VPC configuration • Verify your VPC DNS-related attributes • Verify ingress rules on endpoint security groups • Use ssm-cli to troubleshoot managed node availability Troubleshooting SSM Agent 2388 AWS Systems Manager User Guide SSM Agent is out of date An updated version of SSM Agent is released whenever new tools are added to Systems Manager or updates are made to existing tools. Failing to use the latest version of the agent can prevent your managed node from using various Systems Manager tools and features. For that reason, we recommend that you automate the process of keeping SSM Agent up to date on your machines. For information, see Automating updates to SSM Agent. Subscribe to the SSM Agent Release Notes page on GitHub to get notifications about SSM Agent updates. Troubleshoot issues using SSM Agent log files SSM Agent logs information in the following files. The information in these files can also help you troubleshoot problems. For more information about SSM Agent log files, including how to turn on debug logging, see Viewing SSM Agent logs. Note If you choose to view these logs by using Windows File Explorer, be sure to allow the viewing of hidden files and system files in Folder Options. On Windows • %PROGRAMDATA%\Amazon\SSM\Logs\amazon-ssm-agent.log • %PROGRAMDATA%\Amazon\SSM\Logs\errors.log On Linux and macOS • /var/log/amazon/ssm/amazon-ssm-agent.log • /var/log/amazon/ssm/errors.log For Linux managed nodes, you might find more information in the messages file written to the following directory: /var/log. For additional information about troubleshooting using agent logs, see How do I use SSM Agent logs to troubleshoot issues with SSM Agent in my managed instance? in the AWS re:Post Knowledge Center. SSM Agent is out of date 2389 AWS Systems Manager User Guide Agent log files don't rotate (Windows) If you specify date-based log file rotation in the seelog.xml file (on Windows Server managed nodes) and the logs don't rotate, specify the fullname=true parameter. Here is an example of a seelog.xml configuration file with the fullname=true parameter specified. <seelog type="adaptive" mininterval="2000000" maxinterval="100000000" critmsgcount="500" minlevel="debug"> <exceptions> <exception filepattern="test*" minlevel="error" /> </exceptions> <outputs formatid="fmtinfo"> <console formatid="fmtinfo" /> <rollingfile type="date" datepattern="200601021504" maxrolls="4" filename="C: \ProgramData\Amazon\SSM\Logs\amazon-ssm-agent.log" fullname=true /> <filter levels="error,critical" formatid="fmterror"> <rollingfile type="date" datepattern="200601021504" maxrolls="4" filename="C: \ProgramData\Amazon\SSM\Logs\errors.log" fullname=true /> </filter> </outputs> <formats> <format id="fmterror" format="%Date %Time %LEVEL [%FuncShort @ %File.%Line] %Msg %n" /> <format id="fmtdebug" format="%Date %Time %LEVEL [%FuncShort @ %File.%Line] %Msg %n" /> <format id="fmtinfo" format="%Date %Time %LEVEL %Msg%n" /> </formats> </seelog> Unable to connect to SSM endpoints SSM Agent must allow HTTPS (port 443) outbound traffic to the following endpoints: • ssm.region.amazonaws.com • ssmmessages.region.amazonaws.com region represents the identifier for an AWS Region supported by AWS Systems Manager, such as us-east-2 for the US East (Ohio) Region. For a list of supported region values, see the Region column in Systems Manager service endpoints in the Amazon Web Services General Reference. Agent log files don't rotate (Windows) 2390 AWS Systems Manager Note User Guide Prior to 2024, ec2messages.region.amazonaws.com was also required. For AWS Regions launched before 2024, allowing traffic to ssmmessages.region.amazonaws.com is still required but optional to ec2messages.region.amazonaws.com. For Regions launched in 2024 and later, allowing traffic to ssmmessages.region.amazonaws.com is required, but ec2messages.region.amazonaws.com endpoints are not supported for these Regions. SSM Agent won't work if it can't communicate with the preceding endpoints, as described, even if you use AWS provided Amazon Machine Images (AMIs) such as Amazon Linux 2 or Amazon Linux 2023. Your network configuration must have open internet access or you must have custom virtual private cloud (VPC) endpoints configured. If you don't plan on creating a custom VPC endpoint, check your internet gateways or NAT gateways. For more information about
systems-manager-ug-693
systems-manager-ug.pdf
693
required but optional to ec2messages.region.amazonaws.com. For Regions launched in 2024 and later, allowing traffic to ssmmessages.region.amazonaws.com is required, but ec2messages.region.amazonaws.com endpoints are not supported for these Regions. SSM Agent won't work if it can't communicate with the preceding endpoints, as described, even if you use AWS provided Amazon Machine Images (AMIs) such as Amazon Linux 2 or Amazon Linux 2023. Your network configuration must have open internet access or you must have custom virtual private cloud (VPC) endpoints configured. If you don't plan on creating a custom VPC endpoint, check your internet gateways or NAT gateways. For more information about how to manage VPC endpoints, see Improve the security of EC2 instances by using VPC endpoints for Systems Manager. Verify your VPC configuration In order to manage EC2 instances with Systems Manager, your VPC endpoints must be configured properly for ssm.region.amazonaws.com, ssmmessages.region.amazonaws.com, and in some cases explained earlier in this topic in Unable to connect to SSM endpoints, ec2messages.region.amazonaws.com. Your network configuration must have open internet access or you must have these virtual private cloud (VPC) endpoints configured. To troubleshoot issues with your VPC endpoints, do the following: • Ensure that VPC endpoints are included at the VPC level. If the VPC endpoint with a specific service name is not found on the VPC, first verify that DNS support is enabled at the VPC level. Next, create a new VPC endpoint and associate it with one subnet in each Availability Zone. • Ensure that a private DNS name is enabled at the VPC endpoint level. Private DNS names are enabled by default but might have been manually disabled at some point. • Ensure that existing VPC endpoints are associated with the proper subnet. In addition, ensure that the VPCE is already associated with a subnet in that Availability Zone. For more information, see the following topics: Verify your VPC configuration 2391 AWS Systems Manager User Guide • Access an AWS service using an interface VPC endpoint in the AWS PrivateLink Guide • Associate a private DNS name in the AWS PrivateLink Guide • Improve the security of EC2 instances by using VPC endpoints for Systems Manager Verify your VPC DNS-related attributes As part of verifying your VPC configuration, ensure that the attributes enableDnsSupport and enableDnsHostnames are enabled. You can enable these attributes using the Amazon EC2 ModifyVPCAttribute API action or the AWS CLI command modify-vpc-attribute. For information about enabling these attributes in the Amazon VPC Console, see View and update DNS attributes for your VPC in the Amazon VPC User Guide. Verify ingress rules on endpoint security groups Ensure that any VPC endpoints you have configured (ssm, ssmmessages, and ec2messages) include an ingress rule on their security groups to allow traffic in on port 443. If necessary, you can create a new security group in the VPC with an ingress rule to allow traffic on port 443 for the Classless Inter-Domain Routing (CIDR) block for the VPC. After you create the security group, attach it to each VPC endpoint. For more information, see the following topics: • How do I create VPC endpoints so that I can use Systems Manager to manage private EC2 instances without internet access? on AWS re:Post • VPC CIDR blocks in the Amazon VPC User Guide Use ssm-cli to troubleshoot managed node availability Starting with SSM Agent version 3.1.501.0, you can use ssm-cli to determine whether a managed node meets the primary requirements to be managed by Systems Manager, and to appear in lists of managed nodes in Fleet Manager. The ssm-cli is a standalone command line tool included in the SSM Agent installation. Preconfigured commands are included that gather the required information to help you diagnose why an Amazon EC2 instance or non-EC2 machine that you have confirmed is running isn't included in your lists of managed nodes in Systems Manager. These commands are run when you specify the get-diagnostics option. Verify your VPC DNS-related attributes 2392 AWS Systems Manager User Guide For more information, see Troubleshooting managed node availability using ssm-cli. Use ssm-cli to troubleshoot managed node availability 2393 AWS Systems Manager User Guide Security in AWS Systems Manager Cloud security at Amazon Web Services is the highest priority. As an AWS customer, you benefit from a data center and network architecture that are built to meet the requirements of the most security-sensitive organizations. Security is a shared responsibility between AWS and you. The shared responsibility model describes this as security of the cloud and security in the cloud: • Security of the cloud – AWS is responsible for protecting the infrastructure that runs AWS services in the AWS Cloud. AWS also provides you with services that you can use securely. Third- party auditors regularly test and verify the effectiveness of our security as part of the AWS Compliance Programs. To learn about
systems-manager-ug-694
systems-manager-ug.pdf
694
you benefit from a data center and network architecture that are built to meet the requirements of the most security-sensitive organizations. Security is a shared responsibility between AWS and you. The shared responsibility model describes this as security of the cloud and security in the cloud: • Security of the cloud – AWS is responsible for protecting the infrastructure that runs AWS services in the AWS Cloud. AWS also provides you with services that you can use securely. Third- party auditors regularly test and verify the effectiveness of our security as part of the AWS Compliance Programs. To learn about the compliance programs that apply to AWS Systems Manager, see AWS services in Scope by Compliance Program. • Security in the cloud – Your responsibility is determined by the AWS service that you use. You're also responsible for other factors including the sensitivity of your data, your company’s requirements, and applicable laws and regulations. This documentation helps you understand how to apply the shared responsibility model when using AWS Systems Manager. The following topics show you how to configure Systems Manager to meet your security and compliance objectives. You also learn how to use other AWS services that help you to monitor and secure your Systems Manager resources. Topics • Data protection in AWS Systems Manager • Identity and access management for AWS Systems Manager • Using service-linked roles for Systems Manager • Logging and monitoring in AWS Systems Manager • Compliance validation for AWS Systems Manager • Resilience in AWS Systems Manager • Infrastructure security in AWS Systems Manager • Configuration and vulnerability analysis in AWS Systems Manager • Security best practices for Systems Manager 2394 AWS Systems Manager User Guide Data protection in AWS Systems Manager Data protection refers to protecting data while in transit (as it travels to and from Systems Manager) and at rest (while it's stored in AWS data centers). The AWS shared responsibility model applies to data protection in AWS Systems Manager. As described in this model, AWS is responsible for protecting the global infrastructure that runs all of the AWS Cloud. You are responsible for maintaining control over your content that is hosted on this infrastructure. You are also responsible for the security configuration and management tasks for the AWS services that you use. For more information about data privacy, see the Data Privacy FAQ. For information about data protection in Europe, see the AWS Shared Responsibility Model and GDPR blog post on the AWS Security Blog. For data protection purposes, we recommend that you protect AWS account credentials and set up individual users with AWS IAM Identity Center or AWS Identity and Access Management (IAM). That way, each user is given only the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the following ways: • Use multi-factor authentication (MFA) with each account. • Use SSL/TLS to communicate with AWS resources. We require TLS 1.2 and recommend TLS 1.3. • Set up API and user activity logging with AWS CloudTrail. For information about using CloudTrail trails to capture AWS activities, see Working with CloudTrail trails in the AWS CloudTrail User Guide. • Use AWS encryption solutions, along with all default security controls within AWS services. • Use advanced managed security services such as Amazon Macie, which assists in discovering and securing sensitive data that is stored in Amazon S3. • If you require FIPS 140-3 validated cryptographic modules when accessing AWS through a command line interface or an API, use a FIPS endpoint. For more information about the available FIPS endpoints, see Federal Information Processing Standard (FIPS) 140-3. We strongly recommend that you never put confidential or sensitive information, such as your customers' email addresses, into tags or free-form text fields such as a Name field. This includes when you work with Systems Manager or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter into tags or free-form text fields used for names may be used for billing or diagnostic logs. If you provide a URL to an external server, we strongly recommend that you do not include credentials information in the URL to validate your request to that server. Data protection 2395 AWS Systems Manager Data encryption Encryption at rest Parameter Store parameters User Guide The types of parameters you can create in Parameter Store, a tool in AWS Systems Manager, include String, StringList, and SecureString. All parameters, regardless of their type, are encrypted both in transit and at rest. In transit, parameters are encrypted using transport layer security (TLS) to create a secure HTTPS connection for API requests. At rest, they are encrypted with an AWS owned key in AWS Key Management Service (AWS KMS). For more information about AWS owned key encryption, see AWS
systems-manager-ug-695
systems-manager-ug.pdf
695
to that server. Data protection 2395 AWS Systems Manager Data encryption Encryption at rest Parameter Store parameters User Guide The types of parameters you can create in Parameter Store, a tool in AWS Systems Manager, include String, StringList, and SecureString. All parameters, regardless of their type, are encrypted both in transit and at rest. In transit, parameters are encrypted using transport layer security (TLS) to create a secure HTTPS connection for API requests. At rest, they are encrypted with an AWS owned key in AWS Key Management Service (AWS KMS). For more information about AWS owned key encryption, see AWS owned keys in the AWS Key Management Service Developer Guide . The SecureString type offers additional encryption options and is recommended for all sensitive data. You can choose from the following types of AWS KMS keys to encrypt and decrypt the value of a SecureString parameter: • The AWS managed key for your account • A customer managed key (CMK) that you have created in your account • A CMK in another AWS account that has been shared with you For more information about AWS KMS encryption, see the AWS Key Management Service Developer Guide. Content in S3 buckets As part of your Systems Manager operations, you might choose to upload or store data in one or more Amazon Simple Storage Service (Amazon S3) buckets. For information about S3 bucket encryption, see Protecting data using encryption and Data protection in Amazon S3 in the Amazon Simple Storage Service User Guide. The following are types of data you can upload or have stored in S3 buckets as part of your Systems Manager activities: • The output of commands in Run Command, a tool in AWS Systems Manager • Packages in Distributor, a tool in AWS Systems Manager • Patching operation logs in Patch Manager, a tool in AWS Systems Manager Data encryption 2396 AWS Systems Manager User Guide • Patch Manager patch override lists • Scripts or Ansible Playbooks to run in a runbook workflow in Automation, a tool in AWS Systems Manager • Chef InSpec profiles for use with scans in Compliance, a tool in AWS Systems Manager • AWS CloudTrail logs • Session history logs in Session Manager, a tool in AWS Systems Manager • Reports from Explorer, a tool in AWS Systems Manager • OpsData from OpsCenter, a tool in AWS Systems Manager • AWS CloudFormation templates for use with Automation workflows • Compliance data from a resource data sync scan • Output of requests to create or edit association in State Manager, a tool in AWS Systems Manager, on managed nodes • Custom Systems Manager documents (SSM documents) that you can run using the AWS managed SSM document AWS-RunDocument CloudWatch Logs log groups As part of your Systems Manager operations, you might choose to stream data to one or more Amazon CloudWatch Logs log groups. For information about CloudWatch Logs log group encryption, see Encrypt log data in CloudWatch Logs using AWS Key Management Service in the Amazon CloudWatch Logs User Guide. The following are types of data you might have streamed to a CloudWatch Logs log group as part of your Systems Manager activities: • The output of Run Command commands • The output of scripts run using the aws:executeScript action in an Automation runbook • Session Manager session history logs • Logs from SSM Agent on your managed nodes Encryption in transit We recommend that you use an encryption protocol such as Transport Layer Security (TLS) to encrypt sensitive data in transit between clients and your nodes. Data encryption 2397 AWS Systems Manager User Guide Systems Manager provides the following support for encryption of your data in transit. Connections to Systems Manager API endpoints Systems Manager API endpoints only support secure connections over HTTPS. When you manage Systems Manager resources with the AWS Management Console, AWS SDK, or the Systems Manager API, all communication is encrypted with Transport Layer Security (TLS). For a full list of API endpoints, see AWS service endpoints in the Amazon Web Services General Reference. Managed instances AWS provides secure and private connectivity between Amazon Elastic Compute Cloud (Amazon EC2) instances. In addition, we automatically encrypt in-transit traffic between supported instances in the same virtual private cloud (VPC) or in peered VPCs, using AEAD algorithms with 256-bit encryption. This encryption feature uses the offload capabilities of the underlying hardware, and there is no impact on network performance. The supported instances are: C5n, G4, I3en, M5dn, M5n, P3dn, R5dn, and R5n. Session Manager sessions By default, Session Manager uses TLS 1.3 to encrypt session data transmitted between the local machines of users in your account and your EC2 instances. You can also choose to further encrypt the data in transit using an AWS KMS key that has been created in AWS KMS.
systems-manager-ug-696
systems-manager-ug.pdf
696
in the same virtual private cloud (VPC) or in peered VPCs, using AEAD algorithms with 256-bit encryption. This encryption feature uses the offload capabilities of the underlying hardware, and there is no impact on network performance. The supported instances are: C5n, G4, I3en, M5dn, M5n, P3dn, R5dn, and R5n. Session Manager sessions By default, Session Manager uses TLS 1.3 to encrypt session data transmitted between the local machines of users in your account and your EC2 instances. You can also choose to further encrypt the data in transit using an AWS KMS key that has been created in AWS KMS. AWS KMS encryption is available for Standard_Stream, InteractiveCommands, and NonInteractiveCommands session types. Run Command access By default, remote access to your nodes using Run Command is encrypted using TLS 1.3, and requests to create a connection are signed using SigV4. Internetwork traffic privacy You can use Amazon Virtual Private Cloud (Amazon VPC) to create boundaries between resources in your managed nodes and control traffic between them, your on-premises network, and the internet. For details, see Improve the security of EC2 instances by using VPC endpoints for Systems Manager. For more information about Amazon Virtual Private Cloud security, see Internetwork traffic privacy in Amazon VPC in the Amazon VPC User Guide. Internetwork traffic privacy 2398 AWS Systems Manager User Guide Identity and access management for AWS Systems Manager AWS Identity and Access Management (IAM) is an AWS service that helps an administrator securely control access to AWS resources. IAM administrators control who can be authenticated (signed in) and authorized (have permissions) to use Systems Manager resources. IAM is an AWS service that you can use with no additional charge. Topics • Audience • Authenticating with identities • Managing access using policies • How AWS Systems Manager works with IAM • AWS Systems Manager identity-based policy examples • AWS managed policies for AWS Systems Manager • Troubleshooting AWS Systems Manager identity and access Audience How you use AWS Identity and Access Management (IAM) differs, depending on the work that you do in Systems Manager. Service user – If you use the Systems Manager service to do your job, then your administrator provides you with the credentials and permissions that you need. As you use more Systems Manager features to do your work, you might need additional permissions. Understanding how access is managed can help you request the right permissions from your administrator. If you cannot access a feature in Systems Manager, see Troubleshooting AWS Systems Manager identity and access. Service administrator – If you're in charge of Systems Manager resources at your company, you probably have full access to Systems Manager. It's your job to determine which Systems Manager features and resources your service users should access. You must then submit requests to your IAM administrator to change the permissions of your service users. Review the information on this page to understand the basic concepts of IAM. To learn more about how your company can use IAM with Systems Manager, see How AWS Systems Manager works with IAM. IAM administrator – If you're an IAM administrator, you might want to learn details about how you can write policies to manage access to Systems Manager. To view example Systems Manager Identity and access management 2399 AWS Systems Manager User Guide identity-based policies that you can use in IAM, see AWS Systems Manager identity-based policy examples. Authenticating with identities Authentication is how you sign in to AWS using your identity credentials. You must be authenticated (signed in to AWS) as the AWS account root user, as an IAM user, or by assuming an IAM role. You can sign in to AWS as a federated identity by using credentials provided through an identity source. AWS IAM Identity Center (IAM Identity Center) users, your company's single sign-on authentication, and your Google or Facebook credentials are examples of federated identities. When you sign in as a federated identity, your administrator previously set up identity federation using IAM roles. When you access AWS by using federation, you are indirectly assuming a role. Depending on the type of user you are, you can sign in to the AWS Management Console or the AWS access portal. For more information about signing in to AWS, see How to sign in to your AWS account in the AWS Sign-In User Guide. If you access AWS programmatically, AWS provides a software development kit (SDK) and a command line interface (CLI) to cryptographically sign your requests by using your credentials. If you don't use AWS tools, you must sign requests yourself. For more information about using the recommended method to sign requests yourself, see AWS Signature Version 4 for API requests in the IAM User Guide. Regardless of the authentication method that you use, you might be required to provide additional security information. For
systems-manager-ug-697
systems-manager-ug.pdf
697
signing in to AWS, see How to sign in to your AWS account in the AWS Sign-In User Guide. If you access AWS programmatically, AWS provides a software development kit (SDK) and a command line interface (CLI) to cryptographically sign your requests by using your credentials. If you don't use AWS tools, you must sign requests yourself. For more information about using the recommended method to sign requests yourself, see AWS Signature Version 4 for API requests in the IAM User Guide. Regardless of the authentication method that you use, you might be required to provide additional security information. For example, AWS recommends that you use multi-factor authentication (MFA) to increase the security of your account. To learn more, see Multi-factor authentication in the AWS IAM Identity Center User Guide and AWS Multi-factor authentication in IAM in the IAM User Guide. AWS account root user When you create an AWS account, you begin with one sign-in identity that has complete access to all AWS services and resources in the account. This identity is called the AWS account root user and is accessed by signing in with the email address and password that you used to create the account. We strongly recommend that you don't use the root user for your everyday tasks. Safeguard your root user credentials and use them to perform the tasks that only the root user can perform. For the complete list of tasks that require you to sign in as the root user, see Tasks that require root user credentials in the IAM User Guide. Authenticating with identities 2400 AWS Systems Manager IAM users and groups User Guide An IAM user is an identity within your AWS account that has specific permissions for a single person or application. Where possible, we recommend relying on temporary credentials instead of creating IAM users who have long-term credentials such as passwords and access keys. However, if you have specific use cases that require long-term credentials with IAM users, we recommend that you rotate access keys. For more information, see Rotate access keys regularly for use cases that require long- term credentials in the IAM User Guide. An IAM group is an identity that specifies a collection of IAM users. You can't sign in as a group. You can use groups to specify permissions for multiple users at a time. Groups make permissions easier to manage for large sets of users. For example, you could have a group named IAMAdmins and give that group permissions to administer IAM resources. Users are different from roles. A user is uniquely associated with one person or application, but a role is intended to be assumable by anyone who needs it. Users have permanent long-term credentials, but roles provide temporary credentials. To learn more, see Use cases for IAM users in the IAM User Guide. IAM roles An IAM role is an identity within your AWS account that has specific permissions. It is similar to an IAM user, but is not associated with a specific person. To temporarily assume an IAM role in the AWS Management Console, you can switch from a user to an IAM role (console). You can assume a role by calling an AWS CLI or AWS API operation or by using a custom URL. For more information about methods for using roles, see Methods to assume a role in the IAM User Guide. IAM roles with temporary credentials are useful in the following situations: • Federated user access – To assign permissions to a federated identity, you create a role and define permissions for the role. When a federated identity authenticates, the identity is associated with the role and is granted the permissions that are defined by the role. For information about roles for federation, see Create a role for a third-party identity provider (federation) in the IAM User Guide. If you use IAM Identity Center, you configure a permission set. To control what your identities can access after they authenticate, IAM Identity Center correlates the permission set to a role in IAM. For information about permissions sets, see Permission sets in the AWS IAM Identity Center User Guide. • Temporary IAM user permissions – An IAM user or role can assume an IAM role to temporarily take on different permissions for a specific task. Authenticating with identities 2401 AWS Systems Manager User Guide • Cross-account access – You can use an IAM role to allow someone (a trusted principal) in a different account to access resources in your account. Roles are the primary way to grant cross- account access. However, with some AWS services, you can attach a policy directly to a resource (instead of using a role as a proxy). To learn the difference between roles and resource-based policies for cross-account access, see Cross account resource access in
systems-manager-ug-698
systems-manager-ug.pdf
698
can assume an IAM role to temporarily take on different permissions for a specific task. Authenticating with identities 2401 AWS Systems Manager User Guide • Cross-account access – You can use an IAM role to allow someone (a trusted principal) in a different account to access resources in your account. Roles are the primary way to grant cross- account access. However, with some AWS services, you can attach a policy directly to a resource (instead of using a role as a proxy). To learn the difference between roles and resource-based policies for cross-account access, see Cross account resource access in IAM in the IAM User Guide. • Cross-service access – Some AWS services use features in other AWS services. For example, when you make a call in a service, it's common for that service to run applications in Amazon EC2 or store objects in Amazon S3. A service might do this using the calling principal's permissions, using a service role, or using a service-linked role. • Forward access sessions (FAS) – When you use an IAM user or role to perform actions in AWS, you are considered a principal. When you use some services, you might perform an action that then initiates another action in a different service. FAS uses the permissions of the principal calling an AWS service, combined with the requesting AWS service to make requests to downstream services. FAS requests are only made when a service receives a request that requires interactions with other AWS services or resources to complete. In this case, you must have permissions to perform both actions. For policy details when making FAS requests, see Forward access sessions. • Service role – A service role is an IAM role that a service assumes to perform actions on your behalf. An IAM administrator can create, modify, and delete a service role from within IAM. For more information, see Create a role to delegate permissions to an AWS service in the IAM User Guide. • Service-linked role – A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles. • Applications running on Amazon EC2 – You can use an IAM role to manage temporary credentials for applications that are running on an EC2 instance and making AWS CLI or AWS API requests. This is preferable to storing access keys within the EC2 instance. To assign an AWS role to an EC2 instance and make it available to all of its applications, you create an instance profile that is attached to the instance. An instance profile contains the role and enables programs that are running on the EC2 instance to get temporary credentials. For more information, see Use an IAM role to grant permissions to applications running on Amazon EC2 instances in the IAM User Guide. Authenticating with identities 2402 AWS Systems Manager User Guide Managing access using policies You control access in AWS by creating policies and attaching them to AWS identities or resources. A policy is an object in AWS that, when associated with an identity or resource, defines their permissions. AWS evaluates these policies when a principal (user, root user, or role session) makes a request. Permissions in the policies determine whether the request is allowed or denied. Most policies are stored in AWS as JSON documents. For more information about the structure and contents of JSON policy documents, see Overview of JSON policies in the IAM User Guide. Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. By default, users and roles have no permissions. To grant users permission to perform actions on the resources that they need, an IAM administrator can create IAM policies. The administrator can then add the IAM policies to roles, and users can assume the roles. IAM policies define permissions for an action regardless of the method that you use to perform the operation. For example, suppose that you have a policy that allows the iam:GetRole action. A user with that policy can get role information from the AWS Management Console, the AWS CLI, or the AWS API. Identity-based policies Identity-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, group of users, or role. These policies control what actions users and roles can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see Define custom IAM permissions with customer managed policies in the IAM User Guide. Identity-based
systems-manager-ug-699
systems-manager-ug.pdf
699
For example, suppose that you have a policy that allows the iam:GetRole action. A user with that policy can get role information from the AWS Management Console, the AWS CLI, or the AWS API. Identity-based policies Identity-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, group of users, or role. These policies control what actions users and roles can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see Define custom IAM permissions with customer managed policies in the IAM User Guide. Identity-based policies can be further categorized as inline policies or managed policies. Inline policies are embedded directly into a single user, group, or role. Managed policies are standalone policies that you can attach to multiple users, groups, and roles in your AWS account. Managed policies include AWS managed policies and customer managed policies. To learn how to choose between a managed policy or an inline policy, see Choose between managed policies and inline policies in the IAM User Guide. For information about AWS managed policies for Systems Manager, see AWS Systems Manager managed policies. Managing access using policies 2403 AWS Systems Manager Resource-based policies User Guide Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-based policies are IAM role trust policies and Amazon S3 bucket policies. In services that support resource-based policies, service administrators can use them to control access to a specific resource. For the resource where the policy is attached, the policy defines what actions a specified principal can perform on that resource and under what conditions. You must specify a principal in a resource-based policy. Principals can include accounts, users, roles, federated users, or AWS services. Resource-based policies are inline policies that are located in that service. You can't use AWS managed policies from IAM in a resource-based policy. Policy condition keys The actions that users and roles can perform and the resources on which they can take those actions can be further restricted by specific conditions. In JSON policy documents, the Condition element (or Condition block) lets you specify conditions in which a statement is in effect. The Condition element is optional. You can create conditional expressions that use condition operators, such as StringEquals or StringNotLike, to match the condition in the policy with values in the request. If you specify multiple Condition elements in a statement, or multiple keys in a single Condition element, AWS evaluates them using a logical AND operation. If you specify multiple values for a single condition key, AWS evaluates the condition using a logical OR operation. All of the conditions must be met before the statement's permissions are granted. You can also use placeholder variables when you specify conditions. For example, you can grant an IAM user permission to access a resource only if it is tagged with their IAM user name. For more information, see IAM policy elements: variables and tags in the IAM User Guide. AWS supports global condition keys and service-specific condition keys. For more information, see AWS global condition context keys in the IAM User Guide. Important If you use Systems Manager Automation, we recommend you don't use the aws:SourceIp condition key in your policies. The behavior of this condition key is dependent on multiple Managing access using policies 2404 AWS Systems Manager User Guide factors, including whether an IAM role for Automation runbook execution is supplied and the Automation actions used in the runbook. As a result, the condition key can produce unexpected behavior. For this reason, we recommend you don't use it. Systems Manager supports a number of its own condition keys. For more information, see Condition Keys for AWS Systems Manager in the Service Authorization Reference. The actions and resources you can use a Systems Manager-specific condition key with are listed in Resource types defined by AWS Systems Manager in the Service Authorization Reference. If your policy must depend on a service principal name owned by the Systems Manager service, we recommend you check for its existence or non-existence using the aws:PrincipalServiceNamesList multivalued condition key, rather than the aws:PrincipalServiceName condition key. The aws:PrincipalServiceName condition key contains only one entry from the list of service principal names and it may not always be the service principal name you expect. The following Condition block demonstrates checking for the existence of ssm.amazonaws.com. { "Condition": { "ForAnyValue:StringEquals": { "aws:PrincipalServiceNamesList": "ssm.amazonaws.com" } } } To view examples of Systems Manager identity-based policies, see AWS Systems Manager identity- based policy examples. Access control lists (ACLs) Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format. Amazon S3, AWS WAF, and
systems-manager-ug-700
systems-manager-ug.pdf
700
entry from the list of service principal names and it may not always be the service principal name you expect. The following Condition block demonstrates checking for the existence of ssm.amazonaws.com. { "Condition": { "ForAnyValue:StringEquals": { "aws:PrincipalServiceNamesList": "ssm.amazonaws.com" } } } To view examples of Systems Manager identity-based policies, see AWS Systems Manager identity- based policy examples. Access control lists (ACLs) Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format. Amazon S3, AWS WAF, and Amazon VPC are examples of services that support ACLs. To learn more about ACLs, see Access control list (ACL) overview in the Amazon Simple Storage Service Developer Guide. Managing access using policies 2405 AWS Systems Manager Other policy types User Guide AWS supports additional, less-common policy types. These policy types can set the maximum permissions granted to you by the more common policy types. • Permissions boundaries – A permissions boundary is an advanced feature in which you set the maximum permissions that an identity-based policy can grant to an IAM entity (IAM user or role). You can set a permissions boundary for an entity. The resulting permissions are the intersection of an entity's identity-based policies and its permissions boundaries. Resource-based policies that specify the user or role in the Principal field are not limited by the permissions boundary. An explicit deny in any of these policies overrides the allow. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. • Service control policies (SCPs) – SCPs are JSON policies that specify the maximum permissions for an organization or organizational unit (OU) in AWS Organizations. AWS Organizations is a service for grouping and centrally managing multiple AWS accounts that your business owns. If you enable all features in an organization, then you can apply service control policies (SCPs) to any or all of your accounts. The SCP limits permissions for entities in member accounts, including each AWS account root user. For more information about Organizations and SCPs, see Service control policies in the AWS Organizations User Guide. • Resource control policies (RCPs) – RCPs are JSON policies that you can use to set the maximum available permissions for resources in your accounts without updating the IAM policies attached to each resource that you own. The RCP limits permissions for resources in member accounts and can impact the effective permissions for identities, including the AWS account root user, regardless of whether they belong to your organization. For more information about Organizations and RCPs, including a list of AWS services that support RCPs, see Resource control policies (RCPs) in the AWS Organizations User Guide. • Session policies – Session policies are advanced policies that you pass as a parameter when you programmatically create a temporary session for a role or federated user. The resulting session's permissions are the intersection of the user or role's identity-based policies and the session policies. Permissions can also come from a resource-based policy. An explicit deny in any of these policies overrides the allow. For more information, see Session policies in the IAM User Guide. Managing access using policies 2406 AWS Systems Manager Multiple policy types User Guide When multiple types of policies apply to a request, the resulting permissions are more complicated to understand. To learn how AWS determines whether to allow a request when multiple policy types are involved, see Policy evaluation logic in the IAM User Guide. How AWS Systems Manager works with IAM Before you use AWS Identity and Access Management (IAM) to manage access to AWS Systems Manager, you should understand what IAM features are available to use with Systems Manager. To get a high-level view of how Systems Manager and other AWS services work with IAM, see AWS services that work with IAM in the IAM User Guide. Topics • Systems Manager identity-based policies • Systems Manager resource-based policies • Authorization based on Systems Manager tags • Systems Manager IAM roles Systems Manager identity-based policies With IAM identity-based policies, you can specify allowed or denied actions and resources and the conditions under which actions are allowed or denied. Systems Manager supports specific actions, resources, and condition keys. To learn about all of the elements that you use in a JSON policy, see IAM JSON policy elements reference in the IAM User Guide. Actions Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Action element of a JSON policy describes the actions that you can use to allow or deny access in a policy. Policy actions usually have the same name as the associated AWS API
systems-manager-ug-701
systems-manager-ug.pdf
701
are allowed or denied. Systems Manager supports specific actions, resources, and condition keys. To learn about all of the elements that you use in a JSON policy, see IAM JSON policy elements reference in the IAM User Guide. Actions Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Action element of a JSON policy describes the actions that you can use to allow or deny access in a policy. Policy actions usually have the same name as the associated AWS API operation. There are some exceptions, such as permission-only actions that don't have a matching API operation. There are also some operations that require multiple actions in a policy. These additional actions are called dependent actions. Include actions in a policy to grant permissions to perform the associated operation. How AWS Systems Manager works with IAM 2407 AWS Systems Manager User Guide Policy actions in Systems Manager use the following prefix before the action: ssm:. For example, to grant someone permission to create a Systems Manager parameter (SSM parameter) with the Systems Manager PutParameter API operation, you include the ssm:PutParameter action in their policy. Policy statements must include either an Action or NotAction element. Systems Manager defines its own set of actions that describe tasks that you can perform with this service. To specify multiple actions in a single statement, separate them with commas as follows: "Action": [ "ssm:action1", "ssm:action2" ] Note The following tools in AWS Systems Manager use different prefixes before actions. • AWS AppConfig uses the prefix appconfig: before actions. • Incident Manager uses the prefix ssm-incidents: or ssm-contacts: before actions. • Systems Manager GUI Connect uses the prefix ssm-guiconnect: before actions. • Quick Setup uses the prefix ssm-quicksetup: before actions. You can specify multiple actions using wildcards (*). For example, to specify all actions that begin with the word Describe, include the following action: "Action": "ssm:Describe*" To see a list of Systems Manager actions, see Actions Defined by AWS Systems Manager in the Service Authorization Reference. Resources Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Resource JSON policy element specifies the object or objects to which the action applies. Statements must include either a Resource or a NotResource element. As a best practice, How AWS Systems Manager works with IAM 2408 AWS Systems Manager User Guide specify a resource using its Amazon Resource Name (ARN). You can do this for actions that support a specific resource type, known as resource-level permissions. For actions that don't support resource-level permissions, such as listing operations, use a wildcard (*) to indicate that the statement applies to all resources. "Resource": "*" For example, the Systems Manager maintenance window resource has the following ARN format. arn:aws:ssm:region:account-id:maintenancewindow/window-id To specify the mw-0c50858d01EXAMPLE maintenance windows in your statement in the US East (Ohio) Region, you would use an ARN similar to the following. "Resource": "arn:aws:ssm:us-east-2:123456789012:maintenancewindow/mw-0c50858d01EXAMPLE" To specify all maintenance windows that belong to a specific account, use the wildcard (*). "Resource": "arn:aws:ssm:region:123456789012:maintenancewindow/*" For Parameter Store API operations, you can provide or restrict access to all parameters in one level of a hierarchy by using hierarchical names and AWS Identity and Access Management (IAM) policies as follows. "Resource": "arn:aws:ssm:region:123456789012:parameter/Dev/ERP/Oracle/*" Some Systems Manager actions, such as those for creating resources, can't be performed on a specific resource. In those cases, you must use the wildcard (*). "Resource": "*" Some Systems Manager API operations accept multiple resources. To specify multiple resources in a single statement, separate their ARNs with commas as follows. "Resource": [ How AWS Systems Manager works with IAM 2409 AWS Systems Manager "resource1", "resource2" Note User Guide Most AWS services treat a colon (:) or a forward slash (/) as the same character in ARNs. However, Systems Manager requires an exact match in resource patterns and rules. When creating event patterns, be sure to use the correct ARN characters so that they match the resource's ARN. The table below describes the ARN formats for the resource types supported by Systems Manager. Note Note the following exceptions to ARN formats. • The following tools in AWS Systems Manager use different prefixes before actions. • AWS AppConfig uses the prefix appconfig: before actions. • Incident Manager uses the prefix ssm-incidents: or ssm-contacts: before actions. • Systems Manager GUI Connect uses the prefix ssm-guiconnect before actions. • Documents and automation definition resources that are owned by Amazon, as well as public parameters that are provided by both Amazon and third-party sources, do not include account IDs in their ARN formats. For example: • The SSM document AWS-RunPatchBaseline: arn:aws:ssm:us-east-2::document/AWS-RunPatchBaseline • The automation runbook AWS-ConfigureMaintenanceWindows: arn:aws:ssm:us-east-2::automation-definition/AWS- ConfigureMaintenanceWindows • The public
systems-manager-ug-702
systems-manager-ug.pdf
702
exceptions to ARN formats. • The following tools in AWS Systems Manager use different prefixes before actions. • AWS AppConfig uses the prefix appconfig: before actions. • Incident Manager uses the prefix ssm-incidents: or ssm-contacts: before actions. • Systems Manager GUI Connect uses the prefix ssm-guiconnect before actions. • Documents and automation definition resources that are owned by Amazon, as well as public parameters that are provided by both Amazon and third-party sources, do not include account IDs in their ARN formats. For example: • The SSM document AWS-RunPatchBaseline: arn:aws:ssm:us-east-2::document/AWS-RunPatchBaseline • The automation runbook AWS-ConfigureMaintenanceWindows: arn:aws:ssm:us-east-2::automation-definition/AWS- ConfigureMaintenanceWindows • The public parameter /aws/service/bottlerocket/aws-ecs-1-nvidia/ x86_64/1.13.4/image_version: arn:aws:ssm:us-east-2::parameter/aws/service/bottlerocket/aws- ecs-1-nvidia/x86_64/1.13.4/image_version How AWS Systems Manager works with IAM 2410 AWS Systems Manager User Guide For more information about these three resource types, see the following topics: • Working with documents • Run an automated operation powered by Systems Manager Automation • Working with public parameters in Parameter Store • Quick Setup uses the prefix ssm-quicksetup: before actions. Resource type ARN format Application (AWS AppConfig) arn:aws:appconfig:region:account-id :application/applicati on-id Association arn:aws:ssm:region:account-id :association/association-id Automation execution arn:aws:ssm:region:account-id :automation-execut ion/automation-execution-id Automation definition (with version subresour arn:aws:ssm:region:account-id :automation-defini tion/automation-definition-id :version-id ce) Configuration profile (AWS AppConfig) arn:aws:appconfig:region:account-id :application/applicati on-id /configurationprofile/configurationprofile-id Contact (Incident Manager) arn:aws:ssm-contacts:region:account-id :contact/contact-a lias Deployment strategy (AWS AppConfig) arn:aws:appconfig:region:account-id :deploymentstrateg y/deploymentstrategy-id Document arn:aws:ssm:region:account-id :document/document-name Environment (AWS AppConfig) arn:aws:appconfig:region:account-id :application/applicati on-id /environment/environment-id Incident arn:aws:ssm-incidents:region:account-id :incident- record/response-plan-name /incident-id How AWS Systems Manager works with IAM 2411 AWS Systems Manager User Guide Resource type ARN format Maintenance window arn:aws:ssm:region:account-id :maintenancewindow/window- id Managed node arn:aws:ssm:region:account-id :managed-instance/managed-n ode-id Managed node inventory arn:aws:ssm:region:account-id :managed-instance-inventory /managed-node-id OpsItem arn:aws:ssm:region:account-id :opsitem/OpsItem-id Parameter A one-level parameter: • arn:aws:ssm:region:account-id :parameter/parameter- name/ A parameter named with a hierarchical construction: • arn:aws:ssm:region:account-id :parameter/parameter -name-root /level-2/level-3/level-4/level-5 Patch baseline arn:aws:ssm:region:account-id :patchbaseline/patch-bas eline-id Response plan arn:aws:ssm-incidents:region:account-id :response- plan/response-plan-name Session arn:aws:ssm:region:account-id :session/session-id All Systems Manager resources arn:aws:ssm:* How AWS Systems Manager works with IAM 2412 AWS Systems Manager User Guide Resource type ARN format arn:aws:ssm:region:account-id :* All Systems Manager resources owned by the specified AWS account in the specified AWS Region For automation definitions, Systems Manager supports a second-level resource, version ID. In AWS, these second-level resources are known as subresources. Specifying a version subresource for an automation definition resource allows you to provide access to certain versions of an automation definition. For example, you might want to ensure that only the latest version of an automation definition is used in your node management. To organize and manage parameters, you can create names for parameters with a hierarchical construction. With hierarchical construction, a parameter name can include a path that you define by using forward slashes. You can name a parameter resource with a maximum of fifteen levels. We suggest that you create hierarchies that reflect an existing hierarchical structure in your environment. For more information, see Creating Parameter Store parameters in Systems Manager. In most cases, the session ID is constructed using the ID of the account user who started the session, plus an alphanumeric suffix. For example: arn:aws:us-east-2:111122223333:session/JohnDoe-1a2b3c4sEXAMPLE However, if the user ID isn't available, the ARN is constructed this way instead: arn:aws:us-east-2:111122223333:session/session-1a2b3c4sEXAMPLE For more information about the format of ARNs, see Amazon Resource Names (ARNs) in the Amazon Web Services General Reference. How AWS Systems Manager works with IAM 2413 AWS Systems Manager User Guide For a list of Systems Manager resource types and their ARNs, see Resources Defined by AWS Systems Manager in the Service Authorization Reference. To learn with which actions you can specify the ARN of each resource, see Actions Defined by AWS Systems Manager. Condition keys for Systems Manager Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Condition element (or Condition block) lets you specify conditions in which a statement is in effect. The Condition element is optional. You can create conditional expressions that use condition operators, such as equals or less than, to match the condition in the policy with values in the request. If you specify multiple Condition elements in a statement, or multiple keys in a single Condition element, AWS evaluates them using a logical AND operation. If you specify multiple values for a single condition key, AWS evaluates the condition using a logical OR operation. All of the conditions must be met before the statement's permissions are granted. You can also use placeholder variables when you specify conditions. For example, you can grant an IAM user permission to access a resource only if it is tagged with their IAM user name. For more information, see IAM policy elements: variables and tags in the IAM User Guide. AWS supports global condition keys and service-specific condition keys. To see all AWS global condition keys, see AWS global condition context keys in the IAM User Guide. To see a list
systems-manager-ug-703
systems-manager-ug.pdf
703
evaluates the condition using a logical OR operation. All of the conditions must be met before the statement's permissions are granted. You can also use placeholder variables when you specify conditions. For example, you can grant an IAM user permission to access a resource only if it is tagged with their IAM user name. For more information, see IAM policy elements: variables and tags in the IAM User Guide. AWS supports global condition keys and service-specific condition keys. To see all AWS global condition keys, see AWS global condition context keys in the IAM User Guide. To see a list of Systems Manager condition keys, see Condition Keys for AWS Systems Manager in the Service Authorization Reference. To learn with which actions and resources you can use a condition key, see Actions Defined by AWS Systems Manager. For information about using the ssm:resourceTag/* condition key, see the following topics: • Restricting access to root-level commands through SSM Agent • Restricting Run Command access based on tags • Restrict session access based on instance tags For information about using the ssm:Recursive, ssm:Policies, and ssm:Overwrite condition keys, see Preventing access to Parameter Store API operations. How AWS Systems Manager works with IAM 2414 AWS Systems Manager Examples User Guide To view examples of Systems Manager identity-based policies, see AWS Systems Manager identity- based policy examples. Systems Manager resource-based policies Other AWS services, such as Amazon Simple Storage Service (Amazon S3), support resource-based permissions policies. For example, you can attach a permissions policy to an S3 bucket to manage access permissions to that bucket. Systems Manager doesn't support resource-based policies. Authorization based on Systems Manager tags You can attach tags to Systems Manager resources or pass tags in a request to Systems Manager. To control access based on tags, you provide tag information in the condition element of a policy using the ssm:resourceTag/key-name, aws:ResourceTag/key-name, aws:RequestTag/key-name, or aws:TagKeys condition keys. You can add tags to the following resource types when you create or update them: • Document • Managed node • Maintenance window • Parameter • Patch baseline • OpsItem To view an example identity-based policy for limiting access to a resource based on the tags on that resource, see Viewing Systems Manager documents based on tags. Systems Manager IAM roles An IAM role is an entity within your AWS account that has specific permissions. How AWS Systems Manager works with IAM 2415 AWS Systems Manager User Guide Using temporary credentials with Systems Manager You can use temporary credentials to sign in with federation, assume an IAM role, or to assume a cross-account role. You obtain temporary security credentials by calling AWS Security Token Service (AWS STS) API operations such as AssumeRole or GetFederationToken. Systems Manager supports using temporary credentials. Service-linked roles Service-linked roles allow AWS services to access resources in other services to complete an action on your behalf. Service-linked roles are listed in your IAM account and are owned by the service. An administrator can view but not edit the permissions for service-linked roles. Systems Manager supports service-linked roles. For details about creating or managing Systems Manager service-linked roles, see Using service-linked roles for Systems Manager. Service roles This feature allows a service to assume a service role on your behalf. This role allows the service to access resources in other services to complete an action on your behalf. Service roles are displayed in your IAM account and are owned by the account. This means that an administrator can change the permissions for this role. However, doing so might break the functionality of the service. Systems Manager supports service roles. Choosing an IAM role in Systems Manager For Systems Manager to interact with your managed nodes, you must choose a role to allow Systems Manager to access nodes on your behalf. If you have previously created a service role or service-linked role, then Systems Manager provides you with a list of roles to choose from. It's important to choose a role that allows access to start and stop managed nodes. To access EC2 instances, you must configure instance permissions. For information, see Configure instance permissions required for Systems Manager. To access non-EC2 nodes in a hybrid and multicloud, the role your AWS account needs is an IAM service role. For information, see Create the IAM service role required for Systems Manager in hybrid and multicloud environments. An Automation workflow 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 execution. However, certain situations How AWS Systems Manager works with IAM 2416 AWS Systems Manager User Guide require that you specify a service role for Automation. For more information, see Configuring a service
systems-manager-ug-704
systems-manager-ug.pdf
704
account needs is an IAM service role. For information, see Create the IAM service role required for Systems Manager in hybrid and multicloud environments. An Automation workflow 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 execution. However, certain situations How AWS Systems Manager works with IAM 2416 AWS Systems Manager User Guide require that you specify a service role for Automation. For more information, see Configuring a service role (assume role) access for automations. AWS Systems Manager managed policies AWS addresses many common use cases by providing standalone IAM policies that are created and administered by AWS. These AWS managed policies grant necessary permissions for common use cases so you can avoid having to investigate which permissions are needed. (You can also create your own custom IAM policies to allow permissions for Systems Manager actions and resources.) For more information about managed policies for Systems Manager, see AWS managed policies for AWS Systems Manager For general information about managed policies, see AWS managed policies in the IAM User Guide. AWS Systems Manager identity-based policy examples By default, AWS Identity and Access Management (IAM) entities (users and roles) don't have permission to create or modify AWS Systems Manager resources. They also can't perform tasks using the Systems Manager console, AWS Command Line Interface (AWS CLI), or AWS API. An administrator must create IAM policies that grant users and roles permission to perform specific API operations on the specified resources they need. The administrator must then attach those policies to the users or groups that require those permissions. The following is an example of a permissions policy that allows a user to delete documents with names that begin with MyDocument- in the US East (Ohio) (us-east-2) AWS Region. { "Version": "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Action" : [ "ssm:DeleteDocument" ], "Resource" : [ "arn:aws:ssm:us-east-2:111122223333:document/MyDocument-*" ] } ] } Identity-based policy examples 2417 AWS Systems Manager User Guide To learn how to create an IAM identity-based policy using these example JSON Policy documents, see Creating IAM policies in the IAM User Guide. Topics • Policy best practices • Using the Systems Manager console • Allow users to view their own permissions • Cross-service confused deputy prevention • Customer managed policy examples • Viewing Systems Manager documents based on tags Policy best practices Identity-based policies determine whether someone can create, access, or delete Systems Manager resources in your account. These actions can incur costs for your AWS account. When you create or edit identity-based policies, follow these guidelines and recommendations: • Get started with AWS managed policies and move toward least-privilege permissions – To get started granting permissions to your users and workloads, use the AWS managed policies that grant permissions for many common use cases. They are available in your AWS account. We recommend that you reduce permissions further by defining AWS customer managed policies that are specific to your use cases. For more information, see AWS managed policies or AWS managed policies for job functions in the IAM User Guide. • Apply least-privilege permissions – When you set permissions with IAM policies, grant only the permissions required to perform a task. You do this by defining the actions that can be taken on specific resources under specific conditions, also known as least-privilege permissions. For more information about using IAM to apply permissions, see Policies and permissions in IAM in the IAM User Guide. • Use conditions in IAM policies to further restrict access – You can add a condition to your policies to limit access to actions and resources. For example, you can write a policy condition to specify that all requests must be sent using SSL. You can also use conditions to grant access to service actions if they are used through a specific AWS service, such as AWS CloudFormation. For more information, see IAM JSON policy elements: Condition in the IAM User Guide. • Use IAM Access Analyzer to validate your IAM policies to ensure secure and functional permissions – IAM Access Analyzer validates new and existing policies so that the policies Identity-based policy examples 2418 AWS Systems Manager User Guide adhere to the IAM policy language (JSON) and IAM best practices. IAM Access Analyzer provides more than 100 policy checks and actionable recommendations to help you author secure and functional policies. For more information, see Validate policies with IAM Access Analyzer in the IAM User Guide. • Require multi-factor authentication (MFA) – If you have a scenario that requires IAM users or a root user in your AWS account, turn on MFA for additional security. To require MFA when API operations are called, add
systems-manager-ug-705
systems-manager-ug.pdf
705
and existing policies so that the policies Identity-based policy examples 2418 AWS Systems Manager User Guide adhere to the IAM policy language (JSON) and IAM best practices. IAM Access Analyzer provides more than 100 policy checks and actionable recommendations to help you author secure and functional policies. For more information, see Validate policies with IAM Access Analyzer in the IAM User Guide. • Require multi-factor authentication (MFA) – If you have a scenario that requires IAM users or a root user in your AWS account, turn on MFA for additional security. To require MFA when API operations are called, add MFA conditions to your policies. For more information, see Secure API access with MFA in the IAM User Guide. For more information about best practices in IAM, see Security best practices in IAM in the IAM User Guide. Using the Systems Manager console To access the Systems Manager console, you must have a minimum set of permissions. These permissions must allow you to list and view details about the Systems Manager resources and other resources in your AWS account. If you create an identity-based policy that is more restrictive than the minimum required permissions, the console won't function as intended for IAM entities (users or roles) with that policy. You don't need to allow minimum console permissions for users that are making calls only to the AWS CLI or the AWS API. Instead, allow access to only the actions that match the API operation that you're trying to perform. To ensure that users and roles can still use the Systems Manager console, also attach the AmazonSSMFullAccess or AmazonSSMReadOnlyAccess AWS managed policy to the entities. For more information, see Adding permissions to a user in the IAM User Guide. Allow users to view their own permissions This example shows how you might create a policy that allows IAM users to view the inline and managed policies that are attached to their user identity. This policy includes permissions to complete this action on the console or programmatically using the AWS CLI or AWS API. { "Version": "2012-10-17", "Statement": [ { Identity-based policy examples 2419 AWS Systems Manager User Guide "Sid": "ViewOwnUserInfo", "Effect": "Allow", "Action": [ "iam:GetUserPolicy", "iam:ListGroupsForUser", "iam:ListAttachedUserPolicies", "iam:ListUserPolicies", "iam:GetUser" ], "Resource": ["arn:aws:iam::*:user/${aws:username}"] }, { "Sid": "NavigateInConsole", "Effect": "Allow", "Action": [ "iam:GetGroupPolicy", "iam:GetPolicyVersion", "iam:GetPolicy", "iam:ListAttachedGroupPolicies", "iam:ListGroupPolicies", "iam:ListPolicyVersions", "iam:ListPolicies", "iam:ListUsers" ], "Resource": "*" } ] } Cross-service confused deputy prevention 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 AWS Systems Manager gives Identity-based policy examples 2420 AWS Systems Manager User Guide another service to the resource. If the aws:SourceArn value does not contain the account ID, such as an Amazon Resource Name (ARN) for an S3 bucket, 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 following sections provide example policies for AWS Systems Manager tools. Hybrid activation policy example For service roles used in a hybrid activation, the value of aws:SourceArn must be the ARN of the AWS account. Be sure to specify the AWS Region in the ARN where you created your hybrid activation. 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:*:region:123456789012:*. The following example demonstrates using the aws:SourceArn and aws:SourceAccount global condition context keys for Automation to prevent the confused deputy problem in the US East (Ohio) Region (us-east-2). { "Version":"2012-10-17", "Statement":[ { "Sid":"", "Effect":"Allow", "Principal":{ "Service":"ssm.amazonaws.com" }, "Action":"sts:AssumeRole", "Condition":{ "StringEquals":{ "aws:SourceAccount":"123456789012" }, "ArnEquals":{ "aws:SourceArn":"arn:aws:ssm:us-east-2:123456789012:*" } } Identity-based policy examples 2421 AWS Systems Manager } ] } Resource data sync policy example User Guide
systems-manager-ug-706
systems-manager-ug.pdf
706
activation. 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:*:region:123456789012:*. The following example demonstrates using the aws:SourceArn and aws:SourceAccount global condition context keys for Automation to prevent the confused deputy problem in the US East (Ohio) Region (us-east-2). { "Version":"2012-10-17", "Statement":[ { "Sid":"", "Effect":"Allow", "Principal":{ "Service":"ssm.amazonaws.com" }, "Action":"sts:AssumeRole", "Condition":{ "StringEquals":{ "aws:SourceAccount":"123456789012" }, "ArnEquals":{ "aws:SourceArn":"arn:aws:ssm:us-east-2:123456789012:*" } } Identity-based policy examples 2421 AWS Systems Manager } ] } Resource data sync policy example User Guide Systems Manager Inventory, Explorer, and Compliance enable you to create a resource data sync to centralize storage of your operations data (OpsData) in a central Amazon Simple Storage Service bucket. If you want to encrypt a resource data sync by using AWS Key Management Service (AWS KMS), then you must either create a new key that includes the following policy, or you must update an existing key and add this policy to it. The aws:SourceArn and aws:SourceAccount condition keys in this policy prevent the confused deputy problem. Here is an example policy. { "Version": "2012-10-17", "Id": "ssm-access-policy", "Statement": [ { "Sid": "ssm-access-policy-statement", "Action": [ "kms:GenerateDataKey" ], "Effect": "Allow", "Principal": { "Service": "ssm.amazonaws.com" }, "Resource": "arn:aws:kms:us-east-2:123456789012:key/KMS_key_id", "Condition": { "StringLike": { "aws:SourceAccount": "123456789012" }, "ArnLike": { "aws:SourceArn": "arn:aws:ssm:*:123456789012:role/aws-service-role/ ssm.amazonaws.com/AWSServiceRoleForAmazonSSM" } } } ] } Identity-based policy examples 2422 AWS Systems Manager Note User Guide The ARN in the policy example enables the system to encrypt OpsData from all sources except AWS Security Hub. If you need to encrypt Security Hub data, for example if you use Explorer to collect Security Hub data, then you must attach an additional policy that specifies the following ARN: "aws:SourceArn": "arn:aws:ssm:*:account-id:role/ aws-service-role/opsdatasync.ssm.amazonaws.com/ AWSServiceRoleForSystemsManagerOpsDataSync" Customer managed policy examples You can create standalone policies that you administer in your own AWS account. We refer to these as customer managed policies. You can attach these policies to multiple principal entities in your AWS account. When you attach a policy to a principal entity, you give the entity the permissions that are defined in the policy. For more information, see Customer managed policy examples in the IAM User Guide. The following examples of user policies grant permissions for various Systems Manager actions. Use them to limit the Systems Manager access for your IAM entities (users and roles). These policies work when performing actions in the Systems Manager API, AWS SDKs, or the AWS CLI. For users who use the console, you need to grant additional permissions specific to the console. For more information, see Using the Systems Manager console. Note All examples use the US West (Oregon) Region (us-west-2) and contain fictitious account IDs. The account ID shouldn't be specified in the Amazon Resource Name (ARN) for AWS public documents (documents that begin with AWS-*). Examples • Example 1: Allow a user to perform Systems Manager operations in a single Region • Example 2: Allow a user to list documents for a single Region Identity-based policy examples 2423 AWS Systems Manager User Guide Example 1: Allow a user to perform Systems Manager operations in a single Region The following example grants permissions to perform Systems Manager operations only in the US East (Ohio) Region (us-east-2). { "Version": "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Action" : [ "ssm:*" ], "Resource" : [ "arn:aws:ssm:us-east-2:aws-account-ID:*" ] } ] } Example 2: Allow a user to list documents for a single Region The following example grants permissions to list all document names that begin with Update in the US East (Ohio) Region (us-east-2). { "Version": "2012-10-17", "Statement" : [ { "Effect" : "Allow", "Action" : [ "ssm:ListDocuments" ], "Resource" : [ "arn:aws:ssm:us-east-2:aws-account-ID:document/Update*" ] } ] } Identity-based policy examples 2424 AWS Systems Manager User Guide Example 3: Allow a user to use a specific SSM document to run commands on specific nodes The following example IAM policy allows a user to do the following in the US East (Ohio) Region (us-east-2): • List Systems Manager documents (SSM documents) and document versions. • View details about documents. • Send a command using the document specified in the policy. The name of the document is determined by the following entry. arn:aws:ssm:us-east-2:aws-account-ID:document/Systems-Manager-document-name • Send a command to three nodes. The nodes are determined by the following entries in the second Resource section. "arn:aws:ec2:us-east-2:aws-account-ID:instance/i-02573cafcfEXAMPLE", "arn:aws:ec2:us-east-2:aws-account-ID:instance/i-0471e04240EXAMPLE", "arn:aws:ec2:us-east-2:aws-account-ID:instance/i-07782c72faEXAMPLE" • View details about a command after it has been sent. • Start and stop workflows in Automation, a tool in AWS Systems Manager. • Get information about Automation workflows. If you want to give a user permission to use this document to send commands on any node for which the user has access, you could specify an entry similar to the following in the Resource section and remove the other
systems-manager-ug-707
systems-manager-ug.pdf
707
determined by the following entry. arn:aws:ssm:us-east-2:aws-account-ID:document/Systems-Manager-document-name • Send a command to three nodes. The nodes are determined by the following entries in the second Resource section. "arn:aws:ec2:us-east-2:aws-account-ID:instance/i-02573cafcfEXAMPLE", "arn:aws:ec2:us-east-2:aws-account-ID:instance/i-0471e04240EXAMPLE", "arn:aws:ec2:us-east-2:aws-account-ID:instance/i-07782c72faEXAMPLE" • View details about a command after it has been sent. • Start and stop workflows in Automation, a tool in AWS Systems Manager. • Get information about Automation workflows. If you want to give a user permission to use this document to send commands on any node for which the user has access, you could specify an entry similar to the following in the Resource section and remove the other node entries. The following example uses the US East (Ohio) Region (us-east-2). "arn:aws:ec2:us-east-2:*:instance/*" { "Version": "2012-10-17", "Statement": [ { "Action": [ "ssm:ListDocuments", "ssm:ListDocumentVersions", "ssm:DescribeDocument", "ssm:GetDocument", Identity-based policy examples 2425 AWS Systems Manager User Guide "ssm:DescribeInstanceInformation", "ssm:DescribeDocumentParameters", "ssm:DescribeInstanceProperties" ], "Effect": "Allow", "Resource": "*" }, { "Action": "ssm:SendCommand", "Effect": "Allow", "Resource": [ "arn:aws:ec2:us-east-2:aws-account-ID:instance/i-02573cafcfEXAMPLE", "arn:aws:ec2:us-east-2:aws-account-ID:instance/i-0471e04240EXAMPLE", "arn:aws:ec2:us-east-2:aws-account-ID:instance/i-07782c72faEXAMPLE", "arn:aws:ssm:us-east-2:aws-account-ID:document/Systems-Manager- document-name" ] }, { "Action": [ "ssm:CancelCommand", "ssm:ListCommands", "ssm:ListCommandInvocations" ], "Effect": "Allow", "Resource": "*" }, { "Action": "ec2:DescribeInstanceStatus", "Effect": "Allow", "Resource": "*" }, { "Action": "ssm:StartAutomationExecution", "Effect": "Allow", "Resource": [ "arn:aws:ssm:us-east-2:aws-account-ID:automation-definition/*" ] }, { "Action": "ssm:DescribeAutomationExecutions", "Effect": "Allow", "Resource": [ Identity-based policy examples 2426 User Guide AWS Systems Manager "*" ] }, { "Action": [ "ssm:StopAutomationExecution", "ssm:GetAutomationExecution" ], "Effect": "Allow", "Resource": [ "*" ] } ] } Viewing Systems Manager documents based on tags You can use conditions in your identity-based policy to control access to Systems Manager resources based on tags. This example shows how you might create a policy that allows viewing an SSM document. However, permission is granted only if the document tag Owner has the value of that user's user name. This policy also grants the permissions necessary to complete this action on the console. { "Version": "2012-10-17", "Statement": [ { "Sid": "ListDocumentsInConsole", "Effect": "Allow", "Action": "ssm:ListDocuments", "Resource": "*" }, { "Sid": "ViewDocumentIfOwner", "Effect": "Allow", "Action": "ssm:GetDocument", "Resource": "arn:aws:ssm:*:*:document/*", "Condition": { "StringEquals": {"ssm:ResourceTag/Owner": "${aws:username}"} } } ] Identity-based policy examples 2427 AWS Systems Manager } User Guide You can attach this policy to the users in your account. If a user named richard-roe attempts to view an Systems Manager document, the document must be tagged Owner=richard-roe or owner=richard-roe. Otherwise they're denied access. The condition tag key Owner matches both Owner and owner because condition key names aren't case-sensitive. For more information, see IAM JSON policy elements: Condition in the IAM User Guide. AWS managed policies for AWS Systems Manager An AWS managed policy is a standalone policy that is created and administered by AWS. AWS managed policies are designed to provide permissions for many common use cases so that you can start assigning permissions to users, groups, and roles. Keep in mind that AWS managed policies might not grant least-privilege permissions for your specific use cases because they're available for all AWS customers to use. We recommend that you reduce permissions further by defining customer managed policies that are specific to your use cases. You cannot change the permissions defined in AWS managed policies. If AWS updates the permissions defined in an AWS managed policy, the update affects all principal identities (users, groups, and roles) that the policy is attached to. AWS is most likely to update an AWS managed policy when a new AWS service is launched or new API operations become available for existing services. For more information, see AWS managed policies in the IAM User Guide. AWS managed policy: AmazonSSMServiceRolePolicy This policy provides access to a number of AWS resources that are managed by AWS Systems Manager or used in Systems Manager operations. You can't attach AmazonSSMServiceRolePolicy to your AWS Identity and Access Management (IAM) entities. This policy is attached to a service-linked role that allows AWS Systems Manager to perform actions on your behalf. For more information, see Using roles to collect inventory and view OpsData. AWS managed policies 2428 AWS Systems Manager Permissions details This policy includes the following permissions. User Guide • ssm – Allows principals to start and step executions for both Run Command and Automation; and to retrieve information about Run Command and Automation operations; to retrieve information about Parameter Store parameters Change Calendar calendars; to update and retrieve information about Systems Manager service settings for OpsCenterresources; and to read information about tags that have have applied to resources. • cloudformation – Allows principals to retrieve information about stackset operations and stackset instances, and to delete stacksets on the resource arn:aws:cloudformation:*:*:stackset/AWS-QuickSetup-SSM*:*. Allows principals to delete stack instances that are associated with the following resources: arn:aws:cloudformation:*:*:stackset/AWS-QuickSetup-SSM*:* arn:aws:cloudformation:*:*:stackset-target/AWS-QuickSetup-SSM*:* arn:aws:cloudformation:*:*:type/resource/* • cloudwatch – Allows principals to retrieve information about Amazon CloudWatch alarms. • compute-optimizer – Allows principals to retrieve the enrollment (opt in) status of an account to the AWS Compute Optimizer service, and to retrieve recommendations for Amazon EC2 instances that meet a specific set of
systems-manager-ug-708
systems-manager-ug.pdf
708
settings for OpsCenterresources; and to read information about tags that have have applied to resources. • cloudformation – Allows principals to retrieve information about stackset operations and stackset instances, and to delete stacksets on the resource arn:aws:cloudformation:*:*:stackset/AWS-QuickSetup-SSM*:*. Allows principals to delete stack instances that are associated with the following resources: arn:aws:cloudformation:*:*:stackset/AWS-QuickSetup-SSM*:* arn:aws:cloudformation:*:*:stackset-target/AWS-QuickSetup-SSM*:* arn:aws:cloudformation:*:*:type/resource/* • cloudwatch – Allows principals to retrieve information about Amazon CloudWatch alarms. • compute-optimizer – Allows principals to retrieve the enrollment (opt in) status of an account to the AWS Compute Optimizer service, and to retrieve recommendations for Amazon EC2 instances that meet a specific set of stated requirements. • config – Allows principals to retrieve information remediation configurations and configuration recorders in AWS Config, and to determine whether specified AWS Config rules and AWS resources are compliant. • events – Allows principals retrieve information about EventBridge rules; to create EventBridge rules and targets exclusively for the the Systems Manager service (ssm.amazonaws.com); and to delete rules and targets for the resource arn:aws:events:*:*:rule/ SSMExplorerManagedRule. • ec2 – Allows principals to retrieve information about Amazon EC2 instances.. • iam – Allows principals to pass roles permissions for the Systems Manager service (ssm.amazonaws.com). • lambda – Allows principals to invoke Lambda functions that are configured specifically for use by Systems Manager. • resource-explorer-2 – Allows principals to retrieve data about EC2 instances to determine whether or not each instance is currently managed by Systems Manager. AWS managed policies 2429 AWS Systems Manager User Guide The action resource-explorer-2:CreateManagedView is allowed for the arn:aws:resource-explorer-2:*:*:managed-view/AWSManagedViewForSSM* resource. • resource-groups – Allows principals to retrieve list resource groups and their members from AWS Resource Groups of resources that belong to a resource group. • securityhub – Allows principals to retrieve information about AWS Security Hub hub resources in the current account. • states – Allows principals to start and retrieve information for AWS Step Functions that are configured specifically for use by Systems Manager. • support – Allows principals to retrieve information about checks and cases in AWS Trusted Advisor. • tag – Allows principals to retrieve information about all the tagged or previously tagged resources that are located in a specified AWS Region for an account. To view more details about the policy, including the latest version of the JSON policy document, see AmazonSSMServiceRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AmazonSSMReadOnlyAccess You can attach the AmazonSSMReadOnlyAccess policy to your IAM identities. This policy grants read-only access to AWS Systems Manager API operations including Describe*, Get*, and List*. To view more details about the policy, including the latest version of the JSON policy document, see AmazonSSMReadOnlyAccess in the AWS Managed Policy Reference Guide. AWS managed policy: AWSSystemsManagerOpsDataSyncServiceRolePolicy You can't attach AWSSystemsManagerOpsDataSyncServiceRolePolicy to your IAM entities. This policy is attached to a service-linked role that allows Systems Manager to perform actions on your behalf. For more information, see Using roles to create OpsData and OpsItems for Explorer. AWSSystemsManagerOpsDataSyncServiceRolePolicy allows the AWSServiceRoleForSystemsManagerOpsDataSync service-linked role to create and update OpsItems and OpsData from AWS Security Hub findings. The policy allows Systems Manager to complete the following actions on all related resources ("Resource": "*"), except where indicated: • ssm:GetOpsItem [1] AWS managed policies 2430 User Guide AWS Systems Manager • ssm:UpdateOpsItem [1] • ssm:CreateOpsItem • ssm:AddTagsToResource [2] • ssm:UpdateServiceSetting [3] • ssm:GetServiceSetting [3] • securityhub:GetFindings • securityhub:GetFindings • securityhub:BatchUpdateFindings [4] [1] The ssm:GetOpsItem and ssm:UpdateOpsItem actions are allowed permissions by the following condition for the Systems Manager service only. "Condition": { "StringEquals": { "aws:ResourceTag/ExplorerSecurityHubOpsItem": "true" } } [2] The ssm:AddTagsToResource action is allowed permissions for the following resource only. arn:aws:ssm:*:*:opsitem/* [3] The ssm:UpdateServiceSetting and ssm:GetServiceSetting actions are allowed permissions for the following resources only. arn:aws:ssm:*:*:servicesetting/ssm/opsitem/* arn:aws:ssm:*:*:servicesetting/ssm/opsdata/* [4] The securityhub:BatchUpdateFindings are denied permissions by the following condition for the Systems Manager service only. { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "StringEquals": { "securityhub:ASFFSyntaxPath/Workflow.Status": "SUPPRESSED" AWS managed policies 2431 AWS Systems Manager User Guide } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/Confidence": false } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/Criticality": false } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/Note.Text": false } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/Note.UpdatedBy": false } } }, { AWS managed policies 2432 User Guide AWS Systems Manager "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/RelatedFindings": false } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/Types": false } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/UserDefinedFields.key": false } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/UserDefinedFields.value": false } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { AWS managed
systems-manager-ug-709
systems-manager-ug.pdf
709
{ "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/Note.UpdatedBy": false } } }, { AWS managed policies 2432 User Guide AWS Systems Manager "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/RelatedFindings": false } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/Types": false } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/UserDefinedFields.key": false } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { "Null": { "securityhub:ASFFSyntaxPath/UserDefinedFields.value": false } } }, { "Effect": "Deny", "Action": "securityhub:BatchUpdateFindings", "Resource": "*", "Condition": { AWS managed policies 2433 AWS Systems Manager "Null": { "securityhub:ASFFSyntaxPath/VerificationState": false } } User Guide To view more details about the policy, including the latest version of the JSON policy document, see AWSSystemsManagerOpsDataSyncServiceRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AmazonSSMManagedEC2InstanceDefaultPolicy You should only attach AmazonSSMManagedEC2InstanceDefaultPolicy to IAM roles for Amazon EC2 instances that you want to have permission to use Systems Manager functionality. You shouldn't attached this role to other IAM entities, such as IAM users and IAM groups, or to IAM roles that serve other purposes. For more information, see Managing EC2 instances automatically with Default Host Management Configuration. This policy grants permissions that allow SSM Agent on your Amazon EC2 instance to communicate with the Systems Manager service in the cloud in order to perform a variety of tasks. It also grants permissions for the two services that provide authorization tokens to ensure that operations are performed on the correct instance. Permissions details This policy includes the following permissions. • ssm – Allows principals to retrieve Documents, execute commands using Run Command, establish sessions using Session Manager, collect an inventory of the instance, and scan for patches and patch compliance using Patch Manager. • ssmmessages – Allows principals to access, for each instance, a personalized authorization token that was created by the Amazon Message Gateway Service. Systems Manager validates the personalized authorization token against the Amazon Resource Name (ARN) of the instance that was provided in the API operation. This access is necessary to ensure that SSM Agent performs the API operations on the correct instance. • ec2messages – Allows principals to access, for each instance, a personalized authorization token that was created by the Amazon Message Delivery Service. Systems Manager validates the personalized authorization token against the Amazon Resource Name (ARN) of the instance that was provided in the API operation. This access is necessary to ensure that SSM Agent performs the API operations on the correct instance. AWS managed policies 2434 AWS Systems Manager User Guide For related information about the ssmmessages and ec2messages endpoints, including the differences between the two, see Agent-related API operations (ssmmessages and ec2messages endpoints). To view more details about the policy, including the latest version of the JSON policy document, see AmazonSSMManagedEC2InstanceDefaultPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: SSMQuickSetupRolePolicy You can't attach SSMQuickSetupRolePolicy to your IAM entities. This policy is attached to a service- linked role that allows Systems Manager to perform actions on your behalf. For more information, see Using roles to maintain Quick Setup-provisioned resource health and consistency. This policy grants read-only permissions that allow Systems Manager to check configuration health, ensure consistent use of parameters and provisioned resources, and remediate resources when drift is detected. It also grants administrative permissions for creating a service-linked role. Permissions details This policy includes the following permissions. • ssm – Allows principals to read information Resource Data Syncs and SSM Documents in Systems Manager, including in delegated administrator accounts. This is required so Quick Setup can determine the state that configured resources are intended to be in. • organizations – Allows principals to read information about the member accounts that belong to an organization as configured in AWS Organizations. This is required so Quick Setup can identify all accounts in an organization where resource health checks are to be performed. • cloudformation – Allows principals to read information from AWS CloudFormation. This is required so Quick Setup can gather data about the AWS CloudFormation stacks used to manage the state of resources and CloudFormation stackset operations. To view more details about the policy, including the latest version of the JSON policy document, see SSMQuickSetupRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupDeploymentRolePolicy The managed policy AWSQuickSetupDeploymentRolePolicy supports multiple Quick Setup configuration types. These configuration types create IAM roles and automations that configure frequently used Amazon Web Services services and features with recommended best practices. AWS managed policies 2435 AWS Systems Manager User Guide You can attach AWSQuickSetupDeploymentRolePolicy to your IAM entities. This policy grants administrative permissions needed to create resources associated with the following Quick Setup configurations: • Set up Amazon EC2 host management using Quick Setup • Create an AWS Config configuration
systems-manager-ug-710
systems-manager-ug.pdf
710
version of the JSON policy document, see SSMQuickSetupRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupDeploymentRolePolicy The managed policy AWSQuickSetupDeploymentRolePolicy supports multiple Quick Setup configuration types. These configuration types create IAM roles and automations that configure frequently used Amazon Web Services services and features with recommended best practices. AWS managed policies 2435 AWS Systems Manager User Guide You can attach AWSQuickSetupDeploymentRolePolicy to your IAM entities. This policy grants administrative permissions needed to create resources associated with the following Quick Setup configurations: • Set up Amazon EC2 host management using Quick Setup • Create an AWS Config configuration recorder using Quick Setup • Deploy AWS Config conformance pack using Quick Setup • Set up DevOps Guru using Quick Setup • Deploy Distributor packages using Quick Setup • Stop and start EC2 instances automatically on a schedule using Quick Setup Permissions details This policy includes the following permissions. • iam – Allows principals to manage and delete IAM roles required for Automation configuration tasks; and to manage Automation role policies. • cloudformation – Allows principals to create and manage stack sets. • config – Allows principals to create, manage, and delete conformance packs. • events – Allows principals to create, update, and delete event rules for scheduled actions. • resource-groups – Allows principals to retrieve resource queries that are associated with resource groups targeted by Quick Setup configurations. • ssm – Allows principals to create Automation runbooks and associations that apply Quick Setup configurations. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupDeploymentRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupPatchPolicyDeploymentRolePolicy The managed policy AWSQuickSetupPatchPolicyDeploymentRolePolicy supports the Configure patching for instances in an organization using a Quick Setup patch policy Quick Setup type. This configuration type helps automate patching of applications and nodes in a single account or across your organization. AWS managed policies 2436 AWS Systems Manager User Guide You can attach AWSQuickSetupPatchPolicyDeploymentRolePolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. This policy grants administrative permissions that allow Quick Setup to create resources associated with a patch policy configuration. Permissions details This policy includes the following permissions. • iam – Allows principals to manage and delete IAM roles required for Automation configuration tasks; and to manage Automation role policies. • cloudformation – Allows principals to read AWS CloudFormation stack information; and to control AWS CloudFormation stacks that were created by Quick Setup using AWS CloudFormation stack sets. • ssm – Allows principals to create, update, read, and delete Automation runbooks required for configuration tasks; and to create, update, and delete State Manager associations. • resource-groups – Allows principals to retrieve resource queries that are associated with resource groups targeted by Quick Setup configurations. • s3 – Allows principals to list Amazon S3 buckets; and to manage the buckets for storing patch policy access logs. • lambda – Allows principals to manage AWS Lambda remediation functions that maintain configurations in the correct state. • logs – Allows principals to describe and manage log groups for Lambda configuration resources. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupPatchPolicyDeploymentRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupPatchPolicyBaselineAccess The managed policy AWSQuickSetupPatchPolicyBaselineAccess supports the Configure patching for instances in an organization using a Quick Setup patch policy Quick Setup type. This configuration type helps automate patching of applications and nodes in a single account or across your organization. AWS managed policies 2437 AWS Systems Manager User Guide You can attach AWSQuickSetupPatchPolicyBaselineAccess to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. This policy provides read-only permissions to access patch baselines that have been configured by an administrator in the current AWS account or organization using Quick Setup. The patch baselines are stored in an Amazon S3 bucket and can be used for patching instances in a single account or across an entire organization. Permissions details This policy includes the following permission. • s3 – Allows principals to read patch baseline overrides stored in Amazon S3 buckets. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupPatchPolicyBaselineAccess in the AWS Managed Policy Reference Guide. AWS managed policy: AWSSystemsManagerEnableExplorerExecutionPolicy The managed policy AWSSystemsManagerEnableExplorerExecutionPolicy supports enabling Explorer, a tool in AWS Systems Manager. You can attach AWSSystemsManagerEnableExplorerExecutionPolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. This policy grants administrative permissions for enabling Explorer. This includes permissions to update related Systems Manager service settings, and to create a
systems-manager-ug-711
systems-manager-ug.pdf
711
patch baseline overrides stored in Amazon S3 buckets. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupPatchPolicyBaselineAccess in the AWS Managed Policy Reference Guide. AWS managed policy: AWSSystemsManagerEnableExplorerExecutionPolicy The managed policy AWSSystemsManagerEnableExplorerExecutionPolicy supports enabling Explorer, a tool in AWS Systems Manager. You can attach AWSSystemsManagerEnableExplorerExecutionPolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. This policy grants administrative permissions for enabling Explorer. This includes permissions to update related Systems Manager service settings, and to create a service-linked role for Systems Manager. Permissions details This policy includes the following permissions. • config – Allows principals to help enable Explorer by providing read-only access to configuration recorder details. • iam – Allows principals to help enable Explorer. • ssm – Allows principals to start an Automation workflow that enables Explorer. AWS managed policies 2438 AWS Systems Manager User Guide To view more details about the policy, including the latest version of the JSON policy document, see AWSSystemsManagerEnableExplorerExecutionPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSSystemsManagerEnableConfigRecordingExecutionPolicy The managed policy AWSSystemsManagerEnableConfigRecordingExecutionPolicy supports the Create an AWS Config configuration recorder using Quick Setup Quick Setup configuration type. This configuration type enables Quick Setup to track and record changes to the AWS resource types you choose for AWS Config. It also enables Quick Setup to configure delivery and notifications options for the recorded data. You can attach AWSSystemsManagerEnableConfigRecordingExecutionPolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. This policy grants administrative permissions that allow Quick Setup to enable and configure AWS Config configuration recording. Permissions details This policy includes the following permissions. • s3 – Allows principals to create and configure Amazon S3 buckets for delivery of configuration recordings. • sns – Allows principals to list and create Amazon SNS topics. • config – Allows principals to configure and start the configuration recorder; and to help enable Explorer. • iam – Allows principals to create, get, and pass a service-linked role for AWS Config; and to create a service-linked role for Systems Manager; and to help enable Explorer. • ssm – Allows principals to start an Automation workflow that enables Explorer. • compute-optimizer – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. • support – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. AWS managed policies 2439 AWS Systems Manager User Guide To view more details about the policy, including the latest version of the JSON policy document, see AWSSystemsManagerEnableConfigRecordingExecutionPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupDevOpsGuruPermissionsBoundary Note This policy is a permissions boundary. A permissions boundary sets the maximum permissions that an identity-based policy can grant to an IAM entity. You should not use and attach Quick Setup permissions boundary policies on your own. Quick Setup permissions boundary policies should only be attached to Quick Setup managed roles. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. The managed policy AWSQuickSetupDevOpsGuruPermissionsBoundary supports the Set up DevOps Guru using Quick Setup type. The configuration type enables the machine learning- powered Amazon DevOps Guru. The DevOps Guru service can help improve an application’s operational performance and availability. When you create an AWSQuickSetupDevOpsGuruPermissionsBoundary configuration using Quick Setup, the system applies this permissions boundary to the IAM roles that are created when the configuration is deployed. The permissions boundary limits the scope of the roles that Quick Setup creates. This policy grants administrative permissions that allow Quick Setup to enable and configure Amazon DevOps Guru. Permissions details This policy includes the following permissions. • iam – Allows principals to create service-linked roles for DevOps Guru and Systems Manager; and to list roles that help enable Explorer. • cloudformation – Allows principals to list and describe AWS CloudFormation stacks. • sns – Allows principals to list and create Amazon SNS topics. • devops-guru – Allows principals to configure DevOps Guru; and to add a notification channel. AWS managed policies 2440 AWS Systems Manager User Guide • config – – Allows principals to help enable Explorer by providing read-only access to configuration recorder details. • ssm – Allows principals to start an Automation workflow that enables Explorer; and to read and update Explorer service settings. • compute-optimizer – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. • support – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS
systems-manager-ug-712
systems-manager-ug.pdf
712
and to add a notification channel. AWS managed policies 2440 AWS Systems Manager User Guide • config – – Allows principals to help enable Explorer by providing read-only access to configuration recorder details. • ssm – Allows principals to start an Automation workflow that enables Explorer; and to read and update Explorer service settings. • compute-optimizer – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. • support – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupDevOpsGuruPermissionsBoundary in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupDistributorPermissionsBoundary Note This policy is a permissions boundary. A permissions boundary sets the maximum permissions that an identity-based policy can grant to an IAM entity. You should not use and attach Quick Setup permissions boundary policies on your own. Quick Setup permissions boundary policies should only be attached to Quick Setup managed roles. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. The managed policy AWSQuickSetupDistributorPermissionsBoundary supports the Deploy Distributor packages using Quick Setup Quick Setup configuration type. The configuration type helps enable the distribution of software packages, such as agents, to your Amazon Elastic Compute Cloud (Amazon EC2) instances, using Distributor, a tool in AWS Systems Manager. When you create an AWSQuickSetupDistributorPermissionsBoundary configuration using Quick Setup, the system applies this permissions boundary to the IAM roles that are created when the configuration is deployed. The permissions boundary limits the scope of the roles that Quick Setup creates. This policy grants administrative permissions that allow Quick Setup to enable the distribution of software packages, such as agents, to your Amazon EC2 instances using Distributor. Permissions details AWS managed policies 2441 AWS Systems Manager User Guide This policy includes the following permissions. • iam – Allows principals to get and pass the Distributor automation role; to create, read, update, and delete the default instance role; to pass the default instance role to Amazon EC2 and Systems Manager; to attach instance management policies to instance roles; to create a service- linked role for Systems Manager; to add the default instance role to instance profiles; to read information about IAM roles and instance profiles; and to create the default instance profile. • ec2 – Allows principals to associate the default instance profile with EC2 instances; and to help enable Explorer. • ssm – Allows principals to start automation workflows that which configure instances and install packages; and to help start the automation workflow that enables Explorer; and to read and update Explorer service settings. • config – Allows principals to help enable Explorer by providing read-only access to configuration recorder details. • compute-optimizer – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. • support – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupDistributorPermissionsBoundary in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupSSMHostMgmtPermissionsBoundary Note This policy is a permissions boundary. A permissions boundary sets the maximum permissions that an identity-based policy can grant to an IAM entity. You should not use and attach Quick Setup permissions boundary policies on your own. Quick Setup permissions boundary policies should only be attached to Quick Setup managed roles. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. The managed policy AWSQuickSetupSSMHostMgmtPermissionsBoundary supports the Set up Amazon EC2 host management using Quick Setup Quick Setup configuration type. This AWS managed policies 2442 AWS Systems Manager User Guide configuration type configures IAM roles and enables commonly used Systems Manager tools to securely manage your Amazon EC2 instances. When you create an AWSQuickSetupSSMHostMgmtPermissionsBoundary configuration using Quick Setup, the system applies this permissions boundary to the IAM roles that are created when the configuration is deployed. The permissions boundary limits the scope of the roles that Quick Setup creates. This policy grants administrative permissions that allow Quick Setup to enable and configure Systems Manager tools needed for securely managing EC2 instances. Permissions details This policy includes the following permissions. • iam – Allows principals to get and pass the service role to Automation. Allows principals to create, read, update, and delete the default instance role; to pass the default instance role to Amazon EC2 and Systems Manager; to attach instance management policies to instance roles; to create a service-linked role for Systems Manager; to add the default instance role
systems-manager-ug-713
systems-manager-ug.pdf
713
limits the scope of the roles that Quick Setup creates. This policy grants administrative permissions that allow Quick Setup to enable and configure Systems Manager tools needed for securely managing EC2 instances. Permissions details This policy includes the following permissions. • iam – Allows principals to get and pass the service role to Automation. Allows principals to create, read, update, and delete the default instance role; to pass the default instance role to Amazon EC2 and Systems Manager; to attach instance management policies to instance roles; to create a service-linked role for Systems Manager; to add the default instance role to instance profiles; to read information about IAM roles and instance profiles; and to create the default instance profile. • ec2 – Allows principals to associate and disassociate the default instance profile with EC2 instances. • ssm – Allows principals to start Automation workflows that enable Explorer; to read and update Explorer service settings; to configure instances; and to enable Systems Manager tools on instances. • compute-optimizer – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. • support – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupSSMHostMgmtPermissionsBoundary in the AWS Managed Policy Reference Guide. AWS managed policies 2443 AWS Systems Manager User Guide AWS managed policy: AWSQuickSetupPatchPolicyPermissionsBoundary Note This policy is a permissions boundary. A permissions boundary sets the maximum permissions that an identity-based policy can grant to an IAM entity. You should not use and attach Quick Setup permissions boundary policies on your own. Quick Setup permissions boundary policies should only be attached to Quick Setup managed roles. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. The managed policy AWSQuickSetupPatchPolicyPermissionsBoundary supports the Configure patching for instances in an organization using a Quick Setup patch policy Quick Setup type. This configuration type helps automate patching of applications and nodes in a single account or across your organization. When you create an AWSQuickSetupPatchPolicyPermissionsBoundary configuration using Quick Setup, the system applies this permissions boundary to the IAM roles that are created when the configuration is deployed. The permissions boundary limits the scope of the roles that Quick Setup creates. This policy grants administrative permissions that allow Quick Setup to enable and configure patch policies in Patch Manager, a tool in AWS Systems Manager. Permissions details This policy includes the following permissions. • iam – Allows principals to get the Patch Manager Automation role; to pass Automation roles to Patch Manager patching operations; to create the default instance role, AmazonSSMRoleForInstancesQuickSetup; to pass the default instance role to Amazon EC2 and Systems Manager; to attach selected AWS managed policies to the instance role; to create a service-linked role for Systems Manager; to add the default instance role to instance profiles; to read information about instance profiles and roles; to create a default instance profile; and to tag roles that have permissions to read patch baseline overrides. • ssm – Allows principals to update the instance role this is managed by Systems Manager; to manage associations created by Patch Manager patch policies created in Quick Setup; to tag instances targeted by a patch policy configuration; to read information about instances and AWS managed policies 2444 AWS Systems Manager User Guide patching status; to start Automation workflows that configure, enable and remediate instance patching; to start automation workflows that enable Explorer; to help enable Explorer; and to read and update Explorer service settings. • ec2 – Allows principals to associate and disassociate the default instance profile with EC2 instances; to tag instances targeted by a patch policy configuration; to tag instances targeted by a patch policy configuration; and to help enable Explorer. • s3 – Allows principals to create and configure S3 buckets to store patch baseline overrides. • lambda – Allows principals to invoke AWS Lambda functions that configure patching and to perform clean-up operations after a Quick Setup patch policy configuration is deleted. • logs – Allows principals to configure logging for Patch Manager Quick Setup AWS Lambda functions. • config – Allows principals to help enable Explorer by providing read-only access to configuration recorder details. • compute-optimizer – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. • support – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupPatchPolicyPermissionsBoundary in the AWS Managed Policy Reference Guide. AWS managed
systems-manager-ug-714
systems-manager-ug.pdf
714
for Patch Manager Quick Setup AWS Lambda functions. • config – Allows principals to help enable Explorer by providing read-only access to configuration recorder details. • compute-optimizer – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. • support – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupPatchPolicyPermissionsBoundary in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupSchedulerPermissionsBoundary Note This policy is a permissions boundary. A permissions boundary sets the maximum permissions that an identity-based policy can grant to an IAM entity. You should not use and attach Quick Setup permissions boundary policies on your own. Quick Setup permissions boundary policies should only be attached to Quick Setup managed roles. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. The managed policy AWSQuickSetupSchedulerPermissionsBoundary supports the Stop and start EC2 instances automatically on a schedule using Quick Setup Quick Setup configuration type. AWS managed policies 2445 AWS Systems Manager User Guide This configuration type lets you stop and start your EC2 instances and other resources at the times you specify. When you create an AWSQuickSetupSchedulerPermissionsBoundary configuration using Quick Setup, the system applies this permissions boundary to the IAM roles that are created when the configuration is deployed. The permissions boundary limits the scope of the roles that Quick Setup creates. This policy grants administrative permissions that allow Quick Setup to enable and configure scheduled operations on EC2 instances and other resources. Permissions details This policy includes the following permissions. • iam – Allows principals to retrieve and pass roles for instance management automation actions; to manage, pass, and attach default instance roles for EC2 instance management; to create default instance profiles; to add default instance roles to instance profiles; to create a service- linked role for Systems Manager; to read information about IAM roles and instance profiles; to associate a default instance profile with EC2 instances; and to start Automation workflows to configure instances and enable Systems Manager tools on them. • ssm – Allows principals to start Automation workflows that enable Explorer; and to read and update Explorer service settings. • ec2 – Allows principals to locate targeted instances and to start and stop them on a schedule. • config – Allows principals to help enable Explorer by providing read-only access to configuration recorder details. • compute-optimizer – Allows principals to help enable Explorer by providing read-only access to determine whether a resource is enrolled with AWS Compute Optimizer. • support – Allows principals to help enable Explorer by providing read-only access to AWS Trusted Advisor checks for an account. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupSchedulerPermissionsBoundary in the AWS Managed Policy Reference Guide. AWS managed policies 2446 AWS Systems Manager User Guide AWS managed policy: AWSQuickSetupCFGCPacksPermissionsBoundary Note This policy is a permissions boundary. A permissions boundary sets the maximum permissions that an identity-based policy can grant to an IAM entity. You should not use and attach Quick Setup permissions boundary policies on your own. Quick Setup permissions boundary policies should only be attached to Quick Setup managed roles. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. The managed policy AWSQuickSetupCFGCPacksPermissionsBoundarysupports the Deploy AWS Config conformance pack using Quick Setup Quick Setup configuration type. This configuration type deploys AWS Config conformance packs. Conformance packs are collections of AWS Config rules and remediation actions that can be deployed as a single entity. When you create an AWSQuickSetupCFGCPacksPermissionsBoundary configuration using Quick Setup, the system applies this permissions boundary to the IAM roles that are created when the configuration is deployed. The permissions boundary limits the scope of the roles that Quick Setup creates. This policy grants administrative permissions that allow Quick Setup to deploy AWS Config conformance packs. Permissions details This policy includes the following permissions. • iam – Allows principals to create, get, and pass a service-linked role for AWS Config. • sns – Allows principals to list platform applications in Amazon SNS. • config – Allows principals to deploy AWS Config conformance packs; to get the status of conformance packs; and to get information about configuration recorders. • ssm – Allows principals to get information about SSM documents and Automation workflows; to get information about resource tags; and to get information about and update service settings. • compute-optimizer – Allows principals to get the opt-in status of an account. • support – Allows principals to get information about AWS Trusted Advisor checks. AWS managed policies 2447 AWS Systems
systems-manager-ug-715
systems-manager-ug.pdf
715
AWS Config. • sns – Allows principals to list platform applications in Amazon SNS. • config – Allows principals to deploy AWS Config conformance packs; to get the status of conformance packs; and to get information about configuration recorders. • ssm – Allows principals to get information about SSM documents and Automation workflows; to get information about resource tags; and to get information about and update service settings. • compute-optimizer – Allows principals to get the opt-in status of an account. • support – Allows principals to get information about AWS Trusted Advisor checks. AWS managed policies 2447 AWS Systems Manager User Guide To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupCFGCPacksPermissionsBoundary in the AWS Managed Policy Reference Guide. AWS managed policy: AWS-SSM-DiagnosisAutomation-AdministrationRolePolicy The policy AWS-SSM-DiagnosisAutomation-AdministrationRolePolicy provides permissions for diagnosing issues with nodes that interact with Systems Manager services by starting Automation workflows in accounts and Regions where nodes are managed. You can attach AWS-SSM-DiagnosisAutomation-AdministrationRolePolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform diagnosis actions on your behalf. Permissions details This policy includes the following permissions. • ssm – Allows principals to run Automation runbooks that diagnose node issues and access the execution status for a workflow. • kms – Allows principals to use customer-specified AWS Key Management Service keys that are used to encrypt objects in S3 bucket to decrypt and access the content of objects in the bucket. • sts – Allows principals to assume diagnosis execution roles to run Automation runbooks in the same account. • iam – Allows principals to pass the diagnosis administration role (for example, self) to Systems Manager to run Automation runbooks. • s3 – Allows principals to access and write objects to an S3 bucket. To view more details about the policy, including the latest version of the JSON policy document, see AWS-SSM-DiagnosisAutomation-AdministrationRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWS-SSM-DiagnosisAutomation-ExecutionRolePolicy The managed policy AWS-SSM-DiagnosisAutomation-ExecutionRolePolicy provides administrative permission for running Automation runbooks in a targeted AWS account and Region to diagnose issues with managed nodes that interact with Systems Manager services. AWS managed policies 2448 AWS Systems Manager User Guide You can attach AWS-SSM-DiagnosisAutomation-ExecutionRolePolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. Permissions details This policy includes the following permissions. • ssm – Allows principals to run diagnosis-specific Automation runbooks and access the automation workflow status and execution metadata. • ec2 – Allows principals to describe Amazon EC2 and Amazon VPC resources and their configurations, to diagnose issues with Systems Manager services. • kms – Allows principals to use customer-specified AWS Key Management Service keys that are used to encrypt objects in an S3 bucket to decrypt and access the content of objects in the bucket. • iam – Allows principals to pass the diagnosis execution role (for example, self) to Systems Manager to run Automation documents. To view more details about the policy, including the latest version of the JSON policy document, see AWS-SSM-DiagnosisAutomation-ExecutionRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWS-SSM-RemediationAutomation- AdministrationRolePolicy The managed policy AWS-SSM-RemediationAutomation-AdministrationRolePolicy provides permission for remediating issues in managed nodes that interact with Systems Manager services by starting Automation workflows in accounts and Regions where nodes are managed. You can attach this policy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform remediation actions on your behalf. Permissions details This policy includes the following permissions. • ssm – Allows principals to run specific Automation runbooks and access the automation workflow status and execution status. AWS managed policies 2449 AWS Systems Manager User Guide • kms – Allows principals to use customer-specified AWS Key Management Service keys that are used to encrypt objects in an S3 bucket to decrypt and access the content of objects in the bucket. • sts – Allows principals to assume remediation execution roles to run SSM Automation documents in the same account. • iam – Allows principals to pass the remediation administrator role (for example, self) to Systems Manager to run Automation documents. • s3 – Allows principals to access and write objects to an S3 bucket. To view more details about the policy, including the latest version of the JSON policy document, see AWS-SSM-RemediationAutomation-AdministrationRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWS-SSM-RemediationAutomation-ExecutionRolePolicy The managed policy AWS-SSM-RemediationAutomation-ExecutionRolePolicy provides permission for running Automation runbooks in a specific target account and Region to remediate issues with managed nodes that interact with Systems Managerservices. You can attach the policy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to
systems-manager-ug-716
systems-manager-ug.pdf
716
Manager to run Automation documents. • s3 – Allows principals to access and write objects to an S3 bucket. To view more details about the policy, including the latest version of the JSON policy document, see AWS-SSM-RemediationAutomation-AdministrationRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWS-SSM-RemediationAutomation-ExecutionRolePolicy The managed policy AWS-SSM-RemediationAutomation-ExecutionRolePolicy provides permission for running Automation runbooks in a specific target account and Region to remediate issues with managed nodes that interact with Systems Managerservices. You can attach the policy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform remediation actions on your behalf. Permissions details This policy includes the following permissions. • ssm – Allows principals to run specific Automation runbooks and access execution metadata and status. • ec2 – Allows principals to create, access, and modify Amazon EC2 resources and Amazon VPC resources and their configurations in order to remediate issues with Systems Manager services and associated resources, such as security groups; and to attach tags to resources. • kms – Allows principals to use customer-specified AWS Key Management Service keys that are used to encrypt objects in S3 bucket to decrypt and access the content of objects in the bucket. • iam – Allows principals to pass the remediation execution role (for example, self) to the SSM service to run Automation documents. AWS managed policies 2450 AWS Systems Manager User Guide To view more details about the policy, including the latest version of the JSON policy document, see AWS-SSM-RemediationAutomation-ExecutionRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupSSMManageResourcesExecutionPolicy This policy grants permissions that allow Quick Setup to run the AWSQuickSetupType- SSM-SetupResources Automation runbook. This runbook creates IAM roles for Quick Setup associations, which in turn are created by a AWSQuickSetupType-SSM deployment. It also grants permissions to clean up an associated Amazon S3 bucket on during a Quick Setup delete operation. You can attach the policy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. Permissions details This policy includes the following permissions. • iam – Allows principals to list and manage IAM roles for use with Quick Setup Systems Manager Explorer operations; to view, attach, and detach IAM policies for use with Quick Setup and Systems Manager Explorer These permissions are required so Quick Setup can create the roles needed for some of its configuration operations. • s3 – Allows principals to retrieve information about objects in, and to delete objects from Amazon S3 buckets, in the principal account, that are used specifically in Quick Setup configuration operations. This is required so that S3 objects that are no longer needed after configuration can be removed. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupSSMManageResourcesExecutionPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupSSMLifecycleManagementExecutionPolicy The AWSQuickSetupSSMLifecycleManagementExecutionPolicy policy grants administrative permissions that allow Quick Setup to run the a AWS CloudFormation custom resource on lifecycle events during Quick Setup deployment in Systems Manager. You can attach this policy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. AWS managed policies 2451 AWS Systems Manager Permissions details This policy includes the following permissions. User Guide • ssm – Allows principals to get information about automation executions and start automation executions for setting up certain Quick Setup operations. • iam – Allows principals to pass roles from IAM for setting up certain Quick Setup resources. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupSSMLifecycleManagementExecutionPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupSSMDeploymentRolePolicy The managed policy AWSQuickSetupSSMDeploymentRolePolicy grants administrative permissions that allow Quick Setup to create resources that are used during the Systems Manager onboarding process. Though you can manually attach this policy to your IAM entities, this is not recommended. Quick Setup creates entities that attach this policy to a service role that allows Systems Manager to perform actions on your behalf. This policy is not related to the SSMQuickSetupRolePolicy policy, which is used to provide permissions for the AWSServiceRoleForSSMQuickSetup service-linked role. Permissions details This policy includes the following permissions. • ssm – Allows principals to manage associations for certain resources that are created using AWS CloudFormation templates and a specific set of SSM documents; to manage roles and role policies using for diagnosing and remediating managed nodes through AWS CloudFormation templates; and to attach and delete policies for Quick Setup lifecycle events • iam – Allows principals to tag roles and pass roles permissions for the Systems Manager service and Lambda service, and to pass role permissions for diagnosis operations. • lambda –
systems-manager-ug-717
systems-manager-ug.pdf
717
to provide permissions for the AWSServiceRoleForSSMQuickSetup service-linked role. Permissions details This policy includes the following permissions. • ssm – Allows principals to manage associations for certain resources that are created using AWS CloudFormation templates and a specific set of SSM documents; to manage roles and role policies using for diagnosing and remediating managed nodes through AWS CloudFormation templates; and to attach and delete policies for Quick Setup lifecycle events • iam – Allows principals to tag roles and pass roles permissions for the Systems Manager service and Lambda service, and to pass role permissions for diagnosis operations. • lambda – Allows principals to tag and manage functions for the Quick Setup lifecycle in the principal account using AWS CloudFormation templates. AWS managed policies 2452 AWS Systems Manager User Guide • cloudformation – Allows principals to read information from AWS CloudFormation. This is required so Quick Setup can gather data about the AWS CloudFormation stacks used to manage the state of resources and CloudFormation stackset operations. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupSSMDeploymentRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupSSMDeploymentS3BucketRolePolicy The AWSQuickSetupSSMDeploymentS3BucketRolePolicy policy grants permissions for listing all S3 buckets in an account; and for managing and retrieving information about specific buckets in the principal account that are managed through AWS CloudFormation templates. You can attach AWSQuickSetupSSMDeploymentS3BucketRolePolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. Permissions details This policy includes the following permissions. • s3 – Allows principals list all S3 buckets in an account; and to manage and retrieve information about specific buckets in the principal account that are managed through AWS CloudFormation templates. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupSSMDeploymentS3BucketRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupEnableDHMCExecutionPolicy This policy grants administrative permissions that allow principals to run the AWSQuickSetupType-EnableDHMC Automation runbook, which enables Default Host Management Configuration. The Default Host Management Configuration setting allows Systems Manager to automatically manage Amazon EC2 instances as managed instances. A managed instance is an EC2 instance that is configured for use with Systems Manager. This policy also grants permissions for creating IAM roles that are specified in Systems Manager service settings as the default roles for SSM Agent. AWS managed policies 2453 AWS Systems Manager User Guide You can attach AWSQuickSetupEnableDHMCExecutionPolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. Permissions details This policy includes the following permissions. • ssm – Allows principals to update and get information about Systems Manager service settings. • iam – Allows principals to create and retrieve information about IAM roles for Quick Setup operations. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupEnableDHMCExecutionPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupEnableAREXExecutionPolicy This policy grants administrative permissions that allow Systems Manager to run the AWSQuickSetupType-EnableAREX Automation runbook, which enables AWS Resource Explorer for use with Systems Manager. Resource Explorer makes it possible to view resources in your account with a search experience similar to an Internet search engine. The policy also grants permissions for managing Resource Explorer indexes and views. You can attach AWSQuickSetupEnableAREXExecutionPolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. Permissions details This policy includes the following permissions. • iam – Allows principals to to create a service-linked role in the AWS Identity and Access Management (IAM) service. • resource-explorer-2 – Allows principals to retrieve information about Resource Explorer views and indexes; to create Resource Explorer views and indexes; to change the index type for indexes displayed in Quick Setup. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupEnableAREXExecutionPolicy in the AWS Managed Policy Reference Guide. AWS managed policies 2454 AWS Systems Manager User Guide AWS managed policy: AWSQuickSetupManagedInstanceProfileExecutionPolicy THhis policy grants administrative permissions that allow Systems Manager to create a default IAM instance profile for the Quick Setup tool, and to attach it to Amazon EC2 instances that don't already have an instance profile attached. The policy also grants Systems Manager the ability to attach permissions to existing instance profiles. This is done to ensure that the permissions required for Systems Manager to communicate with .SSM Agent on EC2 instances are in place. You can attach AWSQuickSetupManagedInstanceProfileExecutionPolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. Permissions details This policy includes the
systems-manager-ug-718
systems-manager-ug.pdf
718
to create a default IAM instance profile for the Quick Setup tool, and to attach it to Amazon EC2 instances that don't already have an instance profile attached. The policy also grants Systems Manager the ability to attach permissions to existing instance profiles. This is done to ensure that the permissions required for Systems Manager to communicate with .SSM Agent on EC2 instances are in place. You can attach AWSQuickSetupManagedInstanceProfileExecutionPolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. Permissions details This policy includes the following permissions. • ssm – Allows principals to start automation workflows associated with Quick Setup processes. • ec2 – Allows principals to attach IAM instance profiles to EC2 instances that are managed by Quick Setup. • iam – Allows principals to create, update, and retrieve information about roles from IAM that are used in Quick Setup processes; to create IAM instance profiles; to attach the AmazonSSMManagedInstanceCore managed policy to IAM instance profiles. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupManagedInstanceProfileExecutionPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupFullAccess This policy grants administrative permissions that allow full access to AWS Systems Manager Quick Setup API actions and data in the AWS Management Console and AWS SDKs, as well as limited access to other AWS service resources that are required for Quick Setup operations. You can attach the AWSQuickSetupFullAccess policy to your IAM identities. Permissions details This policy includes the following permissions. AWS managed policies 2455 AWS Systems Manager User Guide • ssm – Allows principals to enable Explorer; to perform resource data sync operations in State Manager; and to perform operations using SSM Command documents and Automation runbooks. Explorer, State Manager, Documents, and Automation are all tools in Systems Manager. • cloudformation – Allows principals to perform the AWS CloudFormation operations that are necessary for provisioning resources across AWS Regions and AWS accounts. • ec2 – Allows principals to select the necessary parameters for a given configuration, and to provide validation in the AWS Management Console. • iam – Allows principals to create the required service roles and service-linked roles for Quick Setup operations. • organizations – Allows principals to read the status of accounts in an AWS Organizations organization; to retrieve an organization's structure; to enable trusted access; and to register a delegated administrator account from the management account. • resource-groups – Allows principals to select the necessary parameters for a given configuration, and to provide validation in the AWS Management Console. • s3 – Allows principals to select the necessary parameters for a given configuration, and to provide validation in the AWS Management Console. • ssm-quicksetup – Allows principals to perform read-only actions in Quick Setup. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupFullAccess in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupReadOnlyAccess This policy grants read-only permissions that allow principals to view AWS Systems Manager Quick Setup data and reports, including information from other AWS service resources that are required for Quick Setup operations. You can attach the AWSQuickSetupReadOnlyAccess policy to your IAM identities. Permissions details This policy includes the following permissions. • ssm – Allows principals to read SSM Command documents and Automation runbooks; and to retrieve the status of State Manager association executions. AWS managed policies 2456 AWS Systems Manager User Guide • cloudformation – Allows principals to initiate operations that are required for retrieving the status of AWS CloudFormation deployments. • organizations – Allows principals to read the status of accounts in an AWS Organizations organization. • ssm-quicksetup – Allows principals to perform read-only actions in Quick Setup. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupReadOnlyAccess in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupManageJITNAResourcesExecutionPolicy The managed policy AWSQuickSetupManageJITNAResourcesExecutionPolicy enables Quick Setup, a tool in Systems Manager, to set up just-in-time node access. You can attach AWSQuickSetupManageJITNAResourcesExecutionPolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. This policy grants administrative permissions that allow Systems Manager to create resources associated with just-in-time node access. Permissions details This policy includes the following permissions. • ssm – Allows principals to get and update the service setting that specifies the identity provider for just-in-time node access. • iam – Allows principals to create, tag, and get roles, attach role policies for just-in-time node access managed policies, and create service-linked roles for just-in-time node access and notifications. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupManageJITNAResourcesExecutionPolicy in the AWS
systems-manager-ug-719
systems-manager-ug.pdf
719
on your behalf. This policy grants administrative permissions that allow Systems Manager to create resources associated with just-in-time node access. Permissions details This policy includes the following permissions. • ssm – Allows principals to get and update the service setting that specifies the identity provider for just-in-time node access. • iam – Allows principals to create, tag, and get roles, attach role policies for just-in-time node access managed policies, and create service-linked roles for just-in-time node access and notifications. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupManageJITNAResourcesExecutionPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSQuickSetupJITNADeploymentRolePolicy The managed policy AWSQuickSetupJITNADeploymentRolePolicy allows Quick Setup to deploy the configuration type required to set up just-in-time node access. AWS managed policies 2457 AWS Systems Manager User Guide You can attach AWSQuickSetupJITNADeploymentRolePolicy to your IAM entities. Systems Manager also attaches this policy to a service role that allows Systems Manager to perform actions on your behalf. This policy grants administrative permissions that allow Systems Manager to create resources associated with just-in-time node access. Permissions details This policy includes the following permissions. • cloudformation – Allows principals to create, update, delete, and read AWS CloudFormation stacks. • ssm – Allows principals to create, delete, update, and read State Manager associations that are called by AWS CloudFormation. • iam – Allows principals create, delete, read and tag IAM roles that are called by AWS CloudFormation. To view more details about the policy, including the latest version of the JSON policy document, see AWSQuickSetupJITNADeploymentRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSSystemsManagerJustInTimeAccessServicePolicy The managed policy AWSSystemsManagerJustInTimeAccessServicePolicy provides permissions to AWS resources managed or used by the Systems Manager just-in-time node access feature. You can't attach AWSSystemsManagerJustInTimeAccessServicePolicy to your IAM entities. This policy is attached to a service-linked role that allows Systems Manager to perform actions on your behalf. For more information, see Using roles to enable just-in-time node access. This policy grants administrative permissions that allows access to resources associated with just- in-time node access. Permissions details This policy includes the following permissions. • ssm – Allows principals to create, describe, and update OpsItems, describe sessions and list tags for managed nodes. AWS managed policies 2458 AWS Systems Manager User Guide • ssm-guiconnect – Allows principals to list connections. • identitystore – Allows to get user and group IDs, describe users, and list group membership. • sso-directory – Allows principals to describe users and determine if a user is a member of a group. • sso – Allows principals to describe registered Regions and list instances and directory associations. • cloudwatch – Allows principals to put metric data for the AWS/SSM/JustInTimeAccess namespace. • ec2 – Allows principals to describe tags. To view more details about the policy, including the latest version of the JSON policy document, see AWSSystemsManagerJustInTimeAccessServicePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSSystemsManagerJustInTimeAccessTokenPolicy The managed policy AWSSystemsManagerJustInTimeAccessTokenPolicy allows Systems Manager to generate access tokens used for just-in-time node access. You can attach AWSSystemsManagerJustInTimeAccessTokenPolicy to your IAM entities. This policy grants administrative permissions that allow Systems Manager to start sessions and generate access tokens for just-in-time node access. Permissions details This policy includes the following permissions. • ssm – Allows principals to send commands, list command invocations, and start, resume, and end Session Manager sessions. • ssm-guiconnect – Allows principals to start, describe, and end Systems Manager GUI Connect RDP connections. • kms – Allows principals to create grants and generate key data. • sso – Allows principals to list directory associations. • identitystore – Allows principals to describe a user. AWS managed policies 2459 AWS Systems Manager User Guide To view more details about the policy, including the latest version of the JSON policy document, see AWSSystemsManagerJustInTimeAccessTokenPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSSystemsManagerJustInTimeAccessTokenSessionPolicy The managed policy AWSSystemsManagerJustInTimeAccessTokenSessionPolicy allows Systems Manager to apply scoped down permissions to a just-in-time node access token. You can attach AWSSystemsManagerJustInTimeAccessTokenSessionPolicy to your IAM entities. This policy grants administrative permissions that allow Systems Manager to scope down permissions for just-in-time node access tokens. Permissions details This policy includes the following permissions. • ssm – Allows principals to start Session Manager sessions using the SSM- SessionManagerRunShell document. Also when called first via ssm-guiconnect, start sessions using the AWS-StartPortForwardingSession document, list command invocations, and send commands using the AWSSSO-CreateSSOUser document. • ssm-guiconnect – Allows principals to cancel, get, and start connections on all resources. • kms – Allows principals to create grants and generate data keys for keys tagged with SystemsManagerJustInTimeNodeAccessManaged when called via ssm-guiconnect through an AWS service. • sso – Allows principals to list directory associations when called via ssm-guiconnect. • identitystore – Allows principals to describe a user when called via ssm-guiconnect. To view more details
systems-manager-ug-720
systems-manager-ug.pdf
720
start Session Manager sessions using the SSM- SessionManagerRunShell document. Also when called first via ssm-guiconnect, start sessions using the AWS-StartPortForwardingSession document, list command invocations, and send commands using the AWSSSO-CreateSSOUser document. • ssm-guiconnect – Allows principals to cancel, get, and start connections on all resources. • kms – Allows principals to create grants and generate data keys for keys tagged with SystemsManagerJustInTimeNodeAccessManaged when called via ssm-guiconnect through an AWS service. • sso – Allows principals to list directory associations when called via ssm-guiconnect. • identitystore – Allows principals to describe a user when called via ssm-guiconnect. To view more details about the policy, including the latest version of the JSON policy document, see AWSSystemsManagerJustInTimeAccessTokenSessionPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSSystemsManagerJustInTimeNodeAccessRolePropagationPolicy The managed policy AWSSystemsManagerJustInTimeNodeAccessRolePropagationPolicy allows Systems Manager to share deny-access policies from the delegated administrator account to member accounts, and replicate the policies across multiple AWS Regions. AWS managed policies 2460 AWS Systems Manager User Guide You can attach AWSSystemsManagerJustInTimeNodeAccessRolePropagationPolicy to your IAM entities. This policy provides the administrative permissions necessary for Systems Manager to share and create deny-access policies. This ensures that deny-access policies are applied to all accounts in an AWS Organizations organization and Regions configured for just-in-time node access. Permissions details This policy includes the following permissions. • ssm – Allows principals to manage SSM documents and resource policies. • ssm-quicksetup – Allows principals to read Quick Setup configuration managers. • organizations – Allows principals to list details about an AWS Organizations organization and delegated administrators. • ram – Allows principals to create, tag, and describe resource shares. • iam – Allows principals to describe a service role. To view more details about the policy, including the latest version of the JSON policy document, see AWSSystemsManagerJustInTimeNodeAccessRolePropagationPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWSSystemsManagerNotificationsServicePolicy The managed policy AWSSystemsManagerNotificationsServicePolicy allows Systems Manager to send email notifications for just-in-time node access requests to access request approvers. You can't attach AWSSystemsManagerJustInTimeAccessServicePolicy to your IAM entities. This policy is attached to a service-linked role that allows Systems Manager to perform actions on your behalf. For more information, see Using roles to send just-in-time node access request notifications. This policy grants administrative permissions that allow Systems Manager to send email notifications for just-in-time node access requests to access request approvers. Permissions details This policy includes the following permissions. AWS managed policies 2461 AWS Systems Manager User Guide • identitystore – Allows principals to list and describe users and group membership. • sso – Allows principals to list instances, directories, and describe registered Regions. • sso-directory – Allows principals to describe users and list members in a group. • iam – Allows principals to get information about roles. To view more details about the policy, including the latest version of the JSON policy document, see AWSSystemsManagerNotificationsServicePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWS-SSM-Automation-DiagnosisBucketPolicy The managed policy AWS-SSM-Automation-DiagnosisBucketPolicy provides permissions for diagnosing issues with nodes that interact with AWS Systems Manager services, by allowing access to S3 buckets that are used for diagnosis and remediation of issues. You can attach the AWS-SSM-Automation-DiagnosisBucketPolicy policy to your IAM identities. Systems Manager also attaches this policy to an IAM role that allows Systems Manager to perform diagnosis actions on your behalf. Permissions details This policy includes the following permissions. • s3 – Allows principals to access and write objects to an Amazon S3 bucket. To view more details about the policy, including the latest version of the JSON policy document, see AWS-SSM-Automation-DiagnosisBucketPolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWS-SSM-RemediationAutomation- OperationalAccountAdministrationRolePolicy The managed policy AWS-SSM-RemediationAutomation- OperationalAccountAdministrationRolePolicy provides permissions for an operational account to diagnose issues with nodes by providing organization-specific permissions. You can attach AWS-SSM-RemediationAutomation- OperationalAccountAdministrationRolePolicy to your IAM identities. Systems Manager also attaches this policy to an IAM role that allows Systems Manager to perform diagnosis actions on your behalf. AWS managed policies 2462 AWS Systems Manager Permissions details This policy includes the following permissions. User Guide • organizations – Allows principals to list a root of the organization, and get member accounts to determine target accounts. • sts – Allows principals to assume remediation execution roles to run SSM Automation documents across accounts and Regions, within the same organization. To view more details about the policy, including the latest version of the JSON policy document, see AWS-SSM-RemediationAutomation-OperationalAccountAdministrationRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWS-SSM-DiagnosisAutomation- OperationalAccountAdministrationRolePolicy The managed policy AWS-SSM-DiagnosisAutomation- OperationalAccountAdministrationRolePolicy provides permissions for an operational account to diagnose issues with nodes by providing organization-specific permissions. You can attach the AWS-SSM-DiagnosisAutomation- OperationalAccountAdministrationRolePolicy policy to your IAM identities. Systems Manager also attaches this policy to an IAM role that allows Systems Manager to perform diagnosis actions on your behalf. Permissions details This policy includes the following permissions. •
systems-manager-ug-721
systems-manager-ug.pdf
721
documents across accounts and Regions, within the same organization. To view more details about the policy, including the latest version of the JSON policy document, see AWS-SSM-RemediationAutomation-OperationalAccountAdministrationRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policy: AWS-SSM-DiagnosisAutomation- OperationalAccountAdministrationRolePolicy The managed policy AWS-SSM-DiagnosisAutomation- OperationalAccountAdministrationRolePolicy provides permissions for an operational account to diagnose issues with nodes by providing organization-specific permissions. You can attach the AWS-SSM-DiagnosisAutomation- OperationalAccountAdministrationRolePolicy policy to your IAM identities. Systems Manager also attaches this policy to an IAM role that allows Systems Manager to perform diagnosis actions on your behalf. Permissions details This policy includes the following permissions. • organizations – Allows principals to list a root of the organization, and get member accounts to determine target accounts. • sts – Allows principals to assume diagnosis execution roles to run SSM Automation documents across accounts and Regions, within the same organization. To view more details about the policy, including the latest version of the JSON policy document, see AWS-SSM-DiagnosisAutomation-OperationalAccountAdministrationRolePolicy in the AWS Managed Policy Reference Guide. AWS managed policies 2463 AWS Systems Manager User Guide Systems Manager updates to AWS managed policies In the following table, view details about updates to AWS managed policies for Systems Manager since this service began tracking these changes on March 12, 2021. For information about other managed policies for the Systems Manager service, see Additional managed policies for Systems Manager later in this topic. For automatic alerts about changes to this page, subscribe to the RSS feed on the Systems Manager Document history page. Change Description Date AWSSystemsManagerJ ustInTimeNodeAcces sRolePropagationPolicy – Systems Manager added permissions to allow Systems Manager to tag a resource Update to an policy shared by for just-in-time node access. April 30th, 2025 AWSQuickSetupManag eJITNAResourcesExecutionPol Systems Manager added permissions to allow Systems April 30th, 2025 icy – Update to an policy Manager to tag IAM roles created for just-in-time node access. AWSSystemsManagerJ ustInTimeAccessTokenSession Systems Manager added a new policy to allow Systems Policy – New policy Manager to apply scoped April 30th, 2025 AWSSystemsManagerN otificationsServicePolicy – New policy down permissions to a just-in- time node access token. Systems Manager added a new policy to allow Systems Manager to send email notifications for just-in-t ime node access requests to access request approvers. April 30th, 2025 AWSSystemsManagerJ ustInTimeNodeAcces Systems Manager added a new policy to allow Systems April 30th, 2025 AWS managed policies 2464 AWS Systems Manager User Guide Change Description Date sRolePropagationPolicy – Manager to replicate approval New policy policies to different Regions. AWSSystemsManagerJ ustInTimeAccessTokenPolicy – Systems Manager added a new policy to allow Systems April 30th, 2025 New policy Manager to generate access tokens used for just-in-time node access. AWSSystemsManagerJ ustInTimeAccessServicePolicy Systems Manager added a new policy to provide April 30th, 2025 – New policy permissions to AWS resources managed or used by the Systems Manager just-in-time node access feature. AWSQuickSetupManag eJITNAResourcesExecutionPol Systems Manager added a new policy to allow Quick April 30th, 2025 icy – New policy Setup, a tool in Systems Manager, to create the IAM roles necessary for just-in-t ime node access. AWSQuickSetupJITNA DeploymentRolePolicy – New Systems Manager added a new policy that provides April 30th, 2025 policy permissions that allow Quick Setup to deploy the configura tion type required to set up just-in-time node access. AWS managed policies 2465 AWS Systems Manager User Guide Change Description Date AWS-SSM-DiagnosisA utomation-Operatio nalAccountAdminist – rationRolePolicy New policy Systems Manager added a new policy that provides permissions for an operation al account to diagnose issues with nodes by providing organization-specific permissions. November 21, 2024 AWS-SSM-Remediatio nAutomation-Operat Systems Manager added a new policy that provides ionalAccountAdmini permissions for an operation strationRolePolicy New policy – al account to diagnose issues with nodes by providing November 21, 2024 AWS-SSM-Automation -DiagnosisBucketPo licy – New policy AmazonSSMServiceRo lePolicy – Update to an existing policy organization-specific permissions. Systems Manager added a new policy to support starting Automation workflows that diagnose issues with managed nodes in targeted accounts and Regions. Systems Manager added new permissions to allow AWS Resource Explorer to gather details about Amazon EC2 instances and display the results in widgets in the new Systems Manager Dashboard. November 21, 2024 November 21, 2024 AWS managed policies 2466 AWS Systems Manager User Guide Change Description Date SSMQuickSetupRoleP olicy – Update to an existing policy AWS-SSM-DiagnosisA utomation-Administ rationRolePolicy New policy AWS-SSM-DiagnosisA utomation-Executio nRolePolicy – New policy November 21, 2024 Systems Manager has updated the managed policy SSMQuickSetupRoleP olicy . This updates allows the associated service-linked role AWSServiceRoleForS to manage SMQuickSetup resource data syncs. Systems Manager added a new policy to support starting November 21, 2024 – Automation workflows that diagnose issues with managed nodes in targeted account and Regions. Systems Manager added a new policy to support starting Automation workflows that diagnose issues with managed nodes in a targeted account and Region. November 21, 2024 AWS-SSM-Remediatio nAutomation-Admini
systems-manager-ug-722
systems-manager-ug.pdf
722
SSMQuickSetupRoleP olicy – Update to an existing policy AWS-SSM-DiagnosisA utomation-Administ rationRolePolicy New policy AWS-SSM-DiagnosisA utomation-Executio nRolePolicy – New policy November 21, 2024 Systems Manager has updated the managed policy SSMQuickSetupRoleP olicy . This updates allows the associated service-linked role AWSServiceRoleForS to manage SMQuickSetup resource data syncs. Systems Manager added a new policy to support starting November 21, 2024 – Automation workflows that diagnose issues with managed nodes in targeted account and Regions. Systems Manager added a new policy to support starting Automation workflows that diagnose issues with managed nodes in a targeted account and Region. November 21, 2024 AWS-SSM-Remediatio nAutomation-Admini strationRolePolicy New policy Systems Manager added a new policy to support starting – Automation workflows that remediate issues in managed nodes in targeted accounts and Regions. November 21, 2024 AWS managed policies 2467 AWS Systems Manager User Guide Change Description Date AWS-SSM-Remediatio nAutomation-Execut Systems Manager added a new policy to support starting November 21, 2024 ionRolePolicy policy – New Automation workflows that remediate issues in managed nodes in a targeted account and Region. AWSQuickSetupSSMDe ploymentRolePolicy – Update Systems Manager added permissions to allow Systems May 7th, 2025 to an policy Manager to tag IAM roles and Lambda created for the unified console. AWSQuickSetupSSMMa nageResourcesExecu Systems Manager added a new policy to support running tionPolicy – New policy an operation in Quick Setup November 21, 2024 AWSQuickSetupSSMLi fecycleManagementE xecutionPolicy – New policy that creates IAM roles for Quick Setup associations, which in turn are created by a AWSQuickSetupType- SSM deployment. Systems Manager added a new policy to support Quick Setup running a AWS CloudFormation custom resource on lifecycle events during a Quick Setup deployment. November 21, 2024 AWS managed policies 2468 AWS Systems Manager User Guide Change Description Date AWSQuickSetupSSMDe ploymentRolePolicy New policy Systems Manager added a new policy to support – granting administrative November 21, 2024 AWSQuickSetupSSMDe ploymentS3BucketRo lePolicy – New policy AWSQuickSetupEnabl eDHMCExecutionPoli cy – New policy permissions that allow Quick Setup to create resources that are using during the Systems Manager onboarding process. Systems Manager added a new policy to support managing and retrieving information about specific buckets in the principal account that are managed through AWS CloudFormation templates November 21, 2024 Systems Manager is introduci ng a new policy to allow November 21, 2024 Quick Setup to create an IAM role that itself uses the existing AmazonSSM ManagedEC2Instance . This DefaultPolicy policy contains all the permissions required for SSM Agent to communicate with Systems Manager service. The new policy also allows modifications to the Systems Manager service settings. AWS managed policies 2469 AWS Systems Manager User Guide Change Description Date AWSQuickSetupEnabl eAREXExecutionPoli cy – New policy AWSQuickSetupManag edInstanceProfileE xecutionPolicy – New policy AWSQuickSetupFullA ccess – New policy November 21, 2024 November 21, 2024 November 21, 2024 Systems Manager added a new policy to allow Quick Setup to create a service-l inked role for AWS Resource Explorer, for accessing Resource Explorer views and aggregator indexes. Systems Manager added a new policy to allow Quick Setup to create a default Quick Setup instance profile and to attach it to any Amazon EC2 instances that lack an associated instance profile. This new policy also allows Quick Setup to attach permissions to existing profiles to ensure that all required Systems Manager permissions have been granted. Systems Manager added a new policy to allow Entities full access to AWS Systems Manager Quick Setup API actions and data in the AWS Management Console and AWS SDKs, as well as limited access to other AWS service resources that are required for Quick Setup operations. AWS managed policies 2470 AWS Systems Manager User Guide Change Description Date AWSQuickSetupReadO nlyAccess – New policy Systems Manager added a new policy to grant read- November 21, 2024 only permissions that allow principals to view AWS Systems Manager Quick Setup data and reports, including information from other AWS service resources that are required for Quick Setup operations. Systems Manager added new permissions to allow Quick Setup to check the health of additional AWS CloudForm ation stack sets that it has created. Systems Manager has added statement IDs (Sids) to the JSON policy for AmazonSSM ManagedEC2Instance DefaultPolicy Sids provide inline descripti . These ons of the purpose of each policy statement. Systems Manager added a new policy to allow Quick Setup to check the health of deployed resources and remediate instances that have drifted from the original configuration. August 13, 2024 July 18, 2024 July 3, 2024 SSMQuickSetupRoleP olicy – Update to an existing policy AmazonSSMManagedEC 2InstanceDefaultPo licy – Update to an existing policy SSMQuickSetupRoleP olicy – New policy AWS managed policies 2471 AWS Systems Manager User Guide Change Description Date AWSQuickSetupDeplo ymentRolePolicy policy – New AWSQuickSetupPatch PolicyDeploymentRo lePolicy – New policy July 3, 2024 July 3, 2024 Systems Manager added a new policy to support multiple Quick Setup configuration
systems-manager-ug-723
systems-manager-ug.pdf
723
statement. Systems Manager added a new policy to allow Quick Setup to check the health of deployed resources and remediate instances that have drifted from the original configuration. August 13, 2024 July 18, 2024 July 3, 2024 SSMQuickSetupRoleP olicy – Update to an existing policy AmazonSSMManagedEC 2InstanceDefaultPo licy – Update to an existing policy SSMQuickSetupRoleP olicy – New policy AWS managed policies 2471 AWS Systems Manager User Guide Change Description Date AWSQuickSetupDeplo ymentRolePolicy policy – New AWSQuickSetupPatch PolicyDeploymentRo lePolicy – New policy July 3, 2024 July 3, 2024 Systems Manager added a new policy to support multiple Quick Setup configuration types that create IAM roles and automations, which in turn configure frequently used Amazon Web Services services and features with recommended best practices. Systems Manager added a new policy to allow Quick Setup to create resources associated with Patch Manager patch policy Quick Setup configurations. AWSQuickSetupPatch PolicyBaselineAccess – New Systems Manager added a new policy to allow Quick July 3, 2024 policy AWSSystemsManagerE nableExplorerExecutionPolicy – New policy AWSSystemsManagerE nableConfigRecordingExecuti onPolicy – New policy Setup to access patch baselines in Patch Manager with read-only permissions. Systems Manager added a new policy to allow Quick Setup to grant administrative permissions for enabling Explorer. Systems Manager added a new policy to allow Quick Setup to enable and configure AWS Config configuration recording. July 3, 2024 July 3, 2024 AWS managed policies 2472 AWS Systems Manager User Guide Change Description Date AWSQuickSetupDevOp sGuruPermissionsBoundary – Systems Manager added a new policy to allow Quick July 3, 2024 New policy Setup to enable and configure Amazon DevOps Guru. AWSQuickSetupDistr ibutorPermissionsBoundary – Systems Manager added a new policy to allow Quick July 3, 2024 New policy Setup to enable and configure Distributor, a tool in AWS Systems Manager. AWSQuickSetupSSMHo stMgmtPermissionsBoundary Systems Manager added a new policy to allow Quick July 3, 2024 – New policy Setup to enable and configure Systems Manager tools for securely managing Amazon EC2 instances. AWSQuickSetupPatch PolicyPermissionsBoundary – Systems Manager added a new policy to allow Quick July 3, 2024 New policy Setup to enable and configure AWSQuickSetupSched ulerPermissionsBoundary – New policy patch policies in Patch Manager, a tool in AWS Systems Manager. Systems Manager added a new policy to allow Quick Setup to enable and configure scheduled operations on Amazon EC2 instances and other resources. July 3, 2024 AWSQuickSetupCFGCP acksPermissionsBoundary – New policy Systems Manager added a new policy to allow Quick Setup to deploy AWS Config July 3, 2024 conformance packs. AWS managed policies 2473 AWS Systems Manager User Guide Change Description Date AWSSystemsManagerO psDataSyncServiceR olePolicy – Update to an existing policy AmazonSSMManagedEC 2InstanceDefaultPo licy – New policy July 3, 2023 August 18, 2022 OpsCenter updated the policy to improve the security of the service code within the service-linked role for Explorer to manage OpsData- related operations. Systems Manager added a new policy to allow Systems Manager functionality on Amazon EC2 instances without the use of an IAM instance profile. AmazonSSMServiceRolePolicy – Update to an existing policy Systems Manager added new permissions to allow April 27, 2021 Explorer to create a managed rule when you turn on Security Hub from Explorer or OpsCenter. New permissio ns were added to check that config and the compute-o ptimizer meet the necessary requirements before allowing OpsData. Systems Manager added a new policy to create and update OpsItems and OpsData from Security Hub findings in Explorer and OpsCenter. April 27, 2021 AWSSystemsManagerO psDataSyncServiceR olePolicy – New policy AWS managed policies 2474 AWS Systems Manager User Guide Change Description Date AmazonSSMServiceRo lePolicy – Update to an existing policy March 24, 2021 Systems Manager added new permissions to allow viewing aggregate OpsData and OpsItems details from multiple accounts and AWS Regions in Explorer. Systems Manager started tracking changes Systems Manager started tracking changes for its AWS March 12, 2021 managed policies. Additional managed policies for Systems Manager In addition to the managed policies described earlier in this topic, the following policies are also supported by Systems Manager. • AmazonSSMAutomationApproverAccess – AWS managed policy that allows access to view automation executions and send approval decisions to automation that is waiting for approval. • AmazonSSMAutomationRole – AWS managed policy that provides permissions for the Systems Manager Automation service to run activities defined within Automation runbooks. Assign this policy to administrators and trusted power users. • AmazonSSMDirectoryServiceAccess – AWS managed policy that that allows SSM Agent to access AWS Directory Service on behalf of the user for requests to join the domain by the managed node. • AmazonSSMFullAccess – AWS managed policy that grants full access to the Systems Manager API and documents. • AmazonSSMMaintenanceWindowRole – AWS managed policy that provides maintenance windows with permissions to the Systems Manager API. • AmazonSSMManagedInstanceCore – AWS managed policy that allows a node to use Systems Manager service core functionality. • AmazonSSMPatchAssociation –
systems-manager-ug-724
systems-manager-ug.pdf
724
run activities defined within Automation runbooks. Assign this policy to administrators and trusted power users. • AmazonSSMDirectoryServiceAccess – AWS managed policy that that allows SSM Agent to access AWS Directory Service on behalf of the user for requests to join the domain by the managed node. • AmazonSSMFullAccess – AWS managed policy that grants full access to the Systems Manager API and documents. • AmazonSSMMaintenanceWindowRole – AWS managed policy that provides maintenance windows with permissions to the Systems Manager API. • AmazonSSMManagedInstanceCore – AWS managed policy that allows a node to use Systems Manager service core functionality. • AmazonSSMPatchAssociation – AWS managed policy that provides access to child instances for patch association operations. AWS managed policies 2475 AWS Systems Manager User Guide • AmazonSSMReadOnlyAccess – AWS managed policy that grants access to Systems Manager read-only API operations, such as Get* and List*. • AWSSSMOpsInsightsServiceRolePolicy – AWS managed policy that provides permissions for creating and updating operational insight OpsItems in Systems Manager. Used to provide permissions through the service-linked role AWSServiceRoleForAmazonSSM_OpsInsights. • AWSSystemsManagerAccountDiscoveryServicePolicy – AWS managed policy that grants Systems Manager permission to discover AWS account information. • AWSSystemsManagerChangeManagementServicePolicy – AWS managed policy that provides access to AWS resources managed or used by the Systems Manager change management framework and used by the service-linked role AWSServiceRoleForSystemsManagerChangeManagement. • AmazonEC2RoleforSSM – This policy is no longer supported and should not be used. In its place, use the AmazonSSMManagedInstanceCore policy to allow Systems Manager service core functionality on EC2 instances. For information, see Configure instance permissions required for Systems Manager. Troubleshooting AWS Systems Manager identity and access Use the following information to help you diagnose and fix common issues that you might encounter when working with AWS Systems Manager and AWS Identity and Access Management (IAM). Topics • I am not authorized to perform an action in Systems Manager • I am not authorized to perform iam:PassRole • I want to allow people outside of my AWS account to access my Systems Manager resources I am not authorized to perform an action in Systems Manager If the AWS Management Console tells you that you're not authorized to perform an action, then you must contact your administrator for assistance. Your administrator is the person that provided you with your sign-in credentials. The following example error occurs when the mateojackson user tries to use the console to view details about a document but doesn't have ssm:GetDocument permissions. Troubleshooting 2476 AWS Systems Manager User Guide User: arn:aws:ssm::123456789012:user/mateojackson isn't authorized to perform: ssm:GetDocument on resource: MyExampleDocument In this case, Mateo asks his administrator to update his policies to allow him to access the MyExampleDocument resource using the ssm:GetDocument action. I am not authorized to perform iam:PassRole If you receive an error that you're not authorized to perform the iam:PassRole action, your policies must be updated to allow you to pass a role to Systems Manager. Some AWS services allow you to pass an existing role to that service instead of creating a new service role or service-linked role. To do this, you must have permissions to pass the role to the service. The following example error occurs when an IAM user named marymajor tries to use the console to perform an action in Systems Manager. However, the action requires the service to have permissions that are granted by a service role. Mary does not have permissions to pass the role to the service. User: arn:aws:iam::123456789012:user/marymajor is not authorized to perform: iam:PassRole In this case, Mary's policies must be updated to allow her to perform the iam:PassRole action. If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials. I want to allow people outside of my AWS account to access my Systems Manager resources You can create a role that users in other accounts or people outside of your organization can use to access your resources. You can specify who is trusted to assume the role. For services that support resource-based policies or access control lists (ACLs), you can use those policies to grant people access to your resources. To learn more, consult the following: • To learn whether Systems Manager supports these features, see How AWS Systems Manager works with IAM. Troubleshooting 2477 AWS Systems Manager User Guide • To learn how to provide access to your resources across AWS accounts that you own, see Providing access to an IAM user in another AWS account that you own in the IAM User Guide. • To learn how to provide access to your resources to third-party AWS accounts, see Providing access to AWS accounts owned by third parties in the IAM User Guide. • To learn how to provide access through identity federation, see Providing access to externally authenticated users (identity federation) in the IAM User Guide. • To
systems-manager-ug-725
systems-manager-ug.pdf
725
works with IAM. Troubleshooting 2477 AWS Systems Manager User Guide • To learn how to provide access to your resources across AWS accounts that you own, see Providing access to an IAM user in another AWS account that you own in the IAM User Guide. • To learn how to provide access to your resources to third-party AWS accounts, see Providing access to AWS accounts owned by third parties in the IAM User Guide. • To learn how to provide access through identity federation, see Providing access to externally authenticated users (identity federation) in the IAM User Guide. • To learn the difference between using roles and resource-based policies for cross-account access, see Cross account resource access in IAM in the IAM User Guide. Using service-linked roles for Systems Manager AWS Systems Manager uses AWS Identity and Access Management (IAM) service-linked roles. A service-linked role is a unique type of IAM role that is linked directly to Systems Manager. Service- linked roles are predefined by Systems Manager and include all the permissions that the service requires to call other AWS services on your behalf. Note A service role role differs from a service-linked role. A service role is a type of AWS Identity and Access Management (IAM) role that grants permissions to an AWS service so that the service can access AWS resources. Only a few Systems Manager scenarios require a service role. When you create a service role for Systems Manager, you choose the permissions to grant so that it can access or interact with other AWS resources. A service-linked role makes setting up Systems Manager easier because you don’t have to manually add the necessary permissions. Systems Manager defines the permissions of its service-linked roles, and unless defined otherwise, only Systems Manager can assume its roles. The defined permissions include the trust policy and the permissions policy, and that permissions policy can't be attached to any other IAM entity. You can delete a service-linked role only after first deleting their related resources. This protects your Systems Manager resources because you can't inadvertently remove permission to access the resources. Using service-linked roles 2478 AWS Systems Manager Note User Guide For non-EC2 nodes in a hybrid and multicloud environment , you need an additional IAM role that allows those machines to communicate with the Systems Manager service. This is the IAM service role for Systems Manager. This role grants AWS Security Token Service (AWS STS) AssumeRole trust to the Systems Manager service. The AssumeRole action returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token). You use these temporary credentials to access AWS resources that you might not normally have access to. For more information, see Create the IAM service role required for Systems Manager in hybrid and multicloud environments and AssumeRole in the AWS Security Token Service API Reference. For information about other services that support service-linked roles, see AWS services that work with IAM and look for the services that have Yes in the Service-linked roles column. Choose a Yes with a link to view the service-linked role documentation for that service. Topics • Using roles to collect inventory and view OpsData • Using roles to collect AWS account information for OpsCenter and Explorer • Using roles to create OpsData and OpsItems for Explorer • Using roles to create operational insight OpsItems in Systems Manager OpsCenter • Using roles to maintain Quick Setup-provisioned resource health and consistency • Using roles to export Explorer OpsData • Using roles to enable just-in-time node access • Using roles to send just-in-time node access request notifications Using roles to collect inventory and view OpsData Systems Manager uses the service-linked role named AWSServiceRoleForAmazonSSM. AWS Systems Manager uses this IAM service role to manage AWS resources on your behalf. Service-linked role permissions for inventory, OpsData, and OpsItems The AWSServiceRoleForAmazonSSM service-linked role trusts only ssm.amazonaws.com to assume this role. Inventory and Explorer data role 2479 AWS Systems Manager User Guide You can use the Systems Manager service-linked role AWSServiceRoleForAmazonSSM for the following: • The Systems Manager Inventory tool uses the service-linked role AWSServiceRoleForAmazonSSM to collect inventory metadata from tags and resource groups. • The Explorer tool uses the service-linked role AWSServiceRoleForAmazonSSM to enable viewing OpsData and OpsItems from multiple accounts. This service-linked role also allows Explorer to create a managed rule when you enable Security Hub as a data source from Explorer or OpsCenter. Important Previously, the Systems Manager console provided you with the ability to choose the AWS managed IAM service-linked role AWSServiceRoleForAmazonSSM to use as the maintenance role for your tasks. Using this role and its associated policy, AmazonSSMServiceRolePolicy, for maintenance window tasks is no longer recommended. If you're using this role for maintenance window tasks now, we encourage you to stop
systems-manager-ug-726
systems-manager-ug.pdf
726
Explorer tool uses the service-linked role AWSServiceRoleForAmazonSSM to enable viewing OpsData and OpsItems from multiple accounts. This service-linked role also allows Explorer to create a managed rule when you enable Security Hub as a data source from Explorer or OpsCenter. Important Previously, the Systems Manager console provided you with the ability to choose the AWS managed IAM service-linked role AWSServiceRoleForAmazonSSM to use as the maintenance role for your tasks. Using this role and its associated policy, AmazonSSMServiceRolePolicy, for maintenance window tasks is no longer recommended. If you're using this role for maintenance window tasks now, we encourage you to stop using it. Instead, create your own IAM role that enables communication between Systems Manager and other AWS services when your maintenance window tasks run. For more information, see Setting up Maintenance Windows. The managed policy that is used to provide permissions for the AWSServiceRoleForAmazonSSM role is AmazonSSMServiceRolePolicy. For details about the permissions it grants, see AWS managed policy: AmazonSSMServiceRolePolicy. Creating the AWSServiceRoleForAmazonSSM service-linked role for Systems Manager You can use the IAM console to create a service-linked role with the EC2 use case. Using commands for IAM in the AWS Command Line Interface (AWS CLI) or using the IAM API, create a service-linked role with the ssm.amazonaws.com service name. For more information, see Creating a service- linked role in the IAM User Guide. If you delete this service-linked role, and then need to create it again, you can use the same process to recreate the role in your account. Inventory and Explorer data role 2480 AWS Systems Manager User Guide Editing the AWSServiceRoleForAmazonSSM service-linked role for Systems Manager Systems Manager doesn't allow you to edit the AWSServiceRoleForAmazonSSM service-linked role. After you create a service-linked role, you can't change the name of the role because various entities might reference the role. However, you can edit the description of the role using IAM. For more information, see Editing a service-linked role in the IAM User Guide. Deleting the AWSServiceRoleForAmazonSSM service-linked role for Systems Manager If you no longer need to use any feature or service that requires a service-linked role, then we recommend that you delete that role. That way you don’t have an unused entity that isn't actively monitored or maintained. You can use the IAM console, the AWS CLI, or the IAM API to manually delete the service-linked role. To do this, you must first manually clean up the resources for your service-linked role, and then you can manually delete it. Because the AWSServiceRoleForAmazonSSM service-linked role can be used by multiple tools, ensure that none are using the role before attempting to delete it. • Inventory: If you delete the service-linked role used by the Inventory tool, then the Inventory data for tags and resource groups will no longer be synchronized. You must clean up the resources for your service-linked role before you can manually delete it. • Explorer: If you delete the service-linked role used by the Explorer tool, then the cross-account and cross-Region OpsData and OpsItems are no longer viewable. Note If the Systems Manager service is using the role when you try to delete tags or resource groups, then the deletion might fail. If that happens, wait for a few minutes and try the operation again. To delete Systems Manager resources used by the AWSServiceRoleForAmazonSSM 1. 2. To delete tags, see Add and delete tags on an individual resource. To delete resource groups, see Delete groups from AWS Resource Groups. Inventory and Explorer data role 2481 AWS Systems Manager User Guide To manually delete the AWSServiceRoleForAmazonSSM service-linked role using IAM Use the IAM console, the AWS CLI, or the IAM API to delete the AWSServiceRoleForAmazonSSM service-linked role. For more information, see Deleting a service-linked role in the IAM User Guide. Supported Regions for the Systems Manager AWSServiceRoleForAmazonSSM service-linked role Systems Manager supports using the AWSServiceRoleForAmazonSSM service-linked role in all of the AWS Regions where the service is available. For more information, see AWS Systems Manager endpoints and quotas. Using roles to collect AWS account information for OpsCenter and Explorer Systems Manager uses the service-linked role named AWSServiceRoleForAmazonSSM_AccountDiscovery. AWS Systems Manager uses this IAM service role to call other AWS services to discover AWS account information. Service-linked role permissions for Systems Manager account discovery The AWSServiceRoleForAmazonSSM_AccountDiscovery service-linked role trusts the following services to assume the role: • accountdiscovery.ssm.amazonaws.com The role permissions policy allows Systems Manager to complete the following actions on the specified resources: • organizations:DescribeAccount • organizations:DescribeOrganizationalUnit • organizations:DescribeOrganization • organizations:ListAccounts • organizations:ListAWSServiceAccessForOrganization • organizations:ListChildren • organizations:ListParents OpsCenter and Explorer account discovery role 2482 AWS Systems Manager User Guide • organizations:ListDelegatedServicesForAccount • organizations:ListDelegatedAdministrators • organizations:ListRoots You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. For more information, see Service-linked role permissions in
systems-manager-ug-727
systems-manager-ug.pdf
727
permissions for Systems Manager account discovery The AWSServiceRoleForAmazonSSM_AccountDiscovery service-linked role trusts the following services to assume the role: • accountdiscovery.ssm.amazonaws.com The role permissions policy allows Systems Manager to complete the following actions on the specified resources: • organizations:DescribeAccount • organizations:DescribeOrganizationalUnit • organizations:DescribeOrganization • organizations:ListAccounts • organizations:ListAWSServiceAccessForOrganization • organizations:ListChildren • organizations:ListParents OpsCenter and Explorer account discovery role 2482 AWS Systems Manager User Guide • organizations:ListDelegatedServicesForAccount • organizations:ListDelegatedAdministrators • organizations:ListRoots You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. For more information, see Service-linked role permissions in the IAM User Guide. Creating the AWSServiceRoleForAmazonSSM_AccountDiscovery service- linked role for Systems Manager You must create a service-linked role if you want to use Explorer and OpsCenter, tools in Systems Manager, across multiple AWS accounts. For OpsCenter, you must manually create the service- linked role. For more information, see (Optional) Manually set up OpsCenter to centrally manage OpsItems across accounts. For Explorer, if you create a resource data sync by using Systems Manager in the AWS Management Console, you can create the service-linked role by choosing the Create role button. If you want to create a resource data sync programmatically, then you must create the role before you create the resource data sync. You can create the role by using the CreateServiceLinkedRole API operation. Editing the AWSServiceRoleForAmazonSSM_AccountDiscovery service-linked role for Systems Manager Systems Manager doesn't allow you to edit the AWSServiceRoleForAmazonSSM_AccountDiscovery service-linked role. After you create a service-linked role, you can't change the name of the role because various entities might reference the role. However, you can edit the description of the role using IAM. For more information, see Editing a service-linked role in the IAM User Guide. Deleting the AWSServiceRoleForAmazonSSM_AccountDiscovery service- linked role for Systems Manager If you no longer need to use a feature or service that requires a service-linked role, we recommend that you delete that role. That way you don’t have an unused entity that isn't actively monitored or maintained. However, you must clean up your service-linked role before you can manually delete it. OpsCenter and Explorer account discovery role 2483 AWS Systems Manager User Guide Cleaning up the AWSServiceRoleForAmazonSSM_AccountDiscovery service-linked role Before you can use IAM to delete the AWSServiceRoleForAmazonSSM_AccountDiscovery service-linked role, you must first delete all Explorer resource data syncs. Note If the Systems Manager service is using the role when you try to delete the resources, then the deletion might fail. If that happens, wait for a few minutes and try the operation again. Manually delete the AWSServiceRoleForAmazonSSM_AccountDiscovery service-linked role Use the IAM console, the AWS CLI, or the AWS API to delete the AWSServiceRoleForAmazonSSM_AccountDiscovery service-linked role. For more information, see Deleting a service-linked role in the IAM User Guide. Supported Regions for the Systems Manager AWSServiceRoleForAmazonSSM_AccountDiscovery service-linked role Systems Manager supports using service-linked roles in all of the regions where the service is available. For more information, see AWS Systems Manager endpoints and quotas. Updates to the AWSServiceRoleForAmazonSSM_AccountDiscovery service-linked role View details about updates to the AWSServiceRoleForAmazonSSM_AccountDiscovery service-linked role since this service began tracking these changes. For automatic alerts about changes to this page, subscribe to the RSS feed on the Systems Manager Document history page. Change Description Date New permissions added This service-linked role October 17, 2022 now includes organizat ions:DescribeOrgan and izationalUnit organizations:List Roots permissions. These permissions enable an AWS OpsCenter and Explorer account discovery role 2484 AWS Systems Manager User Guide Change Description Date Organizations managemen t account or a Systems Manager delegated administr ator account to work with OpsItems across accounts. For more information, see (Optional) Manually set up OpsCenter to centrally manage OpsItems across accounts. Using roles to create OpsData and OpsItems for Explorer Systems Manager uses the service-linked role named AWSServiceRoleForSystemsManagerOpsDataSync. AWS Systems Manager uses this IAM service role for Explorer to create OpsData and OpsItems. Service-linked role permissions for Systems Manager OpsData sync The AWSServiceRoleForSystemsManagerOpsDataSync service-linked role trusts the following services to assume the role: • opsdatasync.ssm.amazonaws.com The role permissions policy allows Systems Manager to complete the following actions on the specified resources: • Systems Manager Explorer requires that a service-linked role grant permission to update a security finding when an OpsItem is updated, create and update an OpsItem, and turn off the Security Hub data source when an SSM managed rule is deleted by customers. The managed policy that is used to provide permissions for the AWSServiceRoleForSystemsManagerOpsDataSync role is AWSSystemsManagerOpsDataSyncServiceRolePolicy. For details about the permissions it grants, see AWS managed policy: AWSSystemsManagerOpsDataSyncServiceRolePolicy. OpsData and OpsItems creation role 2485 AWS Systems Manager User Guide You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. For more information, see Service-linked role permissions in the IAM User Guide. Creating the AWSServiceRoleForSystemsManagerOpsDataSync service-linked role
systems-manager-ug-728
systems-manager-ug.pdf
728
and update an OpsItem, and turn off the Security Hub data source when an SSM managed rule is deleted by customers. The managed policy that is used to provide permissions for the AWSServiceRoleForSystemsManagerOpsDataSync role is AWSSystemsManagerOpsDataSyncServiceRolePolicy. For details about the permissions it grants, see AWS managed policy: AWSSystemsManagerOpsDataSyncServiceRolePolicy. OpsData and OpsItems creation role 2485 AWS Systems Manager User Guide You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. For more information, see Service-linked role permissions in the IAM User Guide. Creating the AWSServiceRoleForSystemsManagerOpsDataSync service-linked role for Systems Manager You don't need to manually create a service-linked role. When you enable Explorer in the AWS Management Console, Systems Manager creates the service-linked role for you. Important This service-linked role can be displayed in your account if you completed an action in another service that uses the features supported by this role. Also, if you were using the Systems Manager service before January 1, 2017, when it began supporting service-linked roles, then Systems Manager created the AWSServiceRoleForSystemsManagerOpsDataSync role in your account. To learn more, see A new role appeared in my IAM account. If you delete this service-linked role, and then need to create it again, you can use the same process to recreate the role in your account. When you enable Explorer in the AWS Management Console, Systems Manager creates the service-linked role for you again. You can also use the IAM console to create a service-linked role with the AWS service role that allows Explorer to create OpsData and OpsItems use case. In the AWS CLI or the AWS API, create a service-linked role with the opsdatasync.ssm.amazonaws.com service name. For more information, see Creating a service-linked role in the IAM User Guide. If you delete this service- linked role, you can use this same process to create the role again. Editing the AWSServiceRoleForSystemsManagerOpsDataSync service-linked role for Systems Manager Systems Manager doesn't allow you to edit the AWSServiceRoleForSystemsManagerOpsDataSync service-linked role. After you create a service-linked role, you can't change the name of the role because various entities might reference the role. However, you can edit the description of the role using IAM. For more information, see Editing a service-linked role in the IAM User Guide. OpsData and OpsItems creation role 2486 AWS Systems Manager User Guide Deleting the AWSServiceRoleForSystemsManagerOpsDataSync service-linked role for Systems Manager If you no longer need to use a feature or service that requires a service-linked role, we recommend that you delete that role. That way you don’t have an unused entity that isn't actively monitored or maintained. However, you must clean up the resources for your service-linked role before you can manually delete it. Note If the Systems Manager service is using the role when you try to delete the resources, then the deletion might fail. If that happens, wait for a few minutes and try the operation again. The procedure for deleting Systems Manager resources used by the AWSServiceRoleForSystemsManagerOpsDataSync role depends on if you've configured Explorer or OpsCenter to integrate with Security Hub. To delete Systems Manager resources used by the AWSServiceRoleForSystemsManagerOpsDataSync role • To stop Explorer from creating new OpsItems for Security Hub findings, see How to stop receiving findings. • To stop OpsCenter from creating new OpsItems for Security Hub findings, see To manually delete the AWSServiceRoleForSystemsManagerOpsDataSync service-linked role using IAM Use the IAM console, the AWS CLI, or the AWS API to delete the AWSServiceRoleForSystemsManagerOpsDataSync service-linked role. For more information, see Deleting a service-linked role in the IAM User Guide. Supported Regions for the Systems Manager AWSServiceRoleForSystemsManagerOpsDataSync service-linked role Systems Manager supports using service-linked roles in all of the Regions where the service is available. For more information, see AWS Systems Manager endpoints and quotas. OpsData and OpsItems creation role 2487 AWS Systems Manager User Guide Systems Manager doesn't support using service-linked roles in every Region where the service is available. You can use the AWSServiceRoleForSystemsManagerOpsDataSync role in the following Regions. AWS Region name Region identity Support in Systems Manager US East (N. Virginia) US East (Ohio) US West (N. California) US West (Oregon) Asia Pacific (Mumbai) Asia Pacific (Osaka) Asia Pacific (Seoul) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific (Tokyo) Canada (Central) Europe (Frankfurt) Europe (Ireland) Europe (London) Europe (Paris) Europe (Stockholm) South America (São Paulo) us-east-1 us-east-2 us-west-1 us-west-2 ap-south-1 ap-northeast-3 ap-northeast-2 ap-southeast-1 ap-southeast-2 ap-northeast-1 ca-central-1 eu-central-1 eu-west-1 eu-west-2 eu-west-3 eu-north-1 sa-east-1 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes OpsData and OpsItems creation role 2488 AWS Systems Manager User Guide AWS Region name Region identity Support in Systems Manager AWS GovCloud (US) us-gov-west-1 No Using roles to create operational insight OpsItems in Systems Manager OpsCenter Systems Manager uses the service-linked role named AWSServiceRoleForAmazonSSM_OpsInsights. AWS Systems
systems-manager-ug-729
systems-manager-ug.pdf
729
(Sydney) Asia Pacific (Tokyo) Canada (Central) Europe (Frankfurt) Europe (Ireland) Europe (London) Europe (Paris) Europe (Stockholm) South America (São Paulo) us-east-1 us-east-2 us-west-1 us-west-2 ap-south-1 ap-northeast-3 ap-northeast-2 ap-southeast-1 ap-southeast-2 ap-northeast-1 ca-central-1 eu-central-1 eu-west-1 eu-west-2 eu-west-3 eu-north-1 sa-east-1 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes OpsData and OpsItems creation role 2488 AWS Systems Manager User Guide AWS Region name Region identity Support in Systems Manager AWS GovCloud (US) us-gov-west-1 No Using roles to create operational insight OpsItems in Systems Manager OpsCenter Systems Manager uses the service-linked role named AWSServiceRoleForAmazonSSM_OpsInsights. AWS Systems Manager uses this IAM service role to create and update operational insight OpsItems in Systems Manager OpsCenter. AWSServiceRoleForAmazonSSM_OpsInsights service-linked role permissions for Systems Manager operational insight OpsItems The AWSServiceRoleForAmazonSSM_OpsInsights service-linked role trusts the following services to assume the role: • opsinsights.ssm.amazonaws.com The role permissions policy allows Systems Manager to complete the following actions on the specified resources: { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCreateOpsItem", "Effect": "Allow", "Action": [ "ssm:CreateOpsItem", "ssm:AddTagsToResource" ], "Resource": "*" }, { "Sid": "AllowAccessOpsItem", "Effect": "Allow", "Action": [ Operational insights creation role 2489 User Guide AWS Systems Manager "ssm:UpdateOpsItem", "ssm:GetOpsItem" ], "Resource": "*", "Condition": { "StringEquals": { "aws:ResourceTag/SsmOperationalInsight": "true" } } } ] } You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. For more information, see Service-linked role permissions in the IAM User Guide. Creating the AWSServiceRoleForAmazonSSM_OpsInsights service-linked role for Systems Manager You must create a service-linked role. If you enable operational insights by using Systems Manager in the AWS Management Console, you can create the service-linked role by choosing the Enable button. Editing the AWSServiceRoleForAmazonSSM_OpsInsights service-linked role for Systems Manager Systems Manager does not allow you to edit the AWSServiceRoleForAmazonSSM_OpsInsights service-linked role. After you create a service-linked role, you cannot change the name of the role because various entities might reference the role. However, you can edit the description of the role using IAM. For more information, see Editing a service-linked role in the IAM User Guide. Deleting the AWSServiceRoleForAmazonSSM_OpsInsights service-linked role for Systems Manager If you no longer need to use a feature or service that requires a service-linked role, we recommend that you delete that role. That way you don’t have an unused entity that is not actively monitored or maintained. However, you must clean up your service-linked role before you can manually delete it. Operational insights creation role 2490 AWS Systems Manager User Guide Cleaning up the AWSServiceRoleForAmazonSSM_OpsInsights service-linked role Before you can use IAM to delete the AWSServiceRoleForAmazonSSM_OpsInsights service- linked role, you must first deactivate operational insights in Systems Manager OpsCenter. For more information, see Analyzing operational insights to reduce OpsItems. Manually delete the AWSServiceRoleForAmazonSSM_OpsInsights service-linked role Use the IAM console, the AWS CLI, or the AWS API to delete the AWSServiceRoleForAmazonSSM_OpsInsights service-linked role. For more information, see Deleting a service-linked role in the IAM User Guide. Supported Regions for the Systems Manager AWSServiceRoleForAmazonSSM_OpsInsights service-linked role Systems Manager does not support using service-linked roles in every Region where the service is available. You can use the AWSServiceRoleForAmazonSSM_OpsInsights role in the following Regions. Region name Region identity Support in Systems Manager US East (N. Virginia) US East (Ohio) US West (N. California) US West (Oregon) Asia Pacific (Mumbai) Asia Pacific (Tokyo) Asia Pacific (Seoul) Asia Pacific (Singapore) Asia Pacific (Sydney) us-east-1 us-east-2 us-west-1 us-west-2 ap-south-1 ap-northeast-1 ap-northeast-2 ap-southeast-1 ap-southeast-2 Asia Pacific (Hong Kong) ap-east-1 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Operational insights creation role 2491 AWS Systems Manager Region name Canada (Central) Europe (Frankfurt) Europe (Ireland) Europe (London) Europe (Paris) Europe (Stockholm) Europe (Milan) South America (São Paulo) Middle East (Bahrain) Africa (Cape Town) AWS GovCloud (US) AWS GovCloud (US) Region identity Support in Systems Manager User Guide ca-central-1 eu-central-1 eu-west-1 eu-west-2 eu-west-3 eu-north-1 eu-south-1 sa-east-1 me-south-1 af-south-1 us-gov-west-1 us-gov-east-1 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Using roles to maintain Quick Setup-provisioned resource health and consistency Systems Manager uses the service-linked role named AWSServiceRoleForSSMQuickSetup. AWSServiceRoleForSSMQuickSetup service-linked role permissions for Systems Manager The AWSServiceRoleForSSMQuickSetup service-linked role trusts the following services to assume the role: • ssm-quicksetup.amazonaws.com Quick Setup deployment health-check role 2492 AWS Systems Manager User Guide AWS Systems Manager uses this IAM service role to check configuration health, ensure consistent use of parameters and provisioned resources, and remediate resources when drift is detected. The role permissions policy allows Systems Manager to complete the following actions on the specified resources: • ssm (Systems Manager) – Reads information about the state that configured resources are intended to be in, including in delegated administrator accounts. • iam (AWS Identity and Access Management) – This is required for resource data syncs to be accessible across entire organizations in AWS Organizations.
systems-manager-ug-730
systems-manager-ug.pdf
730
Setup deployment health-check role 2492 AWS Systems Manager User Guide AWS Systems Manager uses this IAM service role to check configuration health, ensure consistent use of parameters and provisioned resources, and remediate resources when drift is detected. The role permissions policy allows Systems Manager to complete the following actions on the specified resources: • ssm (Systems Manager) – Reads information about the state that configured resources are intended to be in, including in delegated administrator accounts. • iam (AWS Identity and Access Management) – This is required for resource data syncs to be accessible across entire organizations in AWS Organizations. • organizations (AWS Organizations) – Reads information about the member accounts that belong to an organization as configured in Organizations. • cloudformation (AWS CloudFormation) – Reads information about CloudFormation stacks used to manage the state of resources and CloudFormation stackset operations. The managed policy that is used to provide permissions for the AWSServiceRoleForSSMQuickSetup role is SSMQuickSetupRolePolicy. For details about the permissions it grants, see AWS managed policy: SSMQuickSetupRolePolicy. You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. For more information, see Service-linked role permissions in the IAM User Guide. Creating the AWSServiceRoleForSSMQuickSetup service-linked role for Systems Manager You don't need to manually create the AWSServiceRoleForSSMQuickSetup service-linked role. When you create a Quick Setup configuration in the AWS Management Console, Systems Manager creates the service-linked role for you. Editing the AWSServiceRoleForSSMQuickSetup service-linked role for Systems Manager Systems Manager does not allow you to edit the AWSServiceRoleForSSMQuickSetup service- linked role. After you create a service-linked role, you cannot change the name of the role because various entities might reference the role. However, you can edit the description of the role using IAM. For more information, see Editing a service-linked role in the IAM User Guide. Quick Setup deployment health-check role 2493 AWS Systems Manager User Guide Deleting the AWSServiceRoleForSSMQuickSetup service-linked role for Systems Manager If you no longer need to use a feature or service that requires a service-linked role, we recommend that you delete that role. That way you don’t have an unused entity that is not actively monitored or maintained. However, you must clean up your service-linked role before you can manually delete it. Cleaning up the AWSServiceRoleForSSMQuickSetup service-linked role Before you can use IAM to delete the AWSServiceRoleForSSMQuickSetup service-linked role, you must first delete the Quick Setup configurations that are using the role. For more information, see Editing and deleting your configuration. Manually delete the AWSServiceRoleForSSMQuickSetup service-linked role Use the IAM console, the AWS CLI, or the AWS API to delete the AWSServiceRoleForSSMQuickSetup service-linked role. For more information, see the following topics: • Deleting a service-linked role in the IAM User Guide • delete-configuration-manager in the Quick Setup section of the AWS CLI Reference • DeleteConfigurationManager in the Quick Setup API Reference Supported Regions for the Systems Manager AWSServiceRoleForSSMQuickSetup service-linked role Systems Manager does not support using service-linked roles in every Region where the service is available. You can use the AWSServiceRoleForSSMQuickSetup role in the following Regions. • US East (Ohio) • US East (N. Virginia) • US West (N. California) • US West (Oregon) • Asia Pacific (Mumbai) • Asia Pacific (Seoul) Quick Setup deployment health-check role 2494 User Guide AWS Systems Manager • Asia Pacific (Singapore) • Asia Pacific (Sydney) • Asia Pacific (Tokyo) • Canada (Central) • Europe (Frankfurt) • Europe (Stockholm) • Europe (Ireland) • Europe (London) • Europe (Paris) • South America (São Paulo) Using roles to export Explorer OpsData AWS Systems Manager Explorer uses the AmazonSSMExplorerExportRole service role to export operations data (OpsData) using the AWS-ExportOpsDataToS3 automation runbook. Service-linked role permissions for Explorer The AmazonSSMExplorerExportRole service-linked role trusts only ssm.amazonaws.com to assume this role. You can use the AmazonSSMExplorerExportRole service-linked role to export operations data (OpsData) using the AWS-ExportOpsDataToS3 automation runbook. You can export 5,000 OpsData items from Explorer as a comma separated value (.csv) file to an Amazon Simple Storage Service (Amazon S3) bucket. The role permissions policy allows Systems Manager to complete the following actions on the specified resources: • s3:PutObject • s3:GetBucketAcl • s3:GetBucketLocation • sns:Publish • logs:DescribeLogGroups Export OpsData service role 2495 AWS Systems Manager • logs:DescribeLogStreams • logs:CreateLogGroup • logs:PutLogEvents • logs:CreateLogStream • ssm:GetOpsSummary User Guide You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. For more information, see Service-linked role permissions in the IAM User Guide. Creating the AmazonSSMExplorerExportRole service-linked role for Systems Manager Systems Manager creates the AmazonSSMExplorerExportRole service-linked role when you export OpsData using Explorer in the Systems Manager console. For more information, see Exporting OpsData from Systems Manager Explorer. If you delete this service-linked role, and then need to create it again, you can
systems-manager-ug-731
systems-manager-ug.pdf
731
Manager • logs:DescribeLogStreams • logs:CreateLogGroup • logs:PutLogEvents • logs:CreateLogStream • ssm:GetOpsSummary User Guide You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. For more information, see Service-linked role permissions in the IAM User Guide. Creating the AmazonSSMExplorerExportRole service-linked role for Systems Manager Systems Manager creates the AmazonSSMExplorerExportRole service-linked role when you export OpsData using Explorer in the Systems Manager console. For more information, see Exporting OpsData from Systems Manager Explorer. If you delete this service-linked role, and then need to create it again, you can use the same process to recreate the role in your account. Editing the AmazonSSMExplorerExportRole service-linked role for Systems Manager Systems Manager doesn't allow you to edit the AmazonSSMExplorerExportRole service-linked role. After you create a service-linked role, you can't change the name of the role because various entities might reference the role. However, you can edit the description of the role using IAM. For more information, see Editing a service-linked role in the IAM User Guide. Deleting the AmazonSSMExplorerExportRole service-linked role for Systems Manager If you no longer need to use any feature or service that requires a service-linked role, then we recommend that you delete that role. That way you don’t have an unused entity that isn't actively monitored or maintained. You can use the IAM console, the AWS CLI, or the IAM API to manually delete the service-linked role. To do this, you must first manually clean up the resources for your service-linked role, and then you can manually delete it. Export OpsData service role 2496 AWS Systems Manager Note User Guide If the Systems Manager service is using the role when you try to delete tags or resource groups, then the deletion might fail. If that happens, wait for a few minutes and try the operation again. To delete Systems Manager resources used by the AmazonSSMExplorerExportRole 1. 2. To delete tags, see Add and delete tags on an individual resource. To delete resource groups, see Delete groups from AWS Resource Groups. To manually delete the AmazonSSMExplorerExportRole service-linked role using IAM Use the IAM console, the AWS CLI, or the IAM API to delete the AmazonSSMExplorerExportRole service-linked role. For more information, see Deleting a service-linked role in the IAM User Guide. Supported Regions for the Systems Manager AmazonSSMExplorerExportRole service-linked role Systems Manager supports using the AmazonSSMExplorerExportRole service-linked role in all of the AWS Regions where the service is available. For more information, see AWS Systems Manager endpoints and quotas. Using roles to enable just-in-time node access Systems Manager uses the service-linked role named AWSServiceRoleForSystemsManagerJustInTimeAccess. AWS Systems Manager uses this IAM service role to enable just-in-time node access. Service-linked role permissions for Systems Manager just-in-time node access The AWSServiceRoleForSystemsManagerJustInTimeAccess service-linked role trusts the following services to assume the role: • ssm.amazonaws.com The role permissions policy allows Systems Manager to complete the following actions on the specified resources: Just-in-time node access service role 2497 User Guide AWS Systems Manager • ssm:CreateOpsItem • ssm:GetOpsItem • ssm:UpdateOpsItem • ssm:DescribeOpsItems • ssm:DescribeSessions • ssm:ListTagsForResource • ssm-guiconnect:ListConnections • identitystore:ListGroupMembershipsForMember • identitystore:DescribeUser • identitystore:GetGroupId • identitystore:GetUserId • sso-directory:DescribeUsers • sso-directory:IsMemberInGroup • sso:ListInstances • sso:DescribeRegisteredRegions • sso:ListDirectoryAssociations • ec2:DescribeTags The managed policy that is used to provide permissions for the AWSServiceRoleForSystemsManagerJustInTimeAccess role is AWSSystemsManagerEnableJustInTimeAccessPolicy. For details about the permissions it grants, see AWS managed policy: AWSSystemsManagerJustInTimeAccessServicePolicy. You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. For more information, see Service-linked role permissions in the IAM User Guide. Creating the AWSServiceRoleForSystemsManagerJustInTimeAccess service- linked role for Systems Manager You don't need to manually create a service-linked role. When you enable just-in-time node access in the AWS Management Console, Systems Manager creates the service-linked role for you. Just-in-time node access service role 2498 AWS Systems Manager Important User Guide This service-linked role can be displayed in your account if you completed an action in another service that uses the features supported by this role. Also, if you were using the Systems Manager service before November 19, 2024, when it began supporting service-linked roles, then Systems Manager created the AWSServiceRoleForSystemsManagerJustInTimeAccess role in your account. To learn more, see A new role appeared in my IAM account. If you delete this service-linked role, and then need to create it again, you can use the same process to recreate the role in your account. When you enable just-in-time node access in the AWS Management Console, Systems Manager creates the service-linked role for you again. You can also use the IAM console to create a service-linked role with the AWS service role that allows Systems Manager to enable just-in-time node access. use case. In the AWS CLI or the AWS API, create a service-linked role with the ssm.amazonaws.com service
systems-manager-ug-732
systems-manager-ug.pdf
732
more, see A new role appeared in my IAM account. If you delete this service-linked role, and then need to create it again, you can use the same process to recreate the role in your account. When you enable just-in-time node access in the AWS Management Console, Systems Manager creates the service-linked role for you again. You can also use the IAM console to create a service-linked role with the AWS service role that allows Systems Manager to enable just-in-time node access. use case. In the AWS CLI or the AWS API, create a service-linked role with the ssm.amazonaws.com service name. For more information, see Creating a service-linked role in the IAM User Guide. If you delete this service- linked role, you can use this same process to create the role again. Editing the AWSServiceRoleForSystemsManagerJustInTimeAccess service- linked role for Systems Manager Systems Manager doesn't allow you to edit the AWSServiceRoleForSystemsManagerJustInTimeAccess service-linked role. After you create a service-linked role, you can't change the name of the role because various entities might reference the role. However, you can edit the description of the role using IAM. For more information, see Editing a service-linked role in the IAM User Guide. Deleting the AWSServiceRoleForSystemsManagerJustInTimeAccess service- linked role for Systems Manager If you no longer need to use a feature or service that requires a service-linked role, we recommend that you delete that role. That way you don’t have an unused entity that isn't actively monitored or maintained. However, you must clean up the resources for your service-linked role before you can manually delete it. Just-in-time node access service role 2499 AWS Systems Manager Note User Guide If the Systems Manager service is using the role when you try to delete the resources, then the deletion might fail. If that happens, wait for a few minutes and try the operation again. To manually delete the AWSServiceRoleForSystemsManagerJustInTimeAccess service- linked role using IAM Use the IAM console, the AWS CLI, or the AWS API to delete the AWSServiceRoleForSystemsManagerJustInTimeAccess service-linked role. For more information, see Deleting a service-linked role in the IAM User Guide. Supported Regions for the Systems Manager AWSServiceRoleForSystemsManagerJustInTimeAccess service-linked role AWS Region name Region identity Support in Systems Manager US East (N. Virginia) US East (Ohio) US West (N. California) US West (Oregon) Asia Pacific (Mumbai) Asia Pacific (Osaka) Asia Pacific (Seoul) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific (Tokyo) Canada (Central) us-east-1 us-east-2 us-west-1 us-west-2 ap-south-1 ap-northeast-3 ap-northeast-2 ap-southeast-1 ap-southeast-2 ap-northeast-1 ca-central-1 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Just-in-time node access service role 2500 AWS Systems Manager User Guide AWS Region name Region identity Support in Systems Manager Europe (Frankfurt) eu-central-1 Europe (Ireland) Europe (London) Europe (Paris) Europe (Stockholm) South America (São Paulo) eu-west-1 eu-west-2 eu-west-3 eu-north-1 sa-east-1 AWS GovCloud (US) us-gov-west-1 Yes Yes Yes Yes Yes Yes No Using roles to send just-in-time node access request notifications Systems Manager uses the service-linked role named AWSServiceRoleForSystemsManagerNotifications. AWS Systems Manager uses this IAM service role to send notifications to access request approvers. Service-linked role permissions for Systems Manager just-in-time node access notifications The AWSServiceRoleForSystemsManagerNotifications service-linked role trusts the following services to assume the role: • ssm.amazonaws.com The role permissions policy allows Systems Manager to complete the following actions on the specified resources: • identitystore:ListGroupMembershipsForMember • identitystore:ListGroupMemberships • identitystore:DescribeUser • sso:ListInstances Just-in-time node access request notifications service role 2501 AWS Systems Manager User Guide • sso:DescribeRegisteredRegions • sso:ListDirectoryAssociations • sso-directory:DescribeUser • sso-directory:ListMembersInGroup • iam:GetRole The managed policy that is used to provide permissions for the AWSServiceRoleForSystemsManagerNotifications role is AWSSystemsManagerNotificationsServicePolicy. For details about the permissions it grants, see AWS managed policy: AWSSystemsManagerNotificationsServicePolicy. You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. For more information, see Service-linked role permissions in the IAM User Guide. Creating the AWSServiceRoleForSystemsManagerNotifications service- linked role for Systems Manager You don't need to manually create a service-linked role. When you enable just-in-time node access in the AWS Management Console, Systems Manager creates the service-linked role for you. Important This service-linked role can be displayed in your account if you completed an action in another service that uses the features supported by this role. Also, if you were using the Systems Manager service before November 19, 2024, when it began supporting service-linked roles, then Systems Manager created the AWSServiceRoleForSystemsManagerNotifications role in your account. To learn more, see A new role appeared in my IAM account. If you delete this service-linked role, and then need to create it again, you can use the same process to recreate the role in your account. When you enable just-in-time node access in the AWS Management Console, Systems Manager creates the service-linked role for you again. You can also use the IAM console to create a service-linked role with
systems-manager-ug-733
systems-manager-ug.pdf
733
Also, if you were using the Systems Manager service before November 19, 2024, when it began supporting service-linked roles, then Systems Manager created the AWSServiceRoleForSystemsManagerNotifications role in your account. To learn more, see A new role appeared in my IAM account. If you delete this service-linked role, and then need to create it again, you can use the same process to recreate the role in your account. When you enable just-in-time node access in the AWS Management Console, Systems Manager creates the service-linked role for you again. You can also use the IAM console to create a service-linked role with the AWS service role that allows Systems Manager to send notifications to access request approvers. use case. In the AWS Just-in-time node access request notifications service role 2502 AWS Systems Manager User Guide CLI or the AWS API, create a service-linked role with the ssm.amazonaws.com service name. For more information, see Creating a service-linked role in the IAM User Guide. If you delete this service-linked role, you can use this same process to create the role again. Editing the AWSServiceRoleForSystemsManagerNotifications service- linked role for Systems Manager Systems Manager doesn't allow you to edit the AWSServiceRoleForSystemsManagerNotifications service-linked role. After you create a service-linked role, you can't change the name of the role because various entities might reference the role. However, you can edit the description of the role using IAM. For more information, see Editing a service-linked role in the IAM User Guide. Deleting the AWSServiceRoleForSystemsManagerNotifications service- linked role for Systems Manager If you no longer need to use a feature or service that requires a service-linked role, we recommend that you delete that role. That way you don’t have an unused entity that isn't actively monitored or maintained. However, you must clean up the resources for your service-linked role before you can manually delete it. Note If the Systems Manager service is using the role when you try to delete the resources, then the deletion might fail. If that happens, wait for a few minutes and try the operation again. To manually delete the AWSServiceRoleForSystemsManagerNotifications service-linked role using IAM Use the IAM console, the AWS CLI, or the AWS API to delete the AWSServiceRoleForSystemsManagerNotifications service-linked role. For more information, see Deleting a service-linked role in the IAM User Guide. Just-in-time node access request notifications service role 2503 AWS Systems Manager User Guide Supported Regions for the Systems Manager AWSServiceRoleForSystemsManagerNotifications service-linked role AWS Region name Region identity Support in Systems Manager US East (N. Virginia) US East (Ohio) US West (N. California) US West (Oregon) Asia Pacific (Mumbai) Asia Pacific (Osaka) Asia Pacific (Seoul) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific (Tokyo) Canada (Central) Europe (Frankfurt) Europe (Ireland) Europe (London) Europe (Paris) Europe (Stockholm) South America (São Paulo) us-east-1 us-east-2 us-west-1 us-west-2 ap-south-1 ap-northeast-3 ap-northeast-2 ap-southeast-1 ap-southeast-2 ap-northeast-1 ca-central-1 eu-central-1 eu-west-1 eu-west-2 eu-west-3 eu-north-1 sa-east-1 AWS GovCloud (US) us-gov-west-1 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes No Just-in-time node access request notifications service role 2504 AWS Systems Manager User Guide Logging and monitoring in AWS Systems Manager Monitoring is an important part of maintaining the reliability, availability, and performance of AWS Systems Manager and your AWS solutions. You should collect monitoring data from all of the parts of your AWS solution so that you can more debug a multi-point failure if one occurs. AWS provides several tools for monitoring your Systems Manager and other resources and responding to potential incidents. AWS CloudTrail logs CloudTrail provides a record of actions taken by a user, role, or an AWS service in Systems Manager. Using the information collected by CloudTrail, you can determine the request that was made to Systems Manager, the IP address from which the request was made, who made the request, when it was made, and additional details. For more information, see Logging AWS Systems Manager API calls with AWS CloudTrail. Amazon CloudWatch alarms Using Amazon CloudWatch alarms, you watch a single metric over a time period that you specify for your Amazon Elastic Compute Cloud (Amazon EC2) instances and other resources. If the metric exceeds a given threshold, a notification is sent to an Amazon Simple Notification Service (Amazon SNS) topic or AWS Auto Scaling policy. CloudWatch alarms don't invoke actions because they're in a particular state. Rather the state must have changed and been maintained for a specified number of periods. For more information, see Using Amazon CloudWatch alarms in the Amazon CloudWatch User Guide. Amazon CloudWatch dashboards CloudWatch dashboards are customizable home pages in the CloudWatch console that you can use to monitor your resources in a single view, even those resources that are spread across different AWS Regions. You can use CloudWatch dashboards to create customized views of the metrics and alarms for your AWS resources.
systems-manager-ug-734
systems-manager-ug.pdf
734
SNS) topic or AWS Auto Scaling policy. CloudWatch alarms don't invoke actions because they're in a particular state. Rather the state must have changed and been maintained for a specified number of periods. For more information, see Using Amazon CloudWatch alarms in the Amazon CloudWatch User Guide. Amazon CloudWatch dashboards CloudWatch dashboards are customizable home pages in the CloudWatch console that you can use to monitor your resources in a single view, even those resources that are spread across different AWS Regions. You can use CloudWatch dashboards to create customized views of the metrics and alarms for your AWS resources. For more information, see Using Amazon CloudWatch dashboards hosted by Systems Manager. Amazon EventBridge Using Amazon EventBridge, you can configure rules to alert you to changes in Systems Manager resources, and to direct EventBridge to take actions based on the content of those events. EventBridge provides support for a number of events that are emitted by various Systems Manager tools. For more information, see Monitoring Systems Manager events with Amazon EventBridge. Logging and monitoring 2505 AWS Systems Manager User Guide Amazon CloudWatch Logs and SSM Agent logs SSM Agent writes information about executions, scheduled actions, errors, and health statuses to log files on each node. You can view log files by manually connecting to a node. We recommend automatically sending agent log data to a log group in CloudWatch Logs for analysis. For more information, see Sending node logs to unified CloudWatch Logs (CloudWatch agent) and Viewing SSM Agent logs. AWS Systems Manager Compliance You can use Compliance, a tool in AWS Systems Manager, to scan your fleet of managed nodes for patch compliance and configuration inconsistencies. You can collect and aggregate data from multiple AWS accounts and AWS Regions, and then drill down into specific resources that aren’t compliant. By default, Compliance displays current compliance data about patching in Patch Manager, a tool in AWS Systems Manager, and associations in State Manager, a tool in AWS Systems Manager. For more information, see AWS Systems Manager Compliance. AWS Systems Manager Explorer Explorer, a tool in AWS Systems Manager, is a customizable operations dashboard that reports information about your AWS resources. Explorer displays an aggregated view of operations data (OpsData) for your AWS accounts and across AWS Regions. In Explorer, OpsData includes metadata about your EC2 instances, patch compliance details, and operational work items (OpsItems). Explorer provides context about how OpsItems are distributed across your business units or applications, how they trend over time, and how they vary by category. You can group and filter information in Explorer to focus on items that are relevant to you and that require action. For more information, see AWS Systems Manager Explorer. AWS Systems Manager OpsCenter OpsCenter, a tool in AWS Systems Manager, provides a central location where operations engineers and IT professionals can view, investigate, and resolve operational work items (OpsItems) related to AWS resources. OpsCenter aggregates and standardizes OpsItems across services while providing contextual investigation data about each OpsItem, related OpsItems, and related resources. OpsCenter also provides runbooks in Automation, a tool in AWS Systems Manager, that you can use to quickly resolve issues. OpsCenter is integrated with Amazon EventBridge. This means you can create EventBridge rules that automatically create OpsItems for any AWS service that publishes events to EventBridge. For more information, see AWS Systems Manager OpsCenter. Logging and monitoring 2506 AWS Systems Manager User Guide Amazon Simple Notification Service You can configure Amazon Simple Notification Service (Amazon SNS) to send notifications about the status of commands that you send using Run Command or Maintenance Windows, tools in AWS Systems Manager. Amazon SNS coordinates and manages sending and delivering notifications to clients or endpoints that are subscribed to Amazon SNS topics. You can receive a notification whenever a command changes to a new state or to a specific state, such as Failed or Timed Out. In cases where you send a command to multiple nodes, you can receive a notification for each copy of the command sent to a specific node. For more information, see Monitoring Systems Manager status changes using Amazon SNS notifications. AWS Trusted Advisor and AWS Health Dashboard Trusted Advisor draws upon best practices learned from serving hundreds of thousands of AWS customers. Trusted Advisor inspects your AWS environment and then makes recommendations when opportunities exist to save money, improve system availability and performance, or help close security gaps. All AWS customers have access to five Trusted Advisor checks. Customers with either an AWS Support Business or Enterprise plan can view all Trusted Advisor checks. For more information, see AWS Trusted Advisor in the AWS Support User Guide and the AWS Health User Guide. More info • Logging and monitoring in AWS Systems Manager Compliance validation for AWS Systems Manager This topic addresses AWS Systems Manager compliance with
systems-manager-ug-735
systems-manager-ug.pdf
735
of thousands of AWS customers. Trusted Advisor inspects your AWS environment and then makes recommendations when opportunities exist to save money, improve system availability and performance, or help close security gaps. All AWS customers have access to five Trusted Advisor checks. Customers with either an AWS Support Business or Enterprise plan can view all Trusted Advisor checks. For more information, see AWS Trusted Advisor in the AWS Support User Guide and the AWS Health User Guide. More info • Logging and monitoring in AWS Systems Manager Compliance validation for AWS Systems Manager This topic addresses AWS Systems Manager compliance with third-party assurance programs. For information about viewing compliance data for your managed nodes, see AWS Systems Manager Compliance. Third-party auditors assess the security and compliance of Systems Manager as part of multiple AWS compliance programs. These include SOC, PCI, FedRAMP, HIPAA, and others. For a list of AWS services in scope of specific compliance programs, see AWS Services in Scope by Compliance Program. For general information, see AWS Compliance Programs. You can download third-party audit reports using AWS Artifact. For more information, see Downloading reports in AWS Artifact. Compliance validation 2507 AWS Systems Manager User Guide Your compliance responsibility when using Systems Manager is determined by the sensitivity of your data, your company's compliance objectives, and applicable laws and regulations. AWS provides the following resources to help with compliance: • Security and Compliance Quick Start Guides – These deployment guides discuss architectural considerations and provide steps for deploying security- and compliance-focused baseline environments on AWS. • Architecting for HIPAA Security and Compliance Whitepaper – This whitepaper describes how companies can use AWS to create HIPAA-compliant applications. • AWS Compliance Resources – This collection of workbooks and guides might apply to your industry and location. • Evaluating Resources with Rules in the AWS Config Developer Guide – The AWS Config service assesses how well your resource configurations comply with internal practices, industry guidelines, and regulations. • AWS Security Hub – This AWS service provides a comprehensive view of your security state within AWS that helps you check your compliance with security industry standards and best practices. Resilience in AWS Systems Manager The AWS global infrastructure is built around AWS Regions and Availability Zones. AWS Regions provide multiple physically separated and isolated Availability Zones, which are connected with low-latency, high-throughput, and highly redundant networking. With Availability Zones, you can design and operate applications and databases that automatically fail over between zones without interruption. Availability Zones are more highly available, fault tolerant, and scalable than traditional single or multiple data center infrastructures. For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure. Infrastructure security in AWS Systems Manager As a managed service, AWS Systems Manager is protected by AWS global network security. For information about AWS security services and how AWS protects infrastructure, see AWS Cloud Security. To design your AWS environment using the best practices for infrastructure security, see Infrastructure Protection in Security Pillar AWS Well‐Architected Framework. You use AWS published API calls to access Systems Manager through the network. Clients must support the following: Resilience 2508 AWS Systems Manager User Guide • Transport Layer Security (TLS). We require TLS 1.2 and recommend TLS 1.3. • Cipher suites with perfect forward secrecy (PFS) such as DHE (Ephemeral Diffie-Hellman) or ECDHE (Elliptic Curve Ephemeral Diffie-Hellman). Most modern systems such as Java 7 and later support these modes. Additionally, requests must be signed by using an access key ID and a secret access key that is associated with an IAM principal. Or you can use the AWS Security Token Service (AWS STS) to generate temporary security credentials to sign requests. Configuration and vulnerability analysis in AWS Systems Manager AWS handles basic security tasks such as firewall configuration and disaster recovery. These procedures have been reviewed and certified by the appropriate third parties. For more details, see the following resources: • Compliance validation for AWS Systems Manager • Shared Responsibility Model • Best Practices for Security, Identity, & Compliance Security best practices for Systems Manager AWS Systems Manager provides a number of security features to consider as you develop and implement your own security policies. The following best practices are general guidelines and don’t represent a complete security solution. Because these best practices might not be appropriate or sufficient for your environment, treat them as helpful considerations rather than prescriptions. Topics • Systems Manager preventative security best practices • Systems Manager monitoring and auditing best practices Systems Manager preventative security best practices The following best practices for Systems Manager can help prevent security incidents. Configuration and vulnerability analysis 2509 AWS Systems Manager Implement least privilege access User Guide When granting permissions, you decide who is getting what permissions to which Systems Manager resources. You allow specific actions that you want to allow
systems-manager-ug-736
systems-manager-ug.pdf
736
and don’t represent a complete security solution. Because these best practices might not be appropriate or sufficient for your environment, treat them as helpful considerations rather than prescriptions. Topics • Systems Manager preventative security best practices • Systems Manager monitoring and auditing best practices Systems Manager preventative security best practices The following best practices for Systems Manager can help prevent security incidents. Configuration and vulnerability analysis 2509 AWS Systems Manager Implement least privilege access User Guide When granting permissions, you decide who is getting what permissions to which Systems Manager resources. You allow specific actions that you want to allow on those resources. Therefore you should grant only the permissions that are required to perform a task. Implementing least privilege access is fundamental in reducing security risk and the impact that could result from errors or malicious intent. The following tools are available to implement least privilege access: • IAM policies and Permissions boundaries for IAM entities • Service control policies Use recommended settings for SSM Agent when configured to use a proxy If you configure SSM Agent to use a proxy, use the no_proxy variable with the IP address of the Systems Manager instance metadata service to ensure that calls to Systems Manager don't take on the identity of the proxy service. 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. Use SecureString parameters to encrypt and protect secret data In Parameter Store, a tool in AWS Systems Manager, a SecureString parameter is any sensitive data that needs to be stored and referenced in a secure manner. If you have data that you don't want users to alter or reference in plaintext, such as passwords or license keys, create those parameters using the SecureString data type. Parameter Store uses an AWS KMS key in AWS Key Management Service (AWS KMS) to encrypt the parameter value. AWS KMS uses either a customer managed key or an AWS managed key when encrypting the parameter value. For maximum security, we recommend using your own KMS key. If you use the AWS managed key, any user with permission to run the GetParameter and GetParameters actions in your account can view or retrieve the content of all SecureString parameters. If you're using customer managed keys to encrypt your secure SecureString values, you can use IAM policies and key policies to manage permissions for encrypting and decrypting parameters. It's more difficult to establish access control policies for these operations when using an AWS managed key. For example, you if you use an AWS managed key to encrypt SecureString parameters and don't want users to work with SecureString parameters, the user's IAM policies must explicitly deny access to the default key. Systems Manager preventative security best practices 2510 AWS Systems Manager User Guide For more information, see Restricting access to Parameter Store parameters using IAM policies and How AWS Systems Manager Parameter Store Uses AWS KMS in the AWS Key Management Service Developer Guide. Define allowedValues and allowedPattern for document parameters You can validate user input for parameters in Systems Manager documents (SSM documents) by defining allowedValues and allowedPattern. For allowedValues, you define an array of values allowed for the parameter. If a user inputs a value that isn't allowed, the execution fails to start. For allowedPattern, you define a regular expression that validates whether the user input matches the defined pattern for the parameter. If the user input doesn't match the allowed pattern, the execution fails to start. For more information about allowedValues and allowedPattern, see Data elements and parameters. Block public sharing for documents Unless your use case requires public sharing to be allowed, we recommend turning on the block public sharing setting for your SSM documents in the Preferences section of the Systems Manager Documents console. Use an Amazon Virtual Private Cloud (Amazon VPC) and VPC endpoints You can use Amazon VPC to launch AWS resources into a virtual network that you've defined. This virtual network closely resembles a traditional network that you'd operate in your own data center, with the benefits of using the scalable infrastructure of AWS. By implementing a VPC endpoint, you can privately connect your VPC to supported AWS services and VPC endpoint services powered by AWS PrivateLink without requiring an internet gateway, NAT device, VPN connection, or AWS Direct Connect connection. Instances in your VPC don't require public IP addresses to communicate with resources in the service. Traffic between your VPC and the other service doesn't leave the Amazon network. For more information about Amazon VPC security, see Improve the security of EC2 instances by using VPC endpoints for Systems Manager and Internetwork traffic privacy in Amazon VPC in the Amazon VPC User Guide. Restrict Session Manager users to sessions using
systems-manager-ug-737
systems-manager-ug.pdf
737
privately connect your VPC to supported AWS services and VPC endpoint services powered by AWS PrivateLink without requiring an internet gateway, NAT device, VPN connection, or AWS Direct Connect connection. Instances in your VPC don't require public IP addresses to communicate with resources in the service. Traffic between your VPC and the other service doesn't leave the Amazon network. For more information about Amazon VPC security, see Improve the security of EC2 instances by using VPC endpoints for Systems Manager and Internetwork traffic privacy in Amazon VPC in the Amazon VPC User Guide. Restrict Session Manager users to sessions using interactive commands and specific SSM session documents Session Manager, a tool in AWS Systems Manager, provides several methods for starting sessions to your managed nodes. For the most secure connections, you can require users to Systems Manager preventative security best practices 2511 AWS Systems Manager User Guide connect using the interactive commands method to limit user interaction to a specific command or command sequence. This helps you manage the interactive actions a user can take. For more information, see Starting a session (interactive and noninteractive commands). For added security, you can limit Session Manager access to specific Amazon EC2 instances and specific Session Manager session documents. You grant or revoke Session Manager access in this way by using AWS Identity and Access Management (IAM) policies. For more information, see Step 3: Control session access to managed nodes. Provide temporary node permissions for Automation workflows During a workflow in Automation, a tool in AWS Systems Manager, your nodes might need permissions that are needed for that execution only but not for other Systems Manager operations. For example, an Automation workflow might require a node to call a particular API operation or access an AWS resource specifically during the workflow. If these calls or resources are ones that you want to limit access to, you can provide temporary, supplemental permissions for your nodes within the Automation runbook itself instead of adding the permissions to your IAM instance profile. At the end of the Automation workflow, the temporary permissions are removed. For more information, see Providing temporary instance permissions with AWS Systems Manager Automations on the AWS Management and Governance Blog. Keep AWS and Systems Manager tools up to date AWS regularly releases updated versions of tools and plugins that you can use in your AWS and Systems Manager operations. Keeping these resources up to date ensures that users and nodes in your account have access to the latest functionality and security features in these tools. • SSM Agent – AWS Systems Manager Agent (SSM Agent) is Amazon software that can be installed and configured on an Amazon Elastic Compute Cloud (Amazon EC2) instance, an on-premises server, or a virtual machine (VM). SSM Agent makes it possible for Systems Manager to update, manage, and configure these resources. We recommend checking for new versions, or automating updates to the agent, at least every two weeks. For information, see Automating updates to SSM Agent. We also recommend verifying the signature of SSM Agent as part of your update process. For information, see Verifying the signature of SSM Agent. • AWS CLI – The AWS Command Line Interface (AWS CLI) is an open source tool that allows you to interact with AWS services using commands in your command-line shell. To update the AWS CLI, you run the same command used to install the AWS CLI. We recommend creating a scheduled task on your local machine to run the command appropriate to your operating system at least once every two weeks. For information about installation commands, see Installing the AWS CLI version 2 in the AWS Command Line Interface User Guide. Systems Manager preventative security best practices 2512 AWS Systems Manager User Guide • AWS Tools for Windows PowerShell – The Tools for Windows PowerShell are a set of PowerShell modules that are built on the functionality exposed by the AWS SDK for .NET. The AWS Tools for Windows PowerShell allow you to script operations on your AWS resources from the PowerShell command line. Periodically, as updated versions of the Tools for Windows PowerShell are released, you should update the version that you're running locally. For information, see Updating the AWS Tools for Windows PowerShell on Windows or Updating the AWS Tools for Windows PowerShell on Linux or macOS in the IAM Policy Simulator User Guide. • Session Manager plugin – If users in your organization with permissions to use Session Manager want to connect to a node using the AWS CLI, they must first install the Session Manager plugin on their local machines. To update the plugin, you run the same command used to install the plugin. We recommend creating a scheduled task on your local machine to run the command appropriate to your operating system
systems-manager-ug-738
systems-manager-ug.pdf
738
see Updating the AWS Tools for Windows PowerShell on Windows or Updating the AWS Tools for Windows PowerShell on Linux or macOS in the IAM Policy Simulator User Guide. • Session Manager plugin – If users in your organization with permissions to use Session Manager want to connect to a node using the AWS CLI, they must first install the Session Manager plugin on their local machines. To update the plugin, you run the same command used to install the plugin. We recommend creating a scheduled task on your local machine to run the command appropriate to your operating system at least once every two weeks. For information, see Install the Session Manager plugin for the AWS CLI. • CloudWatch agent – You can configure and use the CloudWatch agent to collect metrics and logs from your EC2 instances, on-premises instances, and virtual machines (VMs). These logs can be sent to Amazon CloudWatch Logs for monitoring and analysis. We recommend checking for new versions, or automating updates to the agent, at least every two weeks. For the simplest updates, use AWS Systems Manager Quick Setup. For information, see AWS Systems Manager Quick Setup. Systems Manager monitoring and auditing best practices The following best practices for Systems Manager can help detect potential security weaknesses and incidents. Identify and audit all your Systems Manager resources Identification of your IT assets is a crucial aspect of governance and security. You need to identify all of your Systems Manager resources to assess their security posture and take action on potential areas of weakness. Use Tag Editor to identify security-sensitive or audit-sensitive resources, then use those tags when you need to search for these resources. For more information, see Find resources to tag in the AWS Resource Groups User Guide. Create resource groups for your Systems Manager resources. For more information, see What are resource groups? Systems Manager monitoring and auditing best practices 2513 AWS Systems Manager User Guide Implement monitoring using Amazon CloudWatch monitoring tools Monitoring is an important part of maintaining the reliability, security, availability, and performance of Systems Manager and your AWS solutions. Amazon CloudWatch provides several tools and services to help you monitor Systems Manager and your other AWS services. For more information, see Sending node logs to unified CloudWatch Logs (CloudWatch agent) and Monitoring Systems Manager events with Amazon EventBridge. Use CloudTrail AWS CloudTrail provides a record of actions taken by a user, role, or an AWS service in Systems Manager. Using the information collected by CloudTrail, you can determine the request that was made to Systems Manager, the IP address from which the request was made, who made the request, when it was made, and additional details. For more information, see Logging AWS Systems Manager API calls with AWS CloudTrail. Turn on AWS Config AWS Config allows you to assess, audit, and evaluate the configurations of your AWS resources. AWS Config monitors resource configurations, allowing you to evaluate the recorded configurations against the required secure configurations. Using AWS Config, you can review changes in configurations and relationships between AWS resources, investigate detailed resource configuration histories, and determine your overall compliance against the configurations specified in your internal guidelines. This can help you simplify compliance auditing, security analysis, change management, and operational troubleshooting. For more information, see Setting Up AWS Config with the Console in the AWS Config Developer Guide. When specifying the resource types to record, ensure that you include Systems Manager resources. Monitor AWS security advisories You should regularly check security advisories posted in Trusted Advisor for your AWS account. You can do this programmatically using describe-trusted-advisor-checks. Further, actively monitor the primary email address registered to each of your AWS accounts. AWS will contact you, using this email address, about emerging security issues that might affect you. AWS operational issues with broad impact are posted on the AWS Service Health Dashboard. Operational issues are also posted to individual accounts through the Personal Health Dashboard. For more information, see the AWS Health Documentation. Systems Manager monitoring and auditing best practices 2514 AWS Systems Manager More info User Guide • Best Practices for Security, Identity, & Compliance • Getting Started: Follow Security Best Practices as You Configure Your AWS Resources (AWS Security Blog) • Security best practices in IAM • Security best practices in AWS CloudTrail • Security Best Practices for Amazon S3 • Security best practices for AWS Key Management Service Systems Manager monitoring and auditing best practices 2515 AWS Systems Manager User Guide Code examples for Systems Manager using AWS SDKs The following code examples show how to use Systems Manager with an AWS software development kit (SDK). Basics are code examples that show you how to perform the essential operations within a service. Actions are code excerpts from larger programs and must be run in context. While
systems-manager-ug-739
systems-manager-ug.pdf
739
(AWS Security Blog) • Security best practices in IAM • Security best practices in AWS CloudTrail • Security Best Practices for Amazon S3 • Security best practices for AWS Key Management Service Systems Manager monitoring and auditing best practices 2515 AWS Systems Manager User Guide Code examples for Systems Manager using AWS SDKs The following code examples show how to use Systems Manager with an AWS software development kit (SDK). Basics are code examples that show you how to perform the essential operations within a service. Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Get started Hello Systems Manager The following code examples show how to get started using Systems Manager. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ssm.SsmClient; import software.amazon.awssdk.services.ssm.model.DocumentFilter; import software.amazon.awssdk.services.ssm.model.ListDocumentsRequest; import software.amazon.awssdk.services.ssm.model.ListDocumentsResponse; public class HelloSSM { public static void main(String[] args) { final String usage = """ 2516 AWS Systems Manager User Guide Usage: <awsAccount> Where: awsAccount - Your AWS Account number. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String awsAccount = args[0] ; Region region = Region.US_EAST_1; SsmClient ssmClient = SsmClient.builder() .region(region) .build(); listDocuments(ssmClient, awsAccount); } /* This code automatically fetches the next set of results using the `nextToken` and stops once the desired maxResults (20 in this case) have been reached. */ public static void listDocuments(SsmClient ssmClient, String awsAccount) { String nextToken = null; int totalDocumentsReturned = 0; int maxResults = 20; do { ListDocumentsRequest request = ListDocumentsRequest.builder() .documentFilterList( DocumentFilter.builder() .key("Owner") .value(awsAccount) .build() ) .maxResults(maxResults) .nextToken(nextToken) .build(); ListDocumentsResponse response = ssmClient.listDocuments(request); 2517 AWS Systems Manager User Guide response.documentIdentifiers().forEach(identifier -> System.out.println("Document Name: " + identifier.name())); nextToken = response.nextToken(); totalDocumentsReturned += response.documentIdentifiers().size(); } while (nextToken != null && totalDocumentsReturned < maxResults); } } • For API details, see ListDocuments in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { paginateListDocuments, SSMClient } from "@aws-sdk/client-ssm"; // Call ListDocuments and display the result. export const main = async () => { const client = new SSMClient(); const listDocumentsPaginated = []; console.log( "Hello, AWS Systems Manager! Let's list some of your documents:\n", ); try { // The paginate function is a wrapper around the base command. const paginator = paginateListDocuments({ client }, { MaxResults: 5 }); for await (const page of paginator) { listDocumentsPaginated.push(...page.DocumentIdentifiers); } } catch (caught) { console.error(`There was a problem saying hello: ${caught.message}`); throw caught; } for (const { Name, DocumentFormat, CreatedDate } of listDocumentsPaginated) { 2518 AWS Systems Manager User Guide console.log(`${Name} - ${DocumentFormat} - ${CreatedDate}`); } }; // Call function if run directly. import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); } • For API details, see ListDocuments in AWS SDK for JavaScript API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import boto3 from botocore.exceptions import ClientError def hello_systems_manager(ssm_client): """ Use the AWS SDK for Python (Boto3) to create an AWS Systems Manager client and list the first 5 documents in your account. This example uses the default settings specified in your shared credentials and config files. :param ssm_client: A Boto3 AWS Systems Manager Client object. This object wraps the low-level AWS Systems Manager service API. """ print("Hello, AWS Systems Manager! Let's list some of your documents:\n") paginator = ssm_client.get_paginator("list_documents") page_iterator = paginator.paginate(PaginationConfig={"MaxItems": 5}) 2519 AWS Systems Manager User Guide for page in page_iterator: for document in page["DocumentIdentifiers"]: print(f" {document['Name']}") if __name__ == "__main__": try: hello_systems_manager(boto3.client("ssm")) except ClientError as err: print("Hello systems manager had an error.") print(err.response["Error"]["Code"]) print(err.response["Error"]["Message"]) • For API details, see ListDocuments in AWS SDK for Python (Boto3) API Reference. Code examples • Basic examples for Systems Manager using AWS SDKs • Hello Systems Manager • Learn the basics of Systems Manager with an AWS SDK • Actions for Systems Manager using AWS SDKs • Use AddTagsToResource with a CLI • Use CancelCommand with a CLI • Use CreateActivation with a CLI • Use CreateAssociation with a CLI • Use CreateAssociationBatch with a CLI • Use CreateDocument with an AWS SDK or CLI • Use CreateMaintenanceWindow with an AWS SDK or CLI • Use CreateOpsItem with an AWS SDK or CLI • Use CreatePatchBaseline
systems-manager-ug-740
systems-manager-ug.pdf
740
SDK for Python (Boto3) API Reference. Code examples • Basic examples for Systems Manager using AWS SDKs • Hello Systems Manager • Learn the basics of Systems Manager with an AWS SDK • Actions for Systems Manager using AWS SDKs • Use AddTagsToResource with a CLI • Use CancelCommand with a CLI • Use CreateActivation with a CLI • Use CreateAssociation with a CLI • Use CreateAssociationBatch with a CLI • Use CreateDocument with an AWS SDK or CLI • Use CreateMaintenanceWindow with an AWS SDK or CLI • Use CreateOpsItem with an AWS SDK or CLI • Use CreatePatchBaseline with a CLI • Use DeleteActivation with a CLI • Use DeleteAssociation with a CLI • Use DeleteDocument with an AWS SDK or CLI • Use DeleteMaintenanceWindow with an AWS SDK or CLI • Use DeleteOpsItem with an AWS SDK 2520 AWS Systems Manager User Guide • Use DeleteParameter with a CLI • Use DeletePatchBaseline with a CLI • Use DeregisterManagedInstance with a CLI • Use DeregisterPatchBaselineForPatchGroup with a CLI • Use DeregisterTargetFromMaintenanceWindow with a CLI • Use DeregisterTaskFromMaintenanceWindow with a CLI • Use DescribeActivations with a CLI • Use DescribeAssociation with a CLI • Use DescribeAssociationExecutionTargets with a CLI • Use DescribeAssociationExecutions with a CLI • Use DescribeAutomationExecutions with a CLI • Use DescribeAutomationStepExecutions with a CLI • Use DescribeAvailablePatches with a CLI • Use DescribeDocument with a CLI • Use DescribeDocumentPermission with a CLI • Use DescribeEffectiveInstanceAssociations with a CLI • Use DescribeEffectivePatchesForPatchBaseline with a CLI • Use DescribeInstanceAssociationsStatus with a CLI • Use DescribeInstanceInformation with a CLI • Use DescribeInstancePatchStates with a CLI • Use DescribeInstancePatchStatesForPatchGroup with a CLI • Use DescribeInstancePatches with a CLI • Use DescribeMaintenanceWindowExecutionTaskInvocations with a CLI • Use DescribeMaintenanceWindowExecutionTasks with a CLI • Use DescribeMaintenanceWindowExecutions with a CLI • Use DescribeMaintenanceWindowTargets with a CLI • Use DescribeMaintenanceWindowTasks with a CLI • Use DescribeMaintenanceWindows with a CLI • Use DescribeOpsItems with an AWS SDK or CLI • Use DescribeParameters with an AWS SDK or CLI 2521 AWS Systems Manager User Guide • Use DescribePatchBaselines with a CLI • Use DescribePatchGroupState with a CLI • Use DescribePatchGroups with a CLI • Use GetAutomationExecution with a CLI • Use GetCommandInvocation with a CLI • Use GetConnectionStatus with a CLI • Use GetDefaultPatchBaseline with a CLI • Use GetDeployablePatchSnapshotForInstance with a CLI • Use GetDocument with a CLI • Use GetInventory with a CLI • Use GetInventorySchema with a CLI • Use GetMaintenanceWindow with a CLI • Use GetMaintenanceWindowExecution with a CLI • Use GetMaintenanceWindowExecutionTask with a CLI • Use GetParameter with an AWS SDK or CLI • Use GetParameterHistory with a CLI • Use GetParameters with a CLI • Use GetPatchBaseline with a CLI • Use GetPatchBaselineForPatchGroup with a CLI • Use ListAssociationVersions with a CLI • Use ListAssociations with a CLI • Use ListCommandInvocations with an AWS SDK or CLI • Use ListCommands with a CLI • Use ListComplianceItems with a CLI • Use ListComplianceSummaries with a CLI • Use ListDocumentVersions with a CLI • Use ListDocuments with a CLI • Use ListInventoryEntries with a CLI • Use ListResourceComplianceSummaries with a CLI • Use ListTagsForResource with a CLI 2522 AWS Systems Manager User Guide • Use ModifyDocumentPermission with a CLI • Use PutComplianceItems with a CLI • Use PutInventory with a CLI • Use PutParameter with an AWS SDK or CLI • Use RegisterDefaultPatchBaseline with a CLI • Use RegisterPatchBaselineForPatchGroup with a CLI • Use RegisterTargetWithMaintenanceWindow with a CLI • Use RegisterTaskWithMaintenanceWindow with a CLI • Use RemoveTagsFromResource with a CLI • Use SendCommand with an AWS SDK or CLI • Use StartAutomationExecution with a CLI • Use StartSession with a CLI • Use StopAutomationExecution with a CLI • Use UpdateAssociation with a CLI • Use UpdateAssociationStatus with a CLI • Use UpdateDocument with a CLI • Use UpdateDocumentDefaultVersion with a CLI • Use UpdateMaintenanceWindow with an AWS SDK or CLI • Use UpdateManagedInstanceRole with a CLI • Use UpdateOpsItem with an AWS SDK or CLI • Use UpdatePatchBaseline with a CLI Basic examples for Systems Manager using AWS SDKs The following code examples show how to use the basics of AWS Systems Manager with AWS SDKs. Examples • Hello Systems Manager • Learn the basics of Systems Manager with an AWS SDK • Actions for Systems Manager using AWS SDKs Basics • Use AddTagsToResource with a CLI 2523 AWS Systems Manager User Guide • Use CancelCommand with a CLI • Use CreateActivation with a CLI • Use CreateAssociation with a CLI • Use CreateAssociationBatch with a CLI • Use CreateDocument with an AWS SDK or CLI • Use CreateMaintenanceWindow with an AWS SDK or CLI • Use CreateOpsItem with an AWS SDK or CLI • Use CreatePatchBaseline with a CLI • Use DeleteActivation with a CLI • Use DeleteAssociation with a CLI •
systems-manager-ug-741
systems-manager-ug.pdf
741
the basics of Systems Manager with an AWS SDK • Actions for Systems Manager using AWS SDKs Basics • Use AddTagsToResource with a CLI 2523 AWS Systems Manager User Guide • Use CancelCommand with a CLI • Use CreateActivation with a CLI • Use CreateAssociation with a CLI • Use CreateAssociationBatch with a CLI • Use CreateDocument with an AWS SDK or CLI • Use CreateMaintenanceWindow with an AWS SDK or CLI • Use CreateOpsItem with an AWS SDK or CLI • Use CreatePatchBaseline with a CLI • Use DeleteActivation with a CLI • Use DeleteAssociation with a CLI • Use DeleteDocument with an AWS SDK or CLI • Use DeleteMaintenanceWindow with an AWS SDK or CLI • Use DeleteOpsItem with an AWS SDK • Use DeleteParameter with a CLI • Use DeletePatchBaseline with a CLI • Use DeregisterManagedInstance with a CLI • Use DeregisterPatchBaselineForPatchGroup with a CLI • Use DeregisterTargetFromMaintenanceWindow with a CLI • Use DeregisterTaskFromMaintenanceWindow with a CLI • Use DescribeActivations with a CLI • Use DescribeAssociation with a CLI • Use DescribeAssociationExecutionTargets with a CLI • Use DescribeAssociationExecutions with a CLI • Use DescribeAutomationExecutions with a CLI • Use DescribeAutomationStepExecutions with a CLI • Use DescribeAvailablePatches with a CLI • Use DescribeDocument with a CLI • Use DescribeDocumentPermission with a CLI • Use DescribeEffectiveInstanceAssociations with a CLI Basics • Use DescribeEffectivePatchesForPatchBaseline with a CLI 2524 AWS Systems Manager User Guide • Use DescribeInstanceAssociationsStatus with a CLI • Use DescribeInstanceInformation with a CLI • Use DescribeInstancePatchStates with a CLI • Use DescribeInstancePatchStatesForPatchGroup with a CLI • Use DescribeInstancePatches with a CLI • Use DescribeMaintenanceWindowExecutionTaskInvocations with a CLI • Use DescribeMaintenanceWindowExecutionTasks with a CLI • Use DescribeMaintenanceWindowExecutions with a CLI • Use DescribeMaintenanceWindowTargets with a CLI • Use DescribeMaintenanceWindowTasks with a CLI • Use DescribeMaintenanceWindows with a CLI • Use DescribeOpsItems with an AWS SDK or CLI • Use DescribeParameters with an AWS SDK or CLI • Use DescribePatchBaselines with a CLI • Use DescribePatchGroupState with a CLI • Use DescribePatchGroups with a CLI • Use GetAutomationExecution with a CLI • Use GetCommandInvocation with a CLI • Use GetConnectionStatus with a CLI • Use GetDefaultPatchBaseline with a CLI • Use GetDeployablePatchSnapshotForInstance with a CLI • Use GetDocument with a CLI • Use GetInventory with a CLI • Use GetInventorySchema with a CLI • Use GetMaintenanceWindow with a CLI • Use GetMaintenanceWindowExecution with a CLI • Use GetMaintenanceWindowExecutionTask with a CLI • Use GetParameter with an AWS SDK or CLI • Use GetParameterHistory with a CLI Basics • Use GetParameters with a CLI 2525 AWS Systems Manager User Guide • Use GetPatchBaseline with a CLI • Use GetPatchBaselineForPatchGroup with a CLI • Use ListAssociationVersions with a CLI • Use ListAssociations with a CLI • Use ListCommandInvocations with an AWS SDK or CLI • Use ListCommands with a CLI • Use ListComplianceItems with a CLI • Use ListComplianceSummaries with a CLI • Use ListDocumentVersions with a CLI • Use ListDocuments with a CLI • Use ListInventoryEntries with a CLI • Use ListResourceComplianceSummaries with a CLI • Use ListTagsForResource with a CLI • Use ModifyDocumentPermission with a CLI • Use PutComplianceItems with a CLI • Use PutInventory with a CLI • Use PutParameter with an AWS SDK or CLI • Use RegisterDefaultPatchBaseline with a CLI • Use RegisterPatchBaselineForPatchGroup with a CLI • Use RegisterTargetWithMaintenanceWindow with a CLI • Use RegisterTaskWithMaintenanceWindow with a CLI • Use RemoveTagsFromResource with a CLI • Use SendCommand with an AWS SDK or CLI • Use StartAutomationExecution with a CLI • Use StartSession with a CLI • Use StopAutomationExecution with a CLI • Use UpdateAssociation with a CLI • Use UpdateAssociationStatus with a CLI • Use UpdateDocument with a CLI Basics • Use UpdateDocumentDefaultVersion with a CLI 2526 AWS Systems Manager User Guide • Use UpdateMaintenanceWindow with an AWS SDK or CLI • Use UpdateManagedInstanceRole with a CLI • Use UpdateOpsItem with an AWS SDK or CLI • Use UpdatePatchBaseline with a CLI Hello Systems Manager The following code examples show how to get started using Systems Manager. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ssm.SsmClient; import software.amazon.awssdk.services.ssm.model.DocumentFilter; import software.amazon.awssdk.services.ssm.model.ListDocumentsRequest; import software.amazon.awssdk.services.ssm.model.ListDocumentsResponse; public class HelloSSM { public static void main(String[] args) { final String usage = """ Usage: <awsAccount> Where: awsAccount - Your AWS Account number. """; if (args.length != 1) { System.out.println(usage); System.exit(1); Hello Systems Manager 2527 AWS Systems Manager } User Guide String awsAccount = args[0] ; Region region = Region.US_EAST_1; SsmClient ssmClient = SsmClient.builder() .region(region) .build(); listDocuments(ssmClient, awsAccount); } /* This code automatically fetches the next set of results using the `nextToken` and stops once the desired maxResults (20 in this case) have been reached. */ public static void listDocuments(SsmClient ssmClient,
systems-manager-ug-742
systems-manager-ug.pdf
742
import software.amazon.awssdk.services.ssm.SsmClient; import software.amazon.awssdk.services.ssm.model.DocumentFilter; import software.amazon.awssdk.services.ssm.model.ListDocumentsRequest; import software.amazon.awssdk.services.ssm.model.ListDocumentsResponse; public class HelloSSM { public static void main(String[] args) { final String usage = """ Usage: <awsAccount> Where: awsAccount - Your AWS Account number. """; if (args.length != 1) { System.out.println(usage); System.exit(1); Hello Systems Manager 2527 AWS Systems Manager } User Guide String awsAccount = args[0] ; Region region = Region.US_EAST_1; SsmClient ssmClient = SsmClient.builder() .region(region) .build(); listDocuments(ssmClient, awsAccount); } /* This code automatically fetches the next set of results using the `nextToken` and stops once the desired maxResults (20 in this case) have been reached. */ public static void listDocuments(SsmClient ssmClient, String awsAccount) { String nextToken = null; int totalDocumentsReturned = 0; int maxResults = 20; do { ListDocumentsRequest request = ListDocumentsRequest.builder() .documentFilterList( DocumentFilter.builder() .key("Owner") .value(awsAccount) .build() ) .maxResults(maxResults) .nextToken(nextToken) .build(); ListDocumentsResponse response = ssmClient.listDocuments(request); response.documentIdentifiers().forEach(identifier -> System.out.println("Document Name: " + identifier.name())); nextToken = response.nextToken(); totalDocumentsReturned += response.documentIdentifiers().size(); } while (nextToken != null && totalDocumentsReturned < maxResults); } } • For API details, see ListDocuments in AWS SDK for Java 2.x API Reference. Hello Systems Manager 2528 AWS Systems Manager JavaScript SDK for JavaScript (v3) Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { paginateListDocuments, SSMClient } from "@aws-sdk/client-ssm"; // Call ListDocuments and display the result. export const main = async () => { const client = new SSMClient(); const listDocumentsPaginated = []; console.log( "Hello, AWS Systems Manager! Let's list some of your documents:\n", ); try { // The paginate function is a wrapper around the base command. const paginator = paginateListDocuments({ client }, { MaxResults: 5 }); for await (const page of paginator) { listDocumentsPaginated.push(...page.DocumentIdentifiers); } } catch (caught) { console.error(`There was a problem saying hello: ${caught.message}`); throw caught; } for (const { Name, DocumentFormat, CreatedDate } of listDocumentsPaginated) { console.log(`${Name} - ${DocumentFormat} - ${CreatedDate}`); } }; // Call function if run directly. import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { main(); } Hello Systems Manager 2529 AWS Systems Manager User Guide • For API details, see ListDocuments in AWS SDK for JavaScript API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import boto3 from botocore.exceptions import ClientError def hello_systems_manager(ssm_client): """ Use the AWS SDK for Python (Boto3) to create an AWS Systems Manager client and list the first 5 documents in your account. This example uses the default settings specified in your shared credentials and config files. :param ssm_client: A Boto3 AWS Systems Manager Client object. This object wraps the low-level AWS Systems Manager service API. """ print("Hello, AWS Systems Manager! Let's list some of your documents:\n") paginator = ssm_client.get_paginator("list_documents") page_iterator = paginator.paginate(PaginationConfig={"MaxItems": 5}) for page in page_iterator: for document in page["DocumentIdentifiers"]: print(f" {document['Name']}") if __name__ == "__main__": try: hello_systems_manager(boto3.client("ssm")) except ClientError as err: print("Hello systems manager had an error.") print(err.response["Error"]["Code"]) Hello Systems Manager 2530 AWS Systems Manager User Guide print(err.response["Error"]["Message"]) • For API details, see ListDocuments in AWS SDK for Python (Boto3) API Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Learn the basics of Systems Manager with an AWS SDK The following code examples show how to: • Create a maintenance window. • Modify the maintenance window schedule. • Create a document. • Send a command to a specified EC2 instance. • Create an OpsItem. • Update and resolve the OpsItem. • Delete the maintenance window, OpsItem, and document. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.services.ssm.model.DocumentAlreadyExistsException; import software.amazon.awssdk.services.ssm.model.SsmException; import java.util.Scanner; public class SSMScenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); Learn the basics 2531 AWS Systems Manager User Guide public static void main(String[] args) { String usage = """ Usage: <instanceId> <title> <source> <category> <severity> Where: instanceId - The Amazon EC2 Linux/UNIX instance Id that AWS Systems Manager uses (ie, i-0149338494ed95f06). title - The title of the parameter (default is Disk Space Alert). source - The source of the parameter (default is EC2). category - The category of the parameter. Valid values are 'Availability', 'Cost', 'Performance', 'Recovery', 'Security' (default is Performance). severity - The severity of the parameter. Severity should be a number from 1 to 4 (default is 2). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } Scanner scanner = new Scanner(System.in); SSMActions actions = new SSMActions(); String documentName; String windowName; String instanceId = args[0]; String title = "Disk Space Alert" ; String source = "EC2" ; String category
systems-manager-ug-743
systems-manager-ug.pdf
743
title - The title of the parameter (default is Disk Space Alert). source - The source of the parameter (default is EC2). category - The category of the parameter. Valid values are 'Availability', 'Cost', 'Performance', 'Recovery', 'Security' (default is Performance). severity - The severity of the parameter. Severity should be a number from 1 to 4 (default is 2). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } Scanner scanner = new Scanner(System.in); SSMActions actions = new SSMActions(); String documentName; String windowName; String instanceId = args[0]; String title = "Disk Space Alert" ; String source = "EC2" ; String category = "Availability" ; String severity = "2" ; System.out.println(DASHES); System.out.println(""" Welcome to the AWS Systems Manager SDK Basics scenario. This Java program demonstrates how to interact with AWS Systems Manager using the AWS SDK for Java (v2). AWS Systems Manager is the operations hub for your AWS applications and resources and a secure end-to-end management solution. The program's primary functionalities include creating a maintenance window, creating a document, sending a command to a document, listing documents, listing commands, creating an OpsItem, modifying an OpsItem, and deleting AWS SSM resources. Learn the basics 2532 AWS Systems Manager User Guide Upon completion of the program, all AWS resources are cleaned up. Let's get started... """); waitForInputToContinue(scanner); System.out.println(DASHES); System.out.println("1. Create an SSM maintenance window."); System.out.println("Please enter the maintenance window name (default is ssm-maintenance-window):"); String win = scanner.nextLine(); windowName = win.isEmpty() ? "ssm-maintenance-window" : win; String winId = null; try { winId = actions.createMaintenanceWindow(windowName); waitForInputToContinue(scanner); System.out.println("The maintenance window ID is: " + winId); } catch (DocumentAlreadyExistsException e) { System.err.println("The SSM maintenance window already exists. Retrieving existing window ID..."); String existingWinId = actions.createMaintenanceWindow(windowName); System.out.println("Existing window ID: " + existingWinId); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); return; } catch (RuntimeException e) { System.err.println("Unexpected error: " + e.getMessage()); return; } waitForInputToContinue(scanner); System.out.println(DASHES); System.out.println("2. Modify the maintenance window by changing the schedule"); waitForInputToContinue(scanner); try { actions.updateSSMMaintenanceWindow(winId, windowName); waitForInputToContinue(scanner); System.out.println("The SSM maintenance window was successfully updated"); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); return; } catch (RuntimeException e) { Learn the basics 2533 AWS Systems Manager User Guide System.err.println("Unexpected error: " + e.getMessage()); return; } waitForInputToContinue(scanner); System.out.println(DASHES); System.out.println("3. Create an SSM document that defines the actions that Systems Manager performs on your managed nodes."); System.out.println("Please enter the document name (default is ssmdocument):"); String doc = scanner.nextLine(); documentName = doc.isEmpty() ? "ssmdocument" : doc; try { actions.createSSMDoc(documentName); waitForInputToContinue(scanner); System.out.println("The SSM document was successfully created"); } catch (DocumentAlreadyExistsException e) { System.err.println("The SSM document already exists. Moving on"); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); return; } catch (RuntimeException e) { System.err.println("Unexpected error: " + e.getMessage()); } waitForInputToContinue(scanner); System.out.println(DASHES); System.out.println("4. Now we are going to run a command on an EC2 instance"); waitForInputToContinue(scanner); String commandId=""; try { commandId = actions.sendSSMCommand(documentName, instanceId); waitForInputToContinue(scanner); System.out.println("The command was successfully sent. Command ID: " + commandId); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); } catch (InterruptedException e) { System.err.println("Thread was interrupted: " + e.getMessage()); } catch (RuntimeException e) { System.err.println("Unexpected error: " + e.getMessage()); } waitForInputToContinue(scanner); Learn the basics 2534 AWS Systems Manager User Guide System.out.println(DASHES); System.out.println("5. Lets get the time when the specific command was sent to the specific managed node"); waitForInputToContinue(scanner); try { actions.displayCommands(commandId); System.out.println("The command invocations were successfully displayed."); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); return; } catch (RuntimeException e) { System.err.println("Unexpected error: " + e.getMessage()); return; } waitForInputToContinue(scanner); System.out.println(DASHES); System.out.println(DASHES); System.out.println(""" 6. Now we will create an SSM OpsItem. A SSM OpsItem is a feature provided by Amazon's Systems Manager (SSM) service. It is a type of operational data item that allows you to manage and track various operational issues, events, or tasks within your AWS environment. You can create OpsItems to track and manage operational issues as they arise. For example, you could create an OpsItem whenever your application detects a critical error or an anomaly in your infrastructure. """); waitForInputToContinue(scanner); String opsItemId; try { opsItemId = actions.createSSMOpsItem(title, source, category, severity); System.out.println(opsItemId + " was created"); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); return; Learn the basics 2535 AWS Systems Manager User Guide } catch (RuntimeException e) { System.err.println("Unexpected error: " + e.getMessage()); return; } waitForInputToContinue(scanner); System.out.println(DASHES); System.out.println(DASHES); System.out.println("7. Now we will update the SSM OpsItem "+opsItemId); waitForInputToContinue(scanner); String description = "An update to "+opsItemId ; try { actions.updateOpsItem(opsItemId, title, description); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); return; } catch (RuntimeException e) { System.err.println("Unexpected error: " + e.getMessage()); return; } System.out.println(DASHES); System.out.println("8. Now we will get the status of the SSM OpsItem "+opsItemId); waitForInputToContinue(scanner); try { actions.describeOpsItems(opsItemId); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); return; } catch (RuntimeException e) { System.err.println("Unexpected error: " + e.getMessage()); return; } System.out.println(DASHES); System.out.println("9. Now we will resolve the
systems-manager-ug-744
systems-manager-ug.pdf
744
+ e.getMessage()); return; } waitForInputToContinue(scanner); System.out.println(DASHES); System.out.println(DASHES); System.out.println("7. Now we will update the SSM OpsItem "+opsItemId); waitForInputToContinue(scanner); String description = "An update to "+opsItemId ; try { actions.updateOpsItem(opsItemId, title, description); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); return; } catch (RuntimeException e) { System.err.println("Unexpected error: " + e.getMessage()); return; } System.out.println(DASHES); System.out.println("8. Now we will get the status of the SSM OpsItem "+opsItemId); waitForInputToContinue(scanner); try { actions.describeOpsItems(opsItemId); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); return; } catch (RuntimeException e) { System.err.println("Unexpected error: " + e.getMessage()); return; } System.out.println(DASHES); System.out.println("9. Now we will resolve the SSM OpsItem "+opsItemId); waitForInputToContinue(scanner); try { actions.resolveOpsItem(opsItemId); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); return; } catch (RuntimeException e) { Learn the basics 2536 AWS Systems Manager User Guide System.err.println("Unexpected error: " + e.getMessage()); return; } System.out.println(DASHES); System.out.println("10. Would you like to delete the AWS Systems Manager resources? (y/n)"); String delAns = scanner.nextLine().trim(); if (delAns.equalsIgnoreCase("y")) { System.out.println("You selected to delete the resources."); waitForInputToContinue(scanner); try { actions.deleteMaintenanceWindow(winId); actions.deleteDoc(documentName); } catch (SsmException e) { System.err.println("SSM error: " + e.getMessage()); return; } catch (RuntimeException e) { System.err.println("Unexpected error: " + e.getMessage()); return; } } else { System.out.println("The AWS Systems Manager resources will not be deleted"); } System.out.println(DASHES); System.out.println("This concludes the AWS Systems Manager SDK Basics scenario."); System.out.println(DASHES); } private static void waitForInputToContinue(Scanner scanner) { while (true) { System.out.println(""); System.out.println("Enter 'c' followed by <ENTER> to continue:"); String input = scanner.nextLine(); if (input.trim().equalsIgnoreCase("c")) { System.out.println("Continuing with the program..."); System.out.println(""); break; } else { // Handle invalid input. Learn the basics 2537 AWS Systems Manager User Guide System.out.println("Invalid input. Please try again."); } } } } A wrapper class for Systems Manager SDK methods. public class SSMActions { private static SsmAsyncClient ssmAsyncClient; private static SsmAsyncClient getAsyncClient() { if (ssmAsyncClient == null) { SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder() .maxConcurrency(100) .connectionTimeout(Duration.ofSeconds(60)) .readTimeout(Duration.ofSeconds(60)) .writeTimeout(Duration.ofSeconds(60)) .build(); ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .apiCallTimeout(Duration.ofMinutes(2)) .apiCallAttemptTimeout(Duration.ofSeconds(90)) .retryPolicy(RetryPolicy.builder() .numRetries(3) .build()) .build(); ssmAsyncClient = SsmAsyncClient.builder() .region(Region.US_EAST_1) .httpClient(httpClient) .overrideConfiguration(overrideConfig) .build(); } return ssmAsyncClient; } /** * Deletes an AWS SSM document asynchronously. * Learn the basics 2538 AWS Systems Manager User Guide * @param documentName The name of the document to delete. * <p> * This method initiates an asynchronous request to delete an SSM document. * If an exception occurs, it handles the error appropriately. */ public void deleteDoc(String documentName) { DeleteDocumentRequest documentRequest = DeleteDocumentRequest.builder() .name(documentName) .build(); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { getAsyncClient().deleteDocument(documentRequest) .thenAccept(response -> { System.out.println("The SSM document was successfully deleted."); }) .exceptionally(ex -> { throw new CompletionException(ex); }).join(); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw new RuntimeException("SSM error: " + cause.getMessage(), cause); } else { throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause); } }); try { future.join(); } catch (CompletionException ex) { throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex; } } /** * Deletes an AWS SSM Maintenance Window asynchronously. * * @param winId The ID of the Maintenance Window to delete. * <p> Learn the basics 2539 AWS Systems Manager User Guide * This method initiates an asynchronous request to delete an SSM Maintenance Window. * If an exception occurs, it handles the error appropriately. */ public void deleteMaintenanceWindow(String winId) { DeleteMaintenanceWindowRequest windowRequest = DeleteMaintenanceWindowRequest.builder() .windowId(winId) .build(); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { getAsyncClient().deleteMaintenanceWindow(windowRequest) .thenAccept(response -> { System.out.println("The maintenance window was successfully deleted."); }) .exceptionally(ex -> { throw new CompletionException(ex); }).join(); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw new RuntimeException("SSM error: " + cause.getMessage(), cause); } else { throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause); } }); try { future.join(); } catch (CompletionException ex) { throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex; } } /** * Resolves an AWS SSM OpsItem asynchronously. * * @param opsID The ID of the OpsItem to resolve. * <p> Learn the basics 2540 AWS Systems Manager User Guide * This method initiates an asynchronous request to resolve an SSM OpsItem. * If an exception occurs, it handles the error appropriately. */ public void resolveOpsItem(String opsID) { UpdateOpsItemRequest opsItemRequest = UpdateOpsItemRequest.builder() .opsItemId(opsID) .status(OpsItemStatus.RESOLVED) .build(); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { getAsyncClient().updateOpsItem(opsItemRequest) .thenAccept(response -> { System.out.println("OpsItem resolved successfully."); }) .exceptionally(ex -> { throw new CompletionException(ex); }).join(); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw new RuntimeException("SSM error: " + cause.getMessage(), cause); } else { throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause); } }); try { future.join(); } catch (CompletionException ex) { throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex; } } /** * Describes AWS SSM OpsItems asynchronously. * * @param key The key to filter OpsItems by (e.g., OPS_ITEM_ID). * * This method initiates an asynchronous request to describe SSM OpsItems. Learn
systems-manager-ug-745
systems-manager-ug.pdf
745
resolved successfully."); }) .exceptionally(ex -> { throw new CompletionException(ex); }).join(); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw new RuntimeException("SSM error: " + cause.getMessage(), cause); } else { throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause); } }); try { future.join(); } catch (CompletionException ex) { throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex; } } /** * Describes AWS SSM OpsItems asynchronously. * * @param key The key to filter OpsItems by (e.g., OPS_ITEM_ID). * * This method initiates an asynchronous request to describe SSM OpsItems. Learn the basics 2541 AWS Systems Manager User Guide * If the request is successful, it prints the title and status of each OpsItem. * If an exception occurs, it handles the error appropriately. */ public void describeOpsItems(String key) { OpsItemFilter filter = OpsItemFilter.builder() .key(OpsItemFilterKey.OPS_ITEM_ID) .values(key) .operator(OpsItemFilterOperator.EQUAL) .build(); DescribeOpsItemsRequest itemsRequest = DescribeOpsItemsRequest.builder() .maxResults(10) .opsItemFilters(filter) .build(); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { getAsyncClient().describeOpsItems(itemsRequest) .thenAccept(itemsResponse -> { List<OpsItemSummary> items = itemsResponse.opsItemSummaries(); for (OpsItemSummary item : items) { System.out.println("The item title is " + item.title() + " and the status is " + item.status().toString()); } }) .exceptionally(ex -> { throw new CompletionException(ex); }).join(); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw new RuntimeException("SSM error: " + cause.getMessage(), cause); } else { throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause); } }); try { future.join(); } catch (CompletionException ex) { Learn the basics 2542 AWS Systems Manager User Guide throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex; } } /** * Updates the AWS SSM OpsItem asynchronously. * * @param opsItemId The ID of the OpsItem to update. * @param title The new title of the OpsItem. * @param description The new description of the OpsItem. * <p> * This method initiates an asynchronous request to update an SSM OpsItem. * If the request is successful, it completes without returning a value. * If an exception occurs, it handles the error appropriately. */ public void updateOpsItem(String opsItemId, String title, String description) { Map<String, OpsItemDataValue> operationalData = new HashMap<>(); operationalData.put("key1", OpsItemDataValue.builder().value("value1").build()); operationalData.put("key2", OpsItemDataValue.builder().value("value2").build()); CompletableFuture<Void> future = getOpsItem(opsItemId).thenCompose(opsItem -> { UpdateOpsItemRequest request = UpdateOpsItemRequest.builder() .opsItemId(opsItemId) .title(title) .operationalData(operationalData) .status(opsItem.statusAsString()) .description(description) .build(); return getAsyncClient().updateOpsItem(request).thenAccept(response -> { System.out.println(opsItemId + " updated successfully."); }).exceptionally(ex -> { throw new CompletionException(ex); }); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { Learn the basics 2543 AWS Systems Manager User Guide throw new RuntimeException("SSM error: " + cause.getMessage(), cause); } else { throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause); } }); try { future.join(); } catch (CompletionException ex) { throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex; } } private static CompletableFuture<OpsItem> getOpsItem(String opsItemId) { GetOpsItemRequest request = GetOpsItemRequest.builder().opsItemId(opsItemId).build(); return getAsyncClient().getOpsItem(request).thenApply(GetOpsItemResponse::opsItem); } /** * Creates an SSM OpsItem asynchronously. * * @param title The title of the OpsItem. * @param source The source of the OpsItem. * @param category The category of the OpsItem. * @param severity The severity of the OpsItem. * @return The ID of the created OpsItem. * <p> * This method initiates an asynchronous request to create an SSM OpsItem. * If the request is successful, it returns the OpsItem ID. * If an exception occurs, it handles the error appropriately. */ public String createSSMOpsItem(String title, String source, String category, String severity) { CreateOpsItemRequest opsItemRequest = CreateOpsItemRequest.builder() .description("Created by the SSM Java API") .title(title) .source(source) .category(category) Learn the basics 2544 AWS Systems Manager User Guide .severity(severity) .build(); CompletableFuture<CreateOpsItemResponse> future = getAsyncClient().createOpsItem(opsItemRequest); try { CreateOpsItemResponse response = future.join(); return response.opsItemId(); } catch (CompletionException e) { Throwable cause = e.getCause(); if (cause instanceof SsmException) { throw (SsmException) cause; } else { throw new RuntimeException(cause); } } } /** * Displays the date and time when the specific command was invoked. * * @param commandId The ID of the command to describe. * <p> * This method initiates an asynchronous request to list command invocations and prints the date and time of each command invocation. * If an exception occurs, it handles the error appropriately. */ public void displayCommands(String commandId) { ListCommandInvocationsRequest commandInvocationsRequest = ListCommandInvocationsRequest.builder() .commandId(commandId) .build(); CompletableFuture<ListCommandInvocationsResponse> future = getAsyncClient().listCommandInvocations(commandInvocationsRequest); future.thenAccept(response -> { List<CommandInvocation> commandList = response.commandInvocations(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()); for (CommandInvocation invocation : commandList) { System.out.println("The time of the command invocation is " + formatter.format(invocation.requestedDateTime())); } Learn the basics 2545 AWS Systems Manager User Guide }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw (SsmException) cause; } else { throw new RuntimeException(cause); } }).join(); } /** * Sends a SSM command to a managed node asynchronously. * * @param documentName The name of the document to use. * @param instanceId The ID of the instance to
systems-manager-ug-746
systems-manager-ug.pdf
746
getAsyncClient().listCommandInvocations(commandInvocationsRequest); future.thenAccept(response -> { List<CommandInvocation> commandList = response.commandInvocations(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()); for (CommandInvocation invocation : commandList) { System.out.println("The time of the command invocation is " + formatter.format(invocation.requestedDateTime())); } Learn the basics 2545 AWS Systems Manager User Guide }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw (SsmException) cause; } else { throw new RuntimeException(cause); } }).join(); } /** * Sends a SSM command to a managed node asynchronously. * * @param documentName The name of the document to use. * @param instanceId The ID of the instance to send the command to. * @return The command ID. * <p> * This method initiates asynchronous requests to send a SSM command to a managed node. * It waits until the document is active, sends the command, and checks the command execution status. */ public String sendSSMCommand(String documentName, String instanceId) throws InterruptedException, SsmException { // Before we use Document to send a command - make sure it is active. CompletableFuture<Void> documentActiveFuture = CompletableFuture.runAsync(() -> { boolean isDocumentActive = false; DescribeDocumentRequest request = DescribeDocumentRequest.builder() .name(documentName) .build(); while (!isDocumentActive) { CompletableFuture<DescribeDocumentResponse> response = getAsyncClient().describeDocument(request); String documentStatus = response.join().document().statusAsString(); if (documentStatus.equals("Active")) { System.out.println("The SSM document is active and ready to use."); isDocumentActive = true; } else { Learn the basics 2546 AWS Systems Manager User Guide System.out.println("The SSM document is not active. Status: " + documentStatus); try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }); documentActiveFuture.join(); // Create the SendCommandRequest. SendCommandRequest commandRequest = SendCommandRequest.builder() .documentName(documentName) .instanceIds(instanceId) .build(); // Send the command. CompletableFuture<SendCommandResponse> commandFuture = getAsyncClient().sendCommand(commandRequest); final String[] commandId = {null}; commandFuture.whenComplete((commandResponse, ex) -> { if (commandResponse != null) { commandId[0] = commandResponse.command().commandId(); System.out.println("Command ID: " + commandId[0]); // Wait for the command execution to complete. GetCommandInvocationRequest invocationRequest = GetCommandInvocationRequest.builder() .commandId(commandId[0]) .instanceId(instanceId) .build(); try { System.out.println("Wait 5 secs"); TimeUnit.SECONDS.sleep(5); // Retrieve the command execution details. CompletableFuture<GetCommandInvocationResponse> invocationFuture = getAsyncClient().getCommandInvocation(invocationRequest); Learn the basics 2547 AWS Systems Manager User Guide invocationFuture.whenComplete((commandInvocationResponse, invocationEx) -> { if (commandInvocationResponse != null) { // Check the status of the command execution. CommandInvocationStatus status = commandInvocationResponse.status(); if (status == CommandInvocationStatus.SUCCESS) { System.out.println("Command execution successful"); } else { System.out.println("Command execution failed. Status: " + status); } } else { Throwable invocationCause = (invocationEx instanceof CompletionException) ? invocationEx.getCause() : invocationEx; throw new CompletionException(invocationCause); } }).join(); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw (SsmException) cause; } else { throw new RuntimeException(cause); } } }).join(); return commandId[0]; } /** * Creates an AWS SSM document asynchronously. * * @param docName The name of the document to create. * <p> * This method initiates an asynchronous request to create an SSM document. * If the request is successful, it prints the document status. * If an exception occurs, it handles the error appropriately. Learn the basics 2548 AWS Systems Manager */ User Guide public void createSSMDoc(String docName) throws SsmException { String jsonData = """ { "schemaVersion": "2.2", "description": "Run a simple shell command", "mainSteps": [ { "action": "aws:runShellScript", "name": "runEchoCommand", "inputs": { "runCommand": [ "echo 'Hello, world!'" ] } } ] } """; CreateDocumentRequest request = CreateDocumentRequest.builder() .content(jsonData) .name(docName) .documentType(DocumentType.COMMAND) .build(); CompletableFuture<CreateDocumentResponse> future = getAsyncClient().createDocument(request); future.thenAccept(response -> { System.out.println("The status of the SSM document is " + response.documentDescription().status()); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof DocumentAlreadyExistsException) { throw new CompletionException(cause); } else if (cause instanceof SsmException) { throw new CompletionException(cause); } else { throw new RuntimeException(cause); } }).join(); } Learn the basics 2549 AWS Systems Manager /** User Guide * Updates an SSM maintenance window asynchronously. * * @param id The ID of the maintenance window to update. * @param name The new name for the maintenance window. * <p> * This method initiates an asynchronous request to update an SSM maintenance window. * If the request is successful, it prints a success message. * If an exception occurs, it handles the error appropriately. */ public void updateSSMMaintenanceWindow(String id, String name) throws SsmException { UpdateMaintenanceWindowRequest updateRequest = UpdateMaintenanceWindowRequest.builder() .windowId(id) .allowUnassociatedTargets(true) .duration(24) .enabled(true) .name(name) .schedule("cron(0 0 ? * MON *)") .build(); CompletableFuture<UpdateMaintenanceWindowResponse> future = getAsyncClient().updateMaintenanceWindow(updateRequest); future.whenComplete((response, ex) -> { if (response != null) { System.out.println("The SSM maintenance window was successfully updated"); } else { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw new CompletionException(cause); } else { throw new RuntimeException(cause); } } }).join(); } /** * Creates an SSM maintenance window asynchronously. * Learn the basics 2550 AWS Systems Manager User Guide * @param winName The name of the maintenance window. * @return The ID of the created or existing maintenance window. * <p> * This method initiates an asynchronous request to create
systems-manager-ug-747
systems-manager-ug.pdf
747
CompletableFuture<UpdateMaintenanceWindowResponse> future = getAsyncClient().updateMaintenanceWindow(updateRequest); future.whenComplete((response, ex) -> { if (response != null) { System.out.println("The SSM maintenance window was successfully updated"); } else { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw new CompletionException(cause); } else { throw new RuntimeException(cause); } } }).join(); } /** * Creates an SSM maintenance window asynchronously. * Learn the basics 2550 AWS Systems Manager User Guide * @param winName The name of the maintenance window. * @return The ID of the created or existing maintenance window. * <p> * This method initiates an asynchronous request to create an SSM maintenance window. * If the request is successful, it prints the maintenance window ID. * If an exception occurs, it handles the error appropriately. */ public String createMaintenanceWindow(String winName) throws SsmException, DocumentAlreadyExistsException { CreateMaintenanceWindowRequest request = CreateMaintenanceWindowRequest.builder() .name(winName) .description("This is my maintenance window") .allowUnassociatedTargets(true) .duration(2) .cutoff(1) .schedule("cron(0 10 ? * MON-FRI *)") .build(); CompletableFuture<CreateMaintenanceWindowResponse> future = getAsyncClient().createMaintenanceWindow(request); final String[] windowId = {null}; future.whenComplete((response, ex) -> { if (response != null) { String maintenanceWindowId = response.windowId(); System.out.println("The maintenance window id is " + maintenanceWindowId); windowId[0] = maintenanceWindowId; } else { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof DocumentAlreadyExistsException) { throw new CompletionException(cause); } else if (cause instanceof SsmException) { throw new CompletionException(cause); } else { throw new RuntimeException(cause); } } }).join(); if (windowId[0] == null) { MaintenanceWindowFilter filter = MaintenanceWindowFilter.builder() Learn the basics 2551 AWS Systems Manager User Guide .key("name") .values(winName) .build(); DescribeMaintenanceWindowsRequest winRequest = DescribeMaintenanceWindowsRequest.builder() .filters(filter) .build(); CompletableFuture<DescribeMaintenanceWindowsResponse> describeFuture = getAsyncClient().describeMaintenanceWindows(winRequest); describeFuture.whenComplete((describeResponse, describeEx) -> { if (describeResponse != null) { List<MaintenanceWindowIdentity> windows = describeResponse.windowIdentities(); if (!windows.isEmpty()) { windowId[0] = windows.get(0).windowId(); System.out.println("Window ID: " + windowId[0]); } else { System.out.println("Window not found."); windowId[0] = ""; } } else { Throwable describeCause = (describeEx instanceof CompletionException) ? describeEx.getCause() : describeEx; throw new RuntimeException("Error describing maintenance windows: " + describeCause.getMessage(), describeCause); } }).join(); } return windowId[0]; } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • CreateDocument • CreateMaintenanceWindow • CreateOpsItem • DeleteMaintenanceWindow Learn the basics 2552 AWS Systems Manager User Guide • ListCommandInvocations • SendCommand • UpdateOpsItem JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { Scenario, ScenarioAction, ScenarioInput, ScenarioOutput, } from "@aws-doc-sdk-examples/lib/scenario/index.js"; import { fileURLToPath } from "node:url"; import { CreateDocumentCommand, CreateMaintenanceWindowCommand, CreateOpsItemCommand, DeleteDocumentCommand, DeleteMaintenanceWindowCommand, DeleteOpsItemCommand, DescribeOpsItemsCommand, DocumentAlreadyExists, OpsItemStatus, waitUntilCommandExecuted, CancelCommandCommand, paginateListCommandInvocations, SendCommandCommand, UpdateMaintenanceWindowCommand, UpdateOpsItemCommand, SSMClient, } from "@aws-sdk/client-ssm"; import { parseArgs } from "node:util"; Learn the basics 2553 AWS Systems Manager /** * @typedef {{ * ssmClient: import('@aws-sdk/client-ssm').SSMClient, User Guide * documentName?: string * maintenanceWindow?: string * winId?: int * ec2InstanceId?: string * requestedDateTime?: Date * opsItemId?: string * askToDeleteResources?: boolean * }} State */ const defaultMaintenanceWindow = "ssm-maintenance-window"; const defaultDocumentName = "ssmdocument"; // The timeout duration is highly dependent on the specific setup and environment necessary. This example handles only the most common error cases, and uses a much shorter duration than most productions systems would use. const COMMAND_TIMEOUT_DURATION_SECONDS = 30; // 30 seconds const pressEnter = new ScenarioInput("continue", "Press Enter to continue", { type: "confirm", }); const greet = new ScenarioOutput( "greet", `Welcome to the AWS Systems Manager SDK Getting Started scenario. This program demonstrates how to interact with Systems Manager using the AWS SDK for JavaScript V3. Systems Manager is the operations hub for your AWS applications and resources and a secure end-to-end management solution. The program's primary functions include creating a maintenance window, creating a document, sending a command to a document, listing documents, listing commands, creating an OpsItem, modifying an OpsItem, and deleting Systems Manager resources. Upon completion of the program, all AWS resources are cleaned up. Let's get started...`, { header: true }, ); const createMaintenanceWindow = new ScenarioOutput( "createMaintenanceWindow", "Step 1: Create a Systems Manager maintenance window.", ); Learn the basics 2554 AWS Systems Manager User Guide const getMaintenanceWindow = new ScenarioInput( "maintenanceWindow", "Please enter the maintenance window name:", { type: "input", default: defaultMaintenanceWindow }, ); export const sdkCreateMaintenanceWindow = new ScenarioAction( "sdkCreateMaintenanceWindow", async (/** @type {State} */ state) => { try { const response = await state.ssmClient.send( new CreateMaintenanceWindowCommand({ Name: state.maintenanceWindow, Schedule: "cron(0 10 ? * MON-FRI *)", //The schedule of the maintenance window in the form of a cron or rate expression. Duration: 2, //The duration of the maintenance window in hours. Cutoff: 1, //The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution. AllowUnassociatedTargets: true, //Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets. }), ); state.winId = response.WindowId; } catch (caught) { console.error(caught.message); console.log( `An error occurred while creating
systems-manager-ug-748
systems-manager-ug.pdf
748
= await state.ssmClient.send( new CreateMaintenanceWindowCommand({ Name: state.maintenanceWindow, Schedule: "cron(0 10 ? * MON-FRI *)", //The schedule of the maintenance window in the form of a cron or rate expression. Duration: 2, //The duration of the maintenance window in hours. Cutoff: 1, //The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution. AllowUnassociatedTargets: true, //Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets. }), ); state.winId = response.WindowId; } catch (caught) { console.error(caught.message); console.log( `An error occurred while creating the maintenance window. Please fix the error and try again. Error message: ${caught.message}`, ); throw caught; } }, ); const modifyMaintenanceWindow = new ScenarioOutput( "modifyMaintenanceWindow", "Modify the maintenance window by changing the schedule.", ); const sdkModifyMaintenanceWindow = new ScenarioAction( "sdkModifyMaintenanceWindow", async (/** @type {State} */ state) => { Learn the basics 2555 AWS Systems Manager try { User Guide await state.ssmClient.send( new UpdateMaintenanceWindowCommand({ WindowId: state.winId, Schedule: "cron(0 0 ? * MON *)", }), ); } catch (caught) { console.error(caught.message); console.log( `An error occurred while modifying the maintenance window. Please fix the error and try again. Error message: ${caught.message}`, ); throw caught; } }, ); const createSystemsManagerActions = new ScenarioOutput( "createSystemsManagerActions", "Create a document that defines the actions that Systems Manager performs on your EC2 instance.", ); const getDocumentName = new ScenarioInput( "documentName", "Please enter the document: ", { type: "input", default: defaultDocumentName }, ); const sdkCreateSSMDoc = new ScenarioAction( "sdkCreateSSMDoc", async (/** @type {State} */ state) => { const contentData = `{ "schemaVersion": "2.2", "description": "Run a simple shell command", "mainSteps": [ { "action": "aws:runShellScript", "name": "runEchoCommand", "inputs": { "runCommand": [ "echo 'Hello, world!'" ] Learn the basics 2556 AWS Systems Manager User Guide } } ] }`; try { await state.ssmClient.send( new CreateDocumentCommand({ Content: contentData, Name: state.documentName, DocumentType: "Command", }), ); } catch (caught) { console.log(`Exception type: (${typeof caught})`); if (caught instanceof DocumentAlreadyExists) { console.log("Document already exists. Continuing...\n"); } else { console.error(caught.message); console.log( `An error occurred while creating the document. Please fix the error and try again. Error message: ${caught.message}`, ); throw caught; } } }, ); const ec2HelloWorld = new ScenarioOutput( "ec2HelloWorld", `Now you have the option of running a command on an EC2 instance that echoes 'Hello, world!'. In order to run this command, you must provide the instance ID of a Linux EC2 instance. If you do not already have a running Linux EC2 instance in your account, you can create one using the AWS console. For information about creating an EC2 instance, see https://docs.aws.amazon.com/AWSEC2/latest/ UserGuide/ec2-launch-instance-wizard.html.`, ); const enterIdOrSkipEC2HelloWorld = new ScenarioInput( "enterIdOrSkipEC2HelloWorld", "Enter your EC2 InstanceId or press enter to skip this step: ", { type: "input", default: "" }, ); Learn the basics 2557 AWS Systems Manager User Guide const sdkEC2HelloWorld = new ScenarioAction( "sdkEC2HelloWorld", async (/** @type {State} */ state) => { try { const response = await state.ssmClient.send( new SendCommandCommand({ DocumentName: state.documentName, InstanceIds: [state.ec2InstanceId], TimeoutSeconds: COMMAND_TIMEOUT_DURATION_SECONDS, }), ); state.CommandId = response.Command.CommandId; } catch (caught) { console.error(caught.message); console.log( `An error occurred while sending the command. Please fix the error and try again. Error message: ${caught.message}`, ); throw caught; } }, { skipWhen: (/** @type {State} */ state) => state.enterIdOrSkipEC2HelloWorld === "", }, ); const sdkGetCommandTime = new ScenarioAction( "sdkGetCommandTime", async (/** @type {State} */ state) => { const listInvocationsPaginated = []; console.log( "Let's get the time when the specific command was sent to the specific managed node.", ); console.log( `First, we'll wait for the command to finish executing. This may take up to ${COMMAND_TIMEOUT_DURATION_SECONDS} seconds.`, ); const commandExecutedResult = waitUntilCommandExecuted( { client: state.ssmClient }, { CommandId: state.CommandId, Learn the basics 2558 AWS Systems Manager User Guide InstanceId: state.ec2InstanceId, }, ); // This is necessary because the TimeoutSeconds of SendCommandCommand is only for the delivery, not execution. try { await new Promise((_, reject) => setTimeout( reject, COMMAND_TIMEOUT_DURATION_SECONDS * 1000, new Error("Command Timed Out"), ), ); } catch (caught) { if (caught.message === "Command Timed Out") { commandExecutedResult.state = "TIMED_OUT"; } else { throw caught; } } if (commandExecutedResult.state !== "SUCCESS") { console.log( `The command with id: ${state.CommandId} did not execute in the allotted time. Canceling command.`, ); state.ssmClient.send( new CancelCommandCommand({ CommandId: state.CommandId, }), ); state.enterIdOrSkipEC2HelloWorld === ""; return; } for await (const page of paginateListCommandInvocations( { client: state.ssmClient }, { CommandId: state.CommandId }, )) { listInvocationsPaginated.push(...page.CommandInvocations); } /** * @type {import('@aws-sdk/client-ssm').CommandInvocation} */ Learn the basics 2559 AWS Systems Manager User Guide const commandInvocation = listInvocationsPaginated.shift(); // Because the call was made with CommandId, there's only one result, so shift it off. state.requestedDateTime = commandInvocation.RequestedDateTime; console.log( `The command invocation happened at: ${state.requestedDateTime}.`, ); }, { skipWhen: (/** @type {State} */ state) => state.enterIdOrSkipEC2HelloWorld === "", }, ); const createSSMOpsItem = new ScenarioOutput( "createSSMOpsItem", `Now we will create a Systems Manager OpsItem. An OpsItem is a
systems-manager-ug-749
systems-manager-ug.pdf
749
state.enterIdOrSkipEC2HelloWorld === ""; return; } for await (const page of paginateListCommandInvocations( { client: state.ssmClient }, { CommandId: state.CommandId }, )) { listInvocationsPaginated.push(...page.CommandInvocations); } /** * @type {import('@aws-sdk/client-ssm').CommandInvocation} */ Learn the basics 2559 AWS Systems Manager User Guide const commandInvocation = listInvocationsPaginated.shift(); // Because the call was made with CommandId, there's only one result, so shift it off. state.requestedDateTime = commandInvocation.RequestedDateTime; console.log( `The command invocation happened at: ${state.requestedDateTime}.`, ); }, { skipWhen: (/** @type {State} */ state) => state.enterIdOrSkipEC2HelloWorld === "", }, ); const createSSMOpsItem = new ScenarioOutput( "createSSMOpsItem", `Now we will create a Systems Manager OpsItem. An OpsItem is a feature provided by the Systems Manager service. It is a type of operational data item that allows you to manage and track various operational issues, events, or tasks within your AWS environment. You can create OpsItems to track and manage operational issues as they arise. For example, you could create an OpsItem whenever your application detects a critical error or an anomaly in your infrastructure.`, ); const sdkCreateSSMOpsItem = new ScenarioAction( "sdkCreateSSMOpsItem", async (/** @type {State} */ state) => { try { const response = await state.ssmClient.send( new CreateOpsItemCommand({ Description: "Created by the System Manager Javascript API", Title: "Disk Space Alert", Source: "EC2", Category: "Performance", Severity: "2", }), ); state.opsItemId = response.OpsItemId; } catch (caught) { console.error(caught.message); console.log( `An error occurred while creating the ops item. Please fix the error and try again. Error message: ${caught.message}`, Learn the basics 2560 AWS Systems Manager User Guide ); throw caught; } }, ); const updateOpsItem = new ScenarioOutput( "updateOpsItem", (/** @type {State} */ state) => `Now we will update the OpsItem: ${state.opsItemId}`, ); const sdkUpdateOpsItem = new ScenarioAction( "sdkUpdateOpsItem", async (/** @type {State} */ state) => { try { const _response = await state.ssmClient.send( new UpdateOpsItemCommand({ OpsItemId: state.opsItemId, Description: `An update to ${state.opsItemId}`, }), ); } catch (caught) { console.error(caught.message); console.log( `An error occurred while updating the ops item. Please fix the error and try again. Error message: ${caught.message}`, ); throw caught; } }, ); const getOpsItemStatus = new ScenarioOutput( "getOpsItemStatus", (/** @type {State} */ state) => `Now we will get the status of the OpsItem: ${state.opsItemId}`, ); const sdkOpsItemStatus = new ScenarioAction( "sdkGetOpsItemStatus", async (/** @type {State} */ state) => { try { const response = await state.ssmClient.send( Learn the basics 2561 AWS Systems Manager User Guide new DescribeOpsItemsCommand({ OpsItemId: state.opsItemId, }), ); state.opsItemStatus = response.OpsItemStatus; } catch (caught) { console.error(caught.message); console.log( `An error occurred while describing the ops item. Please fix the error and try again. Error message: ${caught.message}`, ); throw caught; } }, ); const resolveOpsItem = new ScenarioOutput( "resolveOpsItem", (/** @type {State} */ state) => `Now we will resolve the OpsItem: ${state.opsItemId}`, ); const sdkResolveOpsItem = new ScenarioAction( "sdkResolveOpsItem", async (/** @type {State} */ state) => { try { const _response = await state.ssmClient.send( new UpdateOpsItemCommand({ OpsItemId: state.opsItemId, Status: OpsItemStatus.RESOLVED, }), ); } catch (caught) { console.error(caught.message); console.log( `An error occurred while updating the ops item. Please fix the error and try again. Error message: ${caught.message}`, ); throw caught; } }, ); const askToDeleteResources = new ScenarioInput( Learn the basics 2562 AWS Systems Manager User Guide "askToDeleteResources", "Would you like to delete the Systems Manager resources created during this example run?", { type: "confirm" }, ); const confirmDeleteChoice = new ScenarioOutput( "confirmDeleteChoice", (/** @type {State} */ state) => { if (state.askToDeleteResources) { return "You chose to delete the resources."; } return "The Systems Manager resources will not be deleted. Please delete them manually to avoid charges."; }, ); export const sdkDeleteResources = new ScenarioAction( "sdkDeleteResources", async (/** @type {State} */ state) => { try { await state.ssmClient.send( new DeleteOpsItemCommand({ OpsItemId: state.opsItemId, }), ); console.log(`The ops item: ${state.opsItemId} was successfully deleted.`); } catch (caught) { console.log( `There was a problem deleting the ops item: ${state.opsItemId}. Please delete it manually. Error: ${caught.message}`, ); } try { await state.ssmClient.send( new DeleteMaintenanceWindowCommand({ Name: state.maintenanceWindow, WindowId: state.winId, }), ); console.log( `The maintenance window: ${state.maintenanceWindow} was successfully deleted.`, Learn the basics 2563 AWS Systems Manager User Guide ); } catch (caught) { console.log( `There was a problem deleting the maintenance window: ${state.opsItemId}. Please delete it manually. Error: ${caught.message}`, ); } try { await state.ssmClient.send( new DeleteDocumentCommand({ Name: state.documentName, }), ); console.log( `The document: ${state.documentName} was successfully deleted.`, ); } catch (caught) { console.log( `There was a problem deleting the document: ${state.documentName}. Please delete it manually. Error: ${caught.message}`, ); } }, { skipWhen: (/** @type {{}} */ state) => !state.askToDeleteResources }, ); const goodbye = new ScenarioOutput( "goodbye", "This concludes the Systems Manager Basics scenario for the AWS Javascript SDK v3. Thank you!", ); const myScenario = new Scenario( "SSM Basics", [ greet, pressEnter, createMaintenanceWindow, getMaintenanceWindow, sdkCreateMaintenanceWindow, modifyMaintenanceWindow, pressEnter, sdkModifyMaintenanceWindow, Learn the basics 2564 AWS Systems Manager User Guide createSystemsManagerActions, getDocumentName, sdkCreateSSMDoc, ec2HelloWorld, enterIdOrSkipEC2HelloWorld, sdkEC2HelloWorld, sdkGetCommandTime, pressEnter, createSSMOpsItem, pressEnter, sdkCreateSSMOpsItem, updateOpsItem, pressEnter, sdkUpdateOpsItem, getOpsItemStatus, pressEnter,
systems-manager-ug-750
systems-manager-ug.pdf
750
was successfully deleted.`, ); } catch (caught) { console.log( `There was a problem deleting the document: ${state.documentName}. Please delete it manually. Error: ${caught.message}`, ); } }, { skipWhen: (/** @type {{}} */ state) => !state.askToDeleteResources }, ); const goodbye = new ScenarioOutput( "goodbye", "This concludes the Systems Manager Basics scenario for the AWS Javascript SDK v3. Thank you!", ); const myScenario = new Scenario( "SSM Basics", [ greet, pressEnter, createMaintenanceWindow, getMaintenanceWindow, sdkCreateMaintenanceWindow, modifyMaintenanceWindow, pressEnter, sdkModifyMaintenanceWindow, Learn the basics 2564 AWS Systems Manager User Guide createSystemsManagerActions, getDocumentName, sdkCreateSSMDoc, ec2HelloWorld, enterIdOrSkipEC2HelloWorld, sdkEC2HelloWorld, sdkGetCommandTime, pressEnter, createSSMOpsItem, pressEnter, sdkCreateSSMOpsItem, updateOpsItem, pressEnter, sdkUpdateOpsItem, getOpsItemStatus, pressEnter, sdkOpsItemStatus, resolveOpsItem, pressEnter, sdkResolveOpsItem, askToDeleteResources, confirmDeleteChoice, sdkDeleteResources, goodbye, ], { ssmClient: new SSMClient({}) }, ); /** @type {{ stepHandlerOptions: StepHandlerOptions }} */ export const main = async (stepHandlerOptions) => { await myScenario.run(stepHandlerOptions); }; // Invoke main function if this file was run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { const { values } = parseArgs({ options: { yes: { type: "boolean", short: "y", }, }, }); main({ confirmAll: values.yes }); Learn the basics 2565 AWS Systems Manager } User Guide • For API details, see the following topics in AWS SDK for JavaScript API Reference. • CreateDocument • CreateMaintenanceWindow • CreateOpsItem • DeleteMaintenanceWindow • ListCommandInvocations • SendCommand • UpdateOpsItem Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Run an interactive scenario at a command prompt. class SystemsManagerScenario: """Runs an interactive scenario that shows how to get started using Amazon Systems Manager.""" def __init__(self, document_wrapper, maintenance_window_wrapper, ops_item_wrapper): """ :param document_wrapper: An object that wraps Systems Manager document functions. :param maintenance_window_wrapper: An object that wraps Systems Manager maintenance window functions. :param ops_item_wrapper: An object that wraps Systems Manager OpsItem functions. """ self.document_wrapper = document_wrapper Learn the basics 2566 AWS Systems Manager User Guide self.maintenance_window_wrapper = maintenance_window_wrapper self.ops_item_wrapper = ops_item_wrapper def run(self): """Demonstrates how to use the AWS SDK for Python (Boto3) to get started with Systems Manager.""" try: print("-" * 88) print( """ Welcome to the AWS Systems Manager SDK Getting Started scenario. This program demonstrates how to interact with Systems Manager using the AWS SDK for Python (Boto3). Systems Manager is the operations hub for your AWS applications and resources and a secure end-to-end management solution. The program's primary functions include creating a maintenance window, creating a document, sending a command to a document, listing documents, listing commands, creating an OpsItem, modifying an OpsItem, and deleting Systems Manager resources. Upon completion of the program, all AWS resources are cleaned up. Let's get started...""" ) q.ask("Please hit Enter") print("-" * 88) print("Create a Systems Manager maintenance window.") maintenance_window_name = q.ask( "Please enter the maintenance window name (default is ssm- maintenance-window):", ) if not maintenance_window_name: maintenance_window_name = "ssm-maintenance-window" self.maintenance_window_wrapper.create( name=maintenance_window_name, schedule="cron(0 10 ? * MON-FRI *)", duration=2, cutoff=1, allow_unassociated_targets=True, ) print("-" * 88) print("Modify the maintenance window by changing the schedule") Learn the basics 2567 AWS Systems Manager User Guide q.ask("Please hit Enter") self.maintenance_window_wrapper.update( name=maintenance_window_name, schedule="cron(0 0 ? * MON *)", duration=24, cutoff=1, allow_unassociated_targets=True, enabled=True, ) print("-" * 88) print( "Create a document that defines the actions that Systems Manager performs on your EC2 instance." ) document_name = q.ask( "Please enter the document name (default is ssmdocument):" ) if not document_name: document_name = "ssmdocument" self.document_wrapper.create( name=document_name, content=""" { "schemaVersion": "2.2", "description": "Run a simple shell command", "mainSteps": [ { "action": "aws:runShellScript", "name": "runEchoCommand", "inputs": { "runCommand": [ "echo 'Hello, world!'" ] } } ] } """, ) Learn the basics 2568 AWS Systems Manager User Guide self.document_wrapper.wait_until_active() print( """ Now you have the option of running a command on an EC2 instance that echoes 'Hello, world!'. In order to run this command, you must provide the instance ID of a Linux EC2 instance. If you do not already have a running Linux EC2 instance in your account, you can create one using the AWS console. For information about creating an EC2 instance, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance- wizard.html. """ ) if q.ask( "Would you like to run a command on an EC2 instance? (y/n)", q.is_yesno, ): instance_id = q.ask( "Please enter the instance ID of the EC2 instance:", q.non_empty ) command_id = self.document_wrapper.send_command( instance_ids=[instance_id] ) self.document_wrapper.wait_command_executed( command_id=command_id, instance_id=instance_id ) print("-" * 88) print( "Lets get the time when the specific command was sent to the specific managed node" ) q.ask("Please hit Enter") self.document_wrapper.list_command_invocations(instance_id=instance_id) print("-" * 88) print("-" * 88) Learn the basics 2569 AWS Systems Manager User Guide print( """ Now we will create a Systems Manager OpsItem. An OpsItem is a feature provided by the Systems Manager service. It is a type of operational data item that allows you to manage and track various operational issues, events, or tasks within your AWS environment. You can create OpsItems to track and manage operational issues as they arise.
systems-manager-ug-751
systems-manager-ug.pdf
751
instance_id=instance_id ) print("-" * 88) print( "Lets get the time when the specific command was sent to the specific managed node" ) q.ask("Please hit Enter") self.document_wrapper.list_command_invocations(instance_id=instance_id) print("-" * 88) print("-" * 88) Learn the basics 2569 AWS Systems Manager User Guide print( """ Now we will create a Systems Manager OpsItem. An OpsItem is a feature provided by the Systems Manager service. It is a type of operational data item that allows you to manage and track various operational issues, events, or tasks within your AWS environment. You can create OpsItems to track and manage operational issues as they arise. For example, you could create an OpsItem whenever your application detects a critical error or an anomaly in your infrastructure. """ ) q.ask("Please hit Enter") self.ops_item_wrapper.create( title="Disk Space Alert", description="Created by the Systems Manager Python (Boto3) API", source="EC2", category="Performance", severity="2", ) print("-" * 88) print("-" * 88) print(f"Now we will update the OpsItem {self.ops_item_wrapper.id}") q.ask("Please hit Enter") self.ops_item_wrapper.update( title="Disk Space Alert", description=f"An update to {self.ops_item_wrapper.id}", ) print( f"Now we will get the status of the OpsItem {self.ops_item_wrapper.id}" ) q.ask("Please hit Enter") # It may take a second for the ops item to be available counter = 0 while not self.ops_item_wrapper.describe() and counter < 5: counter += 1 Learn the basics 2570 AWS Systems Manager User Guide time.sleep(1) print(f"Now we will resolve the OpsItem {self.ops_item_wrapper.id}") q.ask("Please hit Enter") self.ops_item_wrapper.update(status="Resolved") print("-" * 88) print("-" * 88) if q.ask( "Would you like to delete the Systems Manager resources? (y/n)", q.is_yesno, ): print("You selected to delete the resources.") self.cleanup() else: print("The Systems Manager resources will not be deleted") print("-" * 88) print("This concludes the Systems Manager SDK Getting Started scenario.") print("-" * 88) except Exception: self.cleanup() raise def cleanup(self): self.maintenance_window_wrapper.delete() self.ops_item_wrapper.delete() self.document_wrapper.delete() if __name__ == "__main__": try: scenario = SystemsManagerScenario( DocumentWrapper.from_client(), MaintenanceWindowWrapper.from_client(), OpsItemWrapper.from_client(), ) scenario.run() except Exception: logging.exception("Something went wrong with the demo.") Learn the basics 2571 AWS Systems Manager User Guide Define a class that wraps document and command actions. class DocumentWrapper: """Encapsulates AWS Systems Manager Document actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.name = None @classmethod def from_client(cls): ssm_client = boto3.client("ssm") return cls(ssm_client) def create(self, content, name): """ Creates a document. :param content: The content of the document. :param name: The name of the document. """ try: self.ssm_client.create_document( Name=name, Content=content, DocumentType="Command" ) self.name = name except self.ssm_client.exceptions.DocumentAlreadyExists: print(f"Document {name} already exists.") self.name = name except ClientError as err: logger.error( "Couldn't create %s. Here's why: %s: %s", name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise Learn the basics 2572 AWS Systems Manager User Guide def delete(self): """ Deletes an AWS Systems Manager document. """ if self.name is None: return try: self.ssm_client.delete_document(Name=self.name) print(f"Deleted document {self.name}.") self.name = None except ClientError as err: logger.error( "Couldn't delete %s. Here's why: %s: %s", self.name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise def send_command(self, instance_ids): """ Sends a command to one or more instances. :param instance_ids: The IDs of the instances to send the command to. :return: The ID of the command. """ try: response = self.ssm_client.send_command( InstanceIds=instance_ids, DocumentName=self.name, TimeoutSeconds=3600 ) return response["Command"]["CommandId"] except ClientError as err: logger.error( "Couldn't send command to %s. Here's why: %s: %s", self.name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise Learn the basics 2573 AWS Systems Manager User Guide def describe(self): """ Describes the document. :return: Document status. """ try: response = self.ssm_client.describe_document(Name=self.name) return response["Document"]["Status"] except ClientError as err: logger.error( "Couldn't get %s. Here's why: %s: %s", self.name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise def wait_until_active(self, max_attempts=20, delay=5): """ Waits until the document is active. :param max_attempts: The maximum number of attempts for checking the status. :param delay: The delay in seconds between each check. """ attempt = 0 status = "" while attempt <= max_attempts: status = self.describe() if status == "Active": break attempt += 1 time.sleep(delay) if status != "Active": logger.error("Document is not active.") else: logger.info("Document is active.") def wait_command_executed(self, command_id, instance_id): Learn the basics 2574 AWS Systems Manager """ User Guide Waits until the command is executed on the instance. :param command_id: The ID of the command. :param instance_id: The ID of the instance. """ waiter = self.ssm_client.get_waiter("command_executed") waiter.wait(CommandId=command_id, InstanceId=instance_id) def list_command_invocations(self, instance_id): """ Lists the commands for an instance. :param instance_id: The ID of the instance. :return: The list of commands. """ try: paginator = self.ssm_client.get_paginator("list_command_invocations") command_invocations = [] for page in paginator.paginate(InstanceId=instance_id): command_invocations.extend(page["CommandInvocations"]) num_of_commands = len(command_invocations) print( f"{num_of_commands} command invocation(s) found for instance {instance_id}." ) if num_of_commands > 10: print("Displaying the first 10 commands:") num_of_commands = 10 date_format = "%A, %d %B %Y %I:%M%p" for command in command_invocations[:num_of_commands]: print( f" The time of command invocation is {command['RequestedDateTime'].strftime(date_format)}" ) except ClientError as err: logger.error( "Couldn't list commands for %s. Here's why: %s: %s", instance_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) Learn the basics 2575 AWS Systems Manager raise User Guide Define a class that wraps ops item actions. class OpsItemWrapper: """Encapsulates AWS Systems
systems-manager-ug-752
systems-manager-ug.pdf
752
commands. """ try: paginator = self.ssm_client.get_paginator("list_command_invocations") command_invocations = [] for page in paginator.paginate(InstanceId=instance_id): command_invocations.extend(page["CommandInvocations"]) num_of_commands = len(command_invocations) print( f"{num_of_commands} command invocation(s) found for instance {instance_id}." ) if num_of_commands > 10: print("Displaying the first 10 commands:") num_of_commands = 10 date_format = "%A, %d %B %Y %I:%M%p" for command in command_invocations[:num_of_commands]: print( f" The time of command invocation is {command['RequestedDateTime'].strftime(date_format)}" ) except ClientError as err: logger.error( "Couldn't list commands for %s. Here's why: %s: %s", instance_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) Learn the basics 2575 AWS Systems Manager raise User Guide Define a class that wraps ops item actions. class OpsItemWrapper: """Encapsulates AWS Systems Manager OpsItem actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.id = None @classmethod def from_client(cls): """ :return: A OpsItemWrapper instance. """ ssm_client = boto3.client("ssm") return cls(ssm_client) def create(self, title, source, category, severity, description): """ Create an OpsItem :param title: The OpsItem title. :param source: The OpsItem source. :param category: The OpsItem category. :param severity: The OpsItem severity. :param description: The OpsItem description. """ try: response = self.ssm_client.create_ops_item( Title=title, Source=source, Category=category, Learn the basics 2576 AWS Systems Manager User Guide Severity=severity, Description=description, ) self.id = response["OpsItemId"] except self.ssm_client.exceptions.OpsItemLimitExceededException as err: logger.error( "Couldn't create ops item because you have exceeded your open OpsItem limit. " "Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise except ClientError as err: logger.error( "Couldn't create ops item %s. Here's why: %s: %s", title, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise def delete(self): """ Delete the OpsItem. """ if self.id is None: return try: self.ssm_client.delete_ops_item(OpsItemId=self.id) print(f"Deleted ops item with id {self.id}") self.id = None except ClientError as err: logger.error( "Couldn't delete ops item %s. Here's why: %s: %s", self.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise def describe(self): """ Learn the basics 2577 AWS Systems Manager User Guide Describe an OpsItem. """ try: paginator = self.ssm_client.get_paginator("describe_ops_items") ops_items = [] for page in paginator.paginate( OpsItemFilters=[ {"Key": "OpsItemId", "Values": [self.id], "Operator": "Equal"} ] ): ops_items.extend(page["OpsItemSummaries"]) for item in ops_items: print( f"The item title is {item['Title']} and the status is {item['Status']}" ) return len(ops_items) > 0 except ClientError as err: logger.error( "Couldn't describe ops item %s. Here's why: %s: %s", self.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise def update(self, title=None, description=None, status=None): """ Update an OpsItem. :param title: The new OpsItem title. :param description: The new OpsItem description. :param status: The new OpsItem status. :return: """ args = dict(OpsItemId=self.id) if title is not None: args["Title"] = title if description is not None: args["Description"] = description if status is not None: Learn the basics 2578 AWS Systems Manager User Guide args["Status"] = status try: self.ssm_client.update_ops_item(**args) except ClientError as err: logger.error( "Couldn't update ops item %s. Here's why: %s: %s", self.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise Define a class that wraps maintenance window actions. class MaintenanceWindowWrapper: """Encapsulates AWS Systems Manager maintenance window actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.window_id = None self.name = None @classmethod def from_client(cls): ssm_client = boto3.client("ssm") return cls(ssm_client) def create(self, name, schedule, duration, cutoff, allow_unassociated_targets): """ Create an AWS Systems Manager maintenance window. :param name: The name of the maintenance window. :param schedule: The schedule of the maintenance window. :param duration: The duration of the maintenance window. Learn the basics 2579 AWS Systems Manager User Guide :param cutoff: The cutoff time of the maintenance window. :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets. """ try: response = self.ssm_client.create_maintenance_window( Name=name, Schedule=schedule, Duration=duration, Cutoff=cutoff, AllowUnassociatedTargets=allow_unassociated_targets, ) self.window_id = response["WindowId"] self.name = name logger.info("Created maintenance window %s.", self.window_id) except ParamValidationError as error: logger.error( "Parameter validation error when trying to create maintenance window %s. Here's why: %s", self.window_id, error, ) raise except ClientError as err: logger.error( "Couldn't create maintenance window %s. Here's why: %s: %s", name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise def delete(self): """ Delete the associated AWS Systems Manager maintenance window. """ if self.window_id is None: return try: self.ssm_client.delete_maintenance_window(WindowId=self.window_id) Learn the basics 2580 AWS Systems Manager User Guide logger.info("Deleted maintenance window %s.", self.window_id) print(f"Deleted maintenance window {self.name}") self.window_id = None except ClientError as err: logger.error( "Couldn't delete maintenance window %s. Here's why: %s: %s", self.window_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise def update( self, name, enabled, schedule, duration, cutoff, allow_unassociated_targets ): """ Update an AWS Systems Manager maintenance window. :param name: The name of the maintenance window. :param enabled: Whether the maintenance window is enabled to run on managed nodes. :param schedule: The schedule of the maintenance window. :param duration: The duration of the maintenance window. :param cutoff: The cutoff time of the maintenance window. :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets. """ try: self.ssm_client.update_maintenance_window( WindowId=self.window_id, Name=name, Enabled=enabled, Schedule=schedule, Duration=duration, Cutoff=cutoff, AllowUnassociatedTargets=allow_unassociated_targets, ) self.name = name logger.info("Updated maintenance window %s.", self.window_id) except ParamValidationError as error: Learn the basics 2581 AWS
systems-manager-ug-753
systems-manager-ug.pdf
753
an AWS Systems Manager maintenance window. :param name: The name of the maintenance window. :param enabled: Whether the maintenance window is enabled to run on managed nodes. :param schedule: The schedule of the maintenance window. :param duration: The duration of the maintenance window. :param cutoff: The cutoff time of the maintenance window. :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets. """ try: self.ssm_client.update_maintenance_window( WindowId=self.window_id, Name=name, Enabled=enabled, Schedule=schedule, Duration=duration, Cutoff=cutoff, AllowUnassociatedTargets=allow_unassociated_targets, ) self.name = name logger.info("Updated maintenance window %s.", self.window_id) except ParamValidationError as error: Learn the basics 2581 AWS Systems Manager User Guide logger.error( "Parameter validation error when trying to update maintenance window %s. Here's why: %s", self.window_id, error, ) raise except ClientError as err: logger.error( "Couldn't update maintenance window %s. Here's why: %s: %s", self.name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise • For API details, see the following topics in AWS SDK for Python (Boto3) API Reference. • CreateDocument • CreateMaintenanceWindow • CreateOpsItem • DeleteMaintenanceWindow • ListCommandInvocations • SendCommand • UpdateOpsItem For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions for Systems Manager using AWS SDKs The following code examples demonstrate how to perform individual Systems Manager actions with AWS SDKs. Each example includes a link to GitHub, where you can find instructions for setting up and running the code. The following examples include only the most commonly used actions. For a complete list, see the AWS Systems Manager API Reference. Actions 2582 User Guide AWS Systems Manager Examples • Use AddTagsToResource with a CLI • Use CancelCommand with a CLI • Use CreateActivation with a CLI • Use CreateAssociation with a CLI • Use CreateAssociationBatch with a CLI • Use CreateDocument with an AWS SDK or CLI • Use CreateMaintenanceWindow with an AWS SDK or CLI • Use CreateOpsItem with an AWS SDK or CLI • Use CreatePatchBaseline with a CLI • Use DeleteActivation with a CLI • Use DeleteAssociation with a CLI • Use DeleteDocument with an AWS SDK or CLI • Use DeleteMaintenanceWindow with an AWS SDK or CLI • Use DeleteOpsItem with an AWS SDK • Use DeleteParameter with a CLI • Use DeletePatchBaseline with a CLI • Use DeregisterManagedInstance with a CLI • Use DeregisterPatchBaselineForPatchGroup with a CLI • Use DeregisterTargetFromMaintenanceWindow with a CLI • Use DeregisterTaskFromMaintenanceWindow with a CLI • Use DescribeActivations with a CLI • Use DescribeAssociation with a CLI • Use DescribeAssociationExecutionTargets with a CLI • Use DescribeAssociationExecutions with a CLI • Use DescribeAutomationExecutions with a CLI • Use DescribeAutomationStepExecutions with a CLI • Use DescribeAvailablePatches with a CLI • Use DescribeDocument with a CLI Actions 2583 AWS Systems Manager User Guide • Use DescribeDocumentPermission with a CLI • Use DescribeEffectiveInstanceAssociations with a CLI • Use DescribeEffectivePatchesForPatchBaseline with a CLI • Use DescribeInstanceAssociationsStatus with a CLI • Use DescribeInstanceInformation with a CLI • Use DescribeInstancePatchStates with a CLI • Use DescribeInstancePatchStatesForPatchGroup with a CLI • Use DescribeInstancePatches with a CLI • Use DescribeMaintenanceWindowExecutionTaskInvocations with a CLI • Use DescribeMaintenanceWindowExecutionTasks with a CLI • Use DescribeMaintenanceWindowExecutions with a CLI • Use DescribeMaintenanceWindowTargets with a CLI • Use DescribeMaintenanceWindowTasks with a CLI • Use DescribeMaintenanceWindows with a CLI • Use DescribeOpsItems with an AWS SDK or CLI • Use DescribeParameters with an AWS SDK or CLI • Use DescribePatchBaselines with a CLI • Use DescribePatchGroupState with a CLI • Use DescribePatchGroups with a CLI • Use GetAutomationExecution with a CLI • Use GetCommandInvocation with a CLI • Use GetConnectionStatus with a CLI • Use GetDefaultPatchBaseline with a CLI • Use GetDeployablePatchSnapshotForInstance with a CLI • Use GetDocument with a CLI • Use GetInventory with a CLI • Use GetInventorySchema with a CLI • Use GetMaintenanceWindow with a CLI • Use GetMaintenanceWindowExecution with a CLI Actions 2584 AWS Systems Manager User Guide • Use GetMaintenanceWindowExecutionTask with a CLI • Use GetParameter with an AWS SDK or CLI • Use GetParameterHistory with a CLI • Use GetParameters with a CLI • Use GetPatchBaseline with a CLI • Use GetPatchBaselineForPatchGroup with a CLI • Use ListAssociationVersions with a CLI • Use ListAssociations with a CLI • Use ListCommandInvocations with an AWS SDK or CLI • Use ListCommands with a CLI • Use ListComplianceItems with a CLI • Use ListComplianceSummaries with a CLI • Use ListDocumentVersions with a CLI • Use ListDocuments with a CLI • Use ListInventoryEntries with a CLI • Use ListResourceComplianceSummaries with a CLI • Use ListTagsForResource with a CLI • Use ModifyDocumentPermission with a CLI • Use PutComplianceItems with a CLI • Use PutInventory with a CLI • Use PutParameter with an AWS SDK or CLI • Use RegisterDefaultPatchBaseline with a CLI • Use RegisterPatchBaselineForPatchGroup with a CLI
systems-manager-ug-754
systems-manager-ug.pdf
754
ListAssociations with a CLI • Use ListCommandInvocations with an AWS SDK or CLI • Use ListCommands with a CLI • Use ListComplianceItems with a CLI • Use ListComplianceSummaries with a CLI • Use ListDocumentVersions with a CLI • Use ListDocuments with a CLI • Use ListInventoryEntries with a CLI • Use ListResourceComplianceSummaries with a CLI • Use ListTagsForResource with a CLI • Use ModifyDocumentPermission with a CLI • Use PutComplianceItems with a CLI • Use PutInventory with a CLI • Use PutParameter with an AWS SDK or CLI • Use RegisterDefaultPatchBaseline with a CLI • Use RegisterPatchBaselineForPatchGroup with a CLI • Use RegisterTargetWithMaintenanceWindow with a CLI • Use RegisterTaskWithMaintenanceWindow with a CLI • Use RemoveTagsFromResource with a CLI • Use SendCommand with an AWS SDK or CLI • Use StartAutomationExecution with a CLI • Use StartSession with a CLI Actions 2585 AWS Systems Manager User Guide • Use StopAutomationExecution with a CLI • Use UpdateAssociation with a CLI • Use UpdateAssociationStatus with a CLI • Use UpdateDocument with a CLI • Use UpdateDocumentDefaultVersion with a CLI • Use UpdateMaintenanceWindow with an AWS SDK or CLI • Use UpdateManagedInstanceRole with a CLI • Use UpdateOpsItem with an AWS SDK or CLI • Use UpdatePatchBaseline with a CLI Use AddTagsToResource with a CLI The following code examples show how to use AddTagsToResource. CLI AWS CLI Example 1: To add tags to a maintenance window The following add-tags-to-resource example adds a tag to the specified maintenance window. aws ssm add-tags-to-resource \ --resource-type "MaintenanceWindow" \ --resource-id "mw-03eb9db428EXAMPLE" \ --tags "Key=Stack,Value=Production" This command produces no output. Example 2: To add tags to a parameter The following add-tags-to-resource example adds two tags to to the specified parameter. aws ssm add-tags-to-resource \ --resource-type "Parameter" \ Actions 2586 AWS Systems Manager User Guide --resource-id "My-Parameter" \ --tags '[{"Key":"Region","Value":"East"},{"Key":"Environment", "Value":"Production"}]' This command produces no output. Example 3: To add tags to an SSM document The following add-tags-to-resource example adds a tag to to the specified document. aws ssm add-tags-to-resource \ --resource-type "Document" \ --resource-id "My-Document" \ --tags "Key=Quarter,Value=Q322" This command produces no output. For more information, see Tagging Systems Manager resources in the AWS Systems Manager User Guide. • For API details, see AddTagsToResource in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example updates a maintenance window with new tags. There is no output if the command succeeds. The syntax used by this example requires PowerShell version 3 or later. $option1 = @{Key="Stack";Value=@("Production")} Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $option1 Example 2: With PowerShell version 2, you must use New-Object to create each tag. There is no output if the command succeeds. $tag1 = New-Object Amazon.SimpleSystemsManagement.Model.Tag $tag1.Key = "Stack" $tag1.Value = "Production" Actions 2587 AWS Systems Manager User Guide Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $tag1 • For API details, see AddTagsToResource in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use CancelCommand with a CLI The following code examples show how to use CancelCommand. CLI AWS CLI Example 1: To cancel a command for all instances The following cancel-command example attempts to cancel the specified command that is already running for all instances. aws ssm cancel-command \ --command-id "662add3d-5831-4a10-b64a-f2ff3EXAMPLE" This command produces no output. Example 2: To cancel a command for specific instances The following cancel-command example attempts to cancel a command for the specified instance only. aws ssm cancel-command \ --command-id "662add3d-5831-4a10-b64a-f2ff3EXAMPLE" --instance-ids "i-02573cafcfEXAMPLE" This command produces no output. For more information, see Tagging Systems Manager Parameters in the AWS Systems Manager User Guide. • For API details, see CancelCommand in AWS CLI Command Reference. Actions 2588 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example attempts to cancel a command. There is no output if the operation succeeds. Stop-SSMCommand -CommandId "9ded293e-e792-4440-8e3e-7b8ec5feaa38" • For API details, see CancelCommand in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use CreateActivation with a CLI The following code examples show how to use CreateActivation. CLI AWS CLI To create a managed instance activation The following create-activation example creates a managed instance activation. aws ssm create-activation \ --default-instance-name "HybridWebServers" \ --iam-role "HybridWebServersRole" \ --registration-limit 5 Output: { "ActivationId": "5743558d-563b-4457-8682-d16c3EXAMPLE", "ActivationCode": "dRmgnYaFv567vEXAMPLE" } For more information, see Step 4: Create a Managed-Instance Activation for a Hybrid Environment in the AWS Systems Manager User Guide. Actions 2589 AWS Systems Manager User Guide • For API details, see CreateActivation in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example
systems-manager-ug-755
systems-manager-ug.pdf
755
SDK versions. Use CreateActivation with a CLI The following code examples show how to use CreateActivation. CLI AWS CLI To create a managed instance activation The following create-activation example creates a managed instance activation. aws ssm create-activation \ --default-instance-name "HybridWebServers" \ --iam-role "HybridWebServersRole" \ --registration-limit 5 Output: { "ActivationId": "5743558d-563b-4457-8682-d16c3EXAMPLE", "ActivationCode": "dRmgnYaFv567vEXAMPLE" } For more information, see Step 4: Create a Managed-Instance Activation for a Hybrid Environment in the AWS Systems Manager User Guide. Actions 2589 AWS Systems Manager User Guide • For API details, see CreateActivation in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example creates a managed instance. New-SSMActivation -DefaultInstanceName "MyWebServers" -IamRole "SSMAutomationRole" -RegistrationLimit 10 Output: ActivationCode ActivationId -------------- ------------ KWChhOxBTiwDcKE9BlKC 08e51e79-1e36-446c-8e63-9458569c1363 • For API details, see CreateActivation in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use CreateAssociation with a CLI The following code examples show how to use CreateAssociation. CLI AWS CLI Example 1: To associate a document using instance IDs This example associates a configuration document with an instance, using instance IDs. aws ssm create-association \ --instance-id "i-0cb2b964d3e14fd9f" \ --name "AWS-UpdateSSMAgent" Output: Actions 2590 AWS Systems Manager User Guide { "AssociationDescription": { "Status": { "Date": 1487875500.33, "Message": "Associated with AWS-UpdateSSMAgent", "Name": "Associated" }, "Name": "AWS-UpdateSSMAgent", "InstanceId": "i-0cb2b964d3e14fd9f", "Overview": { "Status": "Pending", "DetailedStatus": "Creating" }, "AssociationId": "b7c3266e-a544-44db-877e-b20d3a108189", "DocumentVersion": "$DEFAULT", "LastUpdateAssociationDate": 1487875500.33, "Date": 1487875500.33, "Targets": [ { "Values": [ "i-0cb2b964d3e14fd9f" ], "Key": "InstanceIds" } ] } } For more information, see CreateAssociation in the AWS Systems Manager API Reference. Example 2: To associate a document using targets This example associates a configuration document with an instance, using targets. aws ssm create-association \ --name "AWS-UpdateSSMAgent" \ --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" Output: { "AssociationDescription": { "Status": { Actions 2591 AWS Systems Manager User Guide "Date": 1487875500.33, "Message": "Associated with AWS-UpdateSSMAgent", "Name": "Associated" }, "Name": "AWS-UpdateSSMAgent", "InstanceId": "i-0cb2b964d3e14fd9f", "Overview": { "Status": "Pending", "DetailedStatus": "Creating" }, "AssociationId": "b7c3266e-a544-44db-877e-b20d3a108189", "DocumentVersion": "$DEFAULT", "LastUpdateAssociationDate": 1487875500.33, "Date": 1487875500.33, "Targets": [ { "Values": [ "i-0cb2b964d3e14fd9f" ], "Key": "InstanceIds" } ] } } For more information, see CreateAssociation in the AWS Systems Manager API Reference. Example 3: To create an association that runs only once This example creates a new association that only runs once on the specified date and time. Associations created with a date in the past or present (by the time it is processed the date is in the past) run immediately. aws ssm create-association \ --name "AWS-UpdateSSMAgent" \ --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" \ --schedule-expression "at(2020-05-14T15:55:00)" \ --apply-only-at-cron-interval Output: { "AssociationDescription": { Actions 2592 AWS Systems Manager "Status": { "Date": 1487875500.33, "Message": "Associated with AWS-UpdateSSMAgent", User Guide "Name": "Associated" }, "Name": "AWS-UpdateSSMAgent", "InstanceId": "i-0cb2b964d3e14fd9f", "Overview": { "Status": "Pending", "DetailedStatus": "Creating" }, "AssociationId": "b7c3266e-a544-44db-877e-b20d3a108189", "DocumentVersion": "$DEFAULT", "LastUpdateAssociationDate": 1487875500.33, "Date": 1487875500.33, "Targets": [ { "Values": [ "i-0cb2b964d3e14fd9f" ], "Key": "InstanceIds" } ] } } For more information, see CreateAssociation in the AWS Systems Manager API Reference or Reference: Cron and rate expressions for Systems Manager in the AWS Systems Manager User Guide. • For API details, see CreateAssociation in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example associates a configuration document with an instance, using instance IDs. New-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent" Output: Actions 2593 AWS Systems Manager User Guide Name : AWS-UpdateSSMAgent InstanceId : i-0000293ffd8c57862 Date : 2/23/2017 6:55:22 PM Status.Name : Associated Status.Date : 2/20/2015 8:31:11 AM Status.Message : Associated with AWS-UpdateSSMAgent Status.AdditionalInfo : Example 2: This example associates a configuration document with an instance, using targets. $target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")} New-SSMAssociation -Name "AWS-UpdateSSMAgent" -Target $target Output: Name : AWS-UpdateSSMAgent InstanceId : Date : 3/1/2017 6:22:21 PM Status.Name : Status.Date : Status.Message : Status.AdditionalInfo : Example 3: This example associates a configuration document with an instance, using targets and parameters. $target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")} $params = @{ "action"="configure" "mode"="ec2" "optionalConfigurationSource"="ssm" "optionalConfigurationLocation"="" "optionalRestart"="yes" } New-SSMAssociation -Name "Configure-CloudWatch" -AssociationName "CWConfiguration" -Target $target -Parameter $params Output: Name : Configure-CloudWatch Actions 2594 AWS Systems Manager User Guide InstanceId : Date : 5/17/2018 3:17:44 PM Status.Name : Status.Date : Status.Message : Status.AdditionalInfo : Example 4: This example creates an association with all instances in the region, with AWS-GatherSoftwareInventory. It also provides custom files and registry locations in the parameters to collect $params = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new() $params["windowsRegistry"] ='[{"Path":"HKEY_LOCAL_MACHINE\SOFTWARE\Amazon \MachineImage","Recursive":false,"ValueNames":["AMIName"]}]' $params["files"] = '[{"Path":"C:\Program Files","Pattern": ["*.exe"],"Recursive":true}, {"Path":"C:\ProgramData","Pattern": ["*.log"],"Recursive":true}]' New-SSMAssociation -AssociationName new-in-mum -Name AWS-GatherSoftwareInventory -Target @{Key="instanceids";Values="*"} -Parameter $params -region ap-south-1 - ScheduleExpression "rate(720 minutes)" Output: Name : AWS-GatherSoftwareInventory InstanceId : Date : 6/9/2019 8:57:56 AM Status.Name : Status.Date : Status.Message : Status.AdditionalInfo : • For API details, see CreateAssociation in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes
systems-manager-ug-756
systems-manager-ug.pdf
756
region, with AWS-GatherSoftwareInventory. It also provides custom files and registry locations in the parameters to collect $params = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new() $params["windowsRegistry"] ='[{"Path":"HKEY_LOCAL_MACHINE\SOFTWARE\Amazon \MachineImage","Recursive":false,"ValueNames":["AMIName"]}]' $params["files"] = '[{"Path":"C:\Program Files","Pattern": ["*.exe"],"Recursive":true}, {"Path":"C:\ProgramData","Pattern": ["*.log"],"Recursive":true}]' New-SSMAssociation -AssociationName new-in-mum -Name AWS-GatherSoftwareInventory -Target @{Key="instanceids";Values="*"} -Parameter $params -region ap-south-1 - ScheduleExpression "rate(720 minutes)" Output: Name : AWS-GatherSoftwareInventory InstanceId : Date : 6/9/2019 8:57:56 AM Status.Name : Status.Date : Status.Message : Status.AdditionalInfo : • For API details, see CreateAssociation in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use CreateAssociationBatch with a CLI The following code examples show how to use CreateAssociationBatch. Actions 2595 AWS Systems Manager CLI AWS CLI User Guide To create multiple associations This example associates a configuration document with multiple instances. The output returns a list of successful and failed operations, if applicable. Command: aws ssm create-association-batch --entries "Name=AWS- UpdateSSMAgent,InstanceId=i-1234567890abcdef0" "Name=AWS- UpdateSSMAgent,InstanceId=i-9876543210abcdef0" Output: { "Successful": [ { "Name": "AWS-UpdateSSMAgent", "InstanceId": "i-1234567890abcdef0", "AssociationVersion": "1", "Date": 1550504725.007, "LastUpdateAssociationDate": 1550504725.007, "Status": { "Date": 1550504725.007, "Name": "Associated", "Message": "Associated with AWS-UpdateSSMAgent" }, "Overview": { "Status": "Pending", "DetailedStatus": "Creating" }, "DocumentVersion": "$DEFAULT", "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "Targets": [ { "Key": "InstanceIds", "Values": [ "i-1234567890abcdef0" ] } Actions 2596 AWS Systems Manager User Guide ] }, { "Name": "AWS-UpdateSSMAgent", "InstanceId": "i-9876543210abcdef0", "AssociationVersion": "1", "Date": 1550504725.057, "LastUpdateAssociationDate": 1550504725.057, "Status": { "Date": 1550504725.057, "Name": "Associated", "Message": "Associated with AWS-UpdateSSMAgent" }, "Overview": { "Status": "Pending", "DetailedStatus": "Creating" }, "DocumentVersion": "$DEFAULT", "AssociationId": "9c9f7f20-5154-4fed-a83e-0123456789ab", "Targets": [ { "Key": "InstanceIds", "Values": [ "i-9876543210abcdef0" ] } ] } ], "Failed": [] } • For API details, see CreateAssociationBatch in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example associates a configuration document with multiple instances. The output returns a list of successful and failed operations, if applicable. $option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")} $option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")} Actions 2597 AWS Systems Manager User Guide New-SSMAssociationFromBatch -Entry $option1,$option2 Output: Failed Successful ------ ---------- {} {Amazon.SimpleSystemsManagement.Model.FailedCreateAssociation, Amazon.SimpleSystemsManagement.Model.FailedCreateAsso... Example 2: This example will show the full details of a successful operation. $option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")} $option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")} (New-SSMAssociationFromBatch -Entry $option1,$option2).Successful • For API details, see CreateAssociationBatch in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use CreateDocument with an AWS SDK or CLI The following code examples show how to use CreateDocument. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics CLI AWS CLI To create a document The following create-document example creates a Systems Manager document. aws ssm create-document \ --content file://exampleDocument.yml \ Actions 2598 AWS Systems Manager User Guide --name "Example" \ --document-type "Automation" \ --document-format YAML Output: { "DocumentDescription": { "Hash": "fc2410281f40779e694a8b95975d0f9f316da8a153daa94e3d9921102EXAMPLE", "HashType": "Sha256", "Name": "Example", "Owner": "29884EXAMPLE", "CreatedDate": 1583256349.452, "Status": "Creating", "DocumentVersion": "1", "Description": "Document Example", "Parameters": [ { "Name": "AutomationAssumeRole", "Type": "String", "Description": "(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to execute this document.", "DefaultValue": "" }, { "Name": "InstanceId", "Type": "String", "Description": "(Required) The ID of the Amazon EC2 instance.", "DefaultValue": "" } ], "PlatformTypes": [ "Windows", "Linux" ], "DocumentType": "Automation", "SchemaVersion": "0.3", "LatestVersion": "1", "DefaultVersion": "1", "DocumentFormat": "YAML", "Tags": [] Actions 2599 AWS Systems Manager } } User Guide For more information, see Creating Systems Manager Documents in the AWS Systems Manager User Guide. • For API details, see CreateDocument in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Creates an AWS SSM document asynchronously. * * @param docName The name of the document to create. * <p> * This method initiates an asynchronous request to create an SSM document. * If the request is successful, it prints the document status. * If an exception occurs, it handles the error appropriately. */ public void createSSMDoc(String docName) throws SsmException { String jsonData = """ { "schemaVersion": "2.2", "description": "Run a simple shell command", "mainSteps": [ { "action": "aws:runShellScript", "name": "runEchoCommand", "inputs": { "runCommand": [ "echo 'Hello, world!'" ] } } Actions 2600 AWS Systems Manager User Guide ] } """; CreateDocumentRequest request = CreateDocumentRequest.builder() .content(jsonData) .name(docName) .documentType(DocumentType.COMMAND) .build(); CompletableFuture<CreateDocumentResponse> future = getAsyncClient().createDocument(request); future.thenAccept(response -> { System.out.println("The status of the SSM document is " + response.documentDescription().status()); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof DocumentAlreadyExistsException) { throw new CompletionException(cause); }
systems-manager-ug-757
systems-manager-ug.pdf
757
it handles the error appropriately. */ public void createSSMDoc(String docName) throws SsmException { String jsonData = """ { "schemaVersion": "2.2", "description": "Run a simple shell command", "mainSteps": [ { "action": "aws:runShellScript", "name": "runEchoCommand", "inputs": { "runCommand": [ "echo 'Hello, world!'" ] } } Actions 2600 AWS Systems Manager User Guide ] } """; CreateDocumentRequest request = CreateDocumentRequest.builder() .content(jsonData) .name(docName) .documentType(DocumentType.COMMAND) .build(); CompletableFuture<CreateDocumentResponse> future = getAsyncClient().createDocument(request); future.thenAccept(response -> { System.out.println("The status of the SSM document is " + response.documentDescription().status()); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof DocumentAlreadyExistsException) { throw new CompletionException(cause); } else if (cause instanceof SsmException) { throw new CompletionException(cause); } else { throw new RuntimeException(cause); } }).join(); } • For API details, see CreateDocument in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { CreateDocumentCommand, SSMClient } from "@aws-sdk/client-ssm"; Actions 2601 AWS Systems Manager User Guide import { parseArgs } from "node:util"; /** * Create an SSM document. * @param {{ content: string, name: string, documentType?: DocumentType }} */ export const main = async ({ content, name, documentType }) => { const client = new SSMClient({}); try { const { documentDescription } = await client.send( new CreateDocumentCommand({ Content: content, // The content for the new SSM document. The content must not exceed 64KB. Name: name, DocumentType: documentType, // Document format type can be JSON, YAML, or TEXT. The default format is JSON. }), ); console.log("Document created successfully."); return { DocumentDescription: documentDescription }; } catch (caught) { if (caught instanceof Error && caught.name === "DocumentAlreadyExists") { console.warn(`${caught.message}. Did you provide a new document name?`); } else { throw caught; } } }; • For API details, see CreateDocument in AWS SDK for JavaScript API Reference. PowerShell Tools for PowerShell Example 1: This example creates a document in your account. The document must be in JSON format. For more information about writing a configuration document, see Configuration Document in the SSM API Reference. New-SSMDocument -Content (Get-Content -Raw "c:\temp\RunShellScript.json") -Name "RunShellScript" -DocumentType "Command" Actions 2602 AWS Systems Manager Output: User Guide CreatedDate : 3/1/2017 1:21:33 AM DefaultVersion : 1 Description : Run an updated script DocumentType : Command DocumentVersion : 1 Hash : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1 HashType : Sha256 LatestVersion : 1 Name : RunShellScript Owner : 809632081692 Parameters : {commands} PlatformTypes : {Linux} SchemaVersion : 2.0 Sha1 : Status : Creating • For API details, see CreateDocument in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class DocumentWrapper: """Encapsulates AWS Systems Manager Document actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.name = None Actions 2603 AWS Systems Manager User Guide @classmethod def from_client(cls): ssm_client = boto3.client("ssm") return cls(ssm_client) def create(self, content, name): """ Creates a document. :param content: The content of the document. :param name: The name of the document. """ try: self.ssm_client.create_document( Name=name, Content=content, DocumentType="Command" ) self.name = name except self.ssm_client.exceptions.DocumentAlreadyExists: print(f"Document {name} already exists.") self.name = name except ClientError as err: logger.error( "Couldn't create %s. Here's why: %s: %s", name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise • For API details, see CreateDocument in AWS SDK for Python (Boto3) API Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use CreateMaintenanceWindow with an AWS SDK or CLI The following code examples show how to use CreateMaintenanceWindow. Actions 2604 AWS Systems Manager User Guide Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics CLI AWS CLI Example 1: To create a maintenance window The following create-maintenance-window example creates a new maintenance window that every five minutes for up to two hours (as needed), prevents new tasks from starting within one hour of the end of the maintenance window execution, allows unassociated targets (instances that you haven't registered with the maintenance window), and indicates through the use of custom tags that its creator intends to use it in a tutorial. aws ssm create-maintenance-window \ --name "My-Tutorial-Maintenance-Window" \ --schedule "rate(5 minutes)" \ --duration 2 --cutoff 1 \ --allow-unassociated-targets \ --tags "Key=Purpose,Value=Tutorial" Output: { "WindowId": "mw-0c50858d01EXAMPLE" } Example 2: To create a maintenance window that runs only once The following create-maintenance-window example creates a new maintenance window that only runs one time on the specified date and time. aws ssm create-maintenance-window \ --name My-One-Time-Maintenance-Window \ --schedule "at(2020-05-14T15:55:00)" \ --duration
systems-manager-ug-758
systems-manager-ug.pdf
758
maintenance window execution, allows unassociated targets (instances that you haven't registered with the maintenance window), and indicates through the use of custom tags that its creator intends to use it in a tutorial. aws ssm create-maintenance-window \ --name "My-Tutorial-Maintenance-Window" \ --schedule "rate(5 minutes)" \ --duration 2 --cutoff 1 \ --allow-unassociated-targets \ --tags "Key=Purpose,Value=Tutorial" Output: { "WindowId": "mw-0c50858d01EXAMPLE" } Example 2: To create a maintenance window that runs only once The following create-maintenance-window example creates a new maintenance window that only runs one time on the specified date and time. aws ssm create-maintenance-window \ --name My-One-Time-Maintenance-Window \ --schedule "at(2020-05-14T15:55:00)" \ --duration 5 \ --cutoff 2 \ --allow-unassociated-targets \ Actions 2605 AWS Systems Manager User Guide --tags "Key=Environment,Value=Production" Output: { "WindowId": "mw-01234567890abcdef" } For more information, see Maintenance Windows in the AWS Systems Manager User Guide. • For API details, see CreateMaintenanceWindow in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Creates an SSM maintenance window asynchronously. * * @param winName The name of the maintenance window. * @return The ID of the created or existing maintenance window. * <p> * This method initiates an asynchronous request to create an SSM maintenance window. * If the request is successful, it prints the maintenance window ID. * If an exception occurs, it handles the error appropriately. */ public String createMaintenanceWindow(String winName) throws SsmException, DocumentAlreadyExistsException { CreateMaintenanceWindowRequest request = CreateMaintenanceWindowRequest.builder() .name(winName) .description("This is my maintenance window") .allowUnassociatedTargets(true) .duration(2) .cutoff(1) Actions 2606 AWS Systems Manager User Guide .schedule("cron(0 10 ? * MON-FRI *)") .build(); CompletableFuture<CreateMaintenanceWindowResponse> future = getAsyncClient().createMaintenanceWindow(request); final String[] windowId = {null}; future.whenComplete((response, ex) -> { if (response != null) { String maintenanceWindowId = response.windowId(); System.out.println("The maintenance window id is " + maintenanceWindowId); windowId[0] = maintenanceWindowId; } else { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof DocumentAlreadyExistsException) { throw new CompletionException(cause); } else if (cause instanceof SsmException) { throw new CompletionException(cause); } else { throw new RuntimeException(cause); } } }).join(); if (windowId[0] == null) { MaintenanceWindowFilter filter = MaintenanceWindowFilter.builder() .key("name") .values(winName) .build(); DescribeMaintenanceWindowsRequest winRequest = DescribeMaintenanceWindowsRequest.builder() .filters(filter) .build(); CompletableFuture<DescribeMaintenanceWindowsResponse> describeFuture = getAsyncClient().describeMaintenanceWindows(winRequest); describeFuture.whenComplete((describeResponse, describeEx) -> { if (describeResponse != null) { List<MaintenanceWindowIdentity> windows = describeResponse.windowIdentities(); if (!windows.isEmpty()) { windowId[0] = windows.get(0).windowId(); Actions 2607 AWS Systems Manager User Guide System.out.println("Window ID: " + windowId[0]); } else { System.out.println("Window not found."); windowId[0] = ""; } } else { Throwable describeCause = (describeEx instanceof CompletionException) ? describeEx.getCause() : describeEx; throw new RuntimeException("Error describing maintenance windows: " + describeCause.getMessage(), describeCause); } }).join(); } return windowId[0]; } • For API details, see CreateMaintenanceWindow in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { CreateMaintenanceWindowCommand, SSMClient } from "@aws-sdk/client-ssm"; import { parseArgs } from "node:util"; /** * Create an SSM maintenance window. * @param {{ name: string, allowUnassociatedTargets: boolean, duration: number, cutoff: number, schedule: string, description?: string }} */ export const main = async ({ name, allowUnassociatedTargets, // Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets. Actions 2608 AWS Systems Manager User Guide duration, // The duration of the maintenance window in hours. cutoff, // The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution. schedule, // The schedule of the maintenance window in the form of a cron or rate expression. description = undefined, }) => { const client = new SSMClient({}); try { const { windowId } = await client.send( new CreateMaintenanceWindowCommand({ Name: name, Description: description, AllowUnassociatedTargets: allowUnassociatedTargets, // Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets. Duration: duration, // The duration of the maintenance window in hours. Cutoff: cutoff, // The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution. Schedule: schedule, // The schedule of the maintenance window in the form of a cron or rate expression. }), ); console.log(`Maintenance window created with Id: ${windowId}`); return { WindowId: windowId }; } catch (caught) { if (caught instanceof Error && caught.name === "MissingParameter") { console.warn(`${caught.message}. Did you provide these values?`); } else { throw caught; } } }; • For API details, see CreateMaintenanceWindow in AWS SDK for JavaScript API Reference. Actions 2609 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example creates a new maintenance window with the specified name that runs at 4 PM on every Tuesday for 4 hours, with a 1 hour cutoff,
systems-manager-ug-759
systems-manager-ug.pdf
759
form of a cron or rate expression. }), ); console.log(`Maintenance window created with Id: ${windowId}`); return { WindowId: windowId }; } catch (caught) { if (caught instanceof Error && caught.name === "MissingParameter") { console.warn(`${caught.message}. Did you provide these values?`); } else { throw caught; } } }; • For API details, see CreateMaintenanceWindow in AWS SDK for JavaScript API Reference. Actions 2609 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example creates a new maintenance window with the specified name that runs at 4 PM on every Tuesday for 4 hours, with a 1 hour cutoff, and that allows unassociated targets. New-SSMMaintenanceWindow -Name "MyMaintenanceWindow" -Duration 4 -Cutoff 1 - AllowUnassociatedTarget $true -Schedule "cron(0 16 ? * TUE *)" Output: mw-03eb53e1ea7383998 • For API details, see CreateMaintenanceWindow in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class MaintenanceWindowWrapper: """Encapsulates AWS Systems Manager maintenance window actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.window_id = None self.name = None @classmethod Actions 2610 AWS Systems Manager User Guide def from_client(cls): ssm_client = boto3.client("ssm") return cls(ssm_client) def create(self, name, schedule, duration, cutoff, allow_unassociated_targets): """ Create an AWS Systems Manager maintenance window. :param name: The name of the maintenance window. :param schedule: The schedule of the maintenance window. :param duration: The duration of the maintenance window. :param cutoff: The cutoff time of the maintenance window. :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets. """ try: response = self.ssm_client.create_maintenance_window( Name=name, Schedule=schedule, Duration=duration, Cutoff=cutoff, AllowUnassociatedTargets=allow_unassociated_targets, ) self.window_id = response["WindowId"] self.name = name logger.info("Created maintenance window %s.", self.window_id) except ParamValidationError as error: logger.error( "Parameter validation error when trying to create maintenance window %s. Here's why: %s", self.window_id, error, ) raise except ClientError as err: logger.error( "Couldn't create maintenance window %s. Here's why: %s: %s", name, err.response["Error"]["Code"], err.response["Error"]["Message"], Actions 2611 AWS Systems Manager User Guide ) raise • For API details, see CreateMaintenanceWindow in AWS SDK for Python (Boto3) API Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use CreateOpsItem with an AWS SDK or CLI The following code examples show how to use CreateOpsItem. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics CLI AWS CLI To create an OpsItems The following create-ops-item example uses the /aws/resources key in OperationalData to create an OpsItem with an Amazon DynamoDB related resource. aws ssm create-ops-item \ --title "EC2 instance disk full" \ --description "Log clean up may have failed which caused the disk to be full" \ --priority 2 \ --source ec2 \ --operational-data '{"/aws/resources":{"Value":"[{\"arn \": \"arn:aws:dynamodb:us-west-2:12345678:table/OpsItems \"}]","Type":"SearchableString"}}' \ --notifications Arn="arn:aws:sns:us-west-2:12345678:TestUser" Actions 2612 AWS Systems Manager Output: { "OpsItemId": "oi-1a2b3c4d5e6f" } User Guide For more information, see Creating OpsItems in the AWS Systems Manager User Guide. • For API details, see CreateOpsItem in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Creates an SSM OpsItem asynchronously. * * @param title The title of the OpsItem. * @param source The source of the OpsItem. * @param category The category of the OpsItem. * @param severity The severity of the OpsItem. * @return The ID of the created OpsItem. * <p> * This method initiates an asynchronous request to create an SSM OpsItem. * If the request is successful, it returns the OpsItem ID. * If an exception occurs, it handles the error appropriately. */ public String createSSMOpsItem(String title, String source, String category, String severity) { CreateOpsItemRequest opsItemRequest = CreateOpsItemRequest.builder() .description("Created by the SSM Java API") .title(title) .source(source) .category(category) .severity(severity) .build(); Actions 2613 AWS Systems Manager User Guide CompletableFuture<CreateOpsItemResponse> future = getAsyncClient().createOpsItem(opsItemRequest); try { CreateOpsItemResponse response = future.join(); return response.opsItemId(); } catch (CompletionException e) { Throwable cause = e.getCause(); if (cause instanceof SsmException) { throw (SsmException) cause; } else { throw new RuntimeException(cause); } } } • For API details, see CreateOpsItem in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { CreateOpsItemCommand, SSMClient } from "@aws-sdk/client-ssm"; import { parseArgs } from "node:util"; /** * Create an SSM OpsItem. * @param {{ title: string, source: string, category?: string, severity?: string
systems-manager-ug-760
systems-manager-ug.pdf
760
return response.opsItemId(); } catch (CompletionException e) { Throwable cause = e.getCause(); if (cause instanceof SsmException) { throw (SsmException) cause; } else { throw new RuntimeException(cause); } } } • For API details, see CreateOpsItem in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { CreateOpsItemCommand, SSMClient } from "@aws-sdk/client-ssm"; import { parseArgs } from "node:util"; /** * Create an SSM OpsItem. * @param {{ title: string, source: string, category?: string, severity?: string }} */ export const main = async ({ title, source, category = undefined, Actions 2614 AWS Systems Manager User Guide severity = undefined, }) => { const client = new SSMClient({}); try { const { opsItemArn, opsItemId } = await client.send( new CreateOpsItemCommand({ Title: title, Source: source, // The origin of the OpsItem, such as Amazon EC2 or Systems Manager. Category: category, Severity: severity, }), ); console.log(`Ops item created with id: ${opsItemId}`); return { OpsItemArn: opsItemArn, OpsItemId: opsItemId }; } catch (caught) { if (caught instanceof Error && caught.name === "MissingParameter") { console.warn(`${caught.message}. Did you provide these values?`); } else { throw caught; } } }; • For API details, see CreateOpsItem in AWS SDK for JavaScript API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class OpsItemWrapper: """Encapsulates AWS Systems Manager OpsItem actions.""" def __init__(self, ssm_client): """ Actions 2615 AWS Systems Manager User Guide :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.id = None @classmethod def from_client(cls): """ :return: A OpsItemWrapper instance. """ ssm_client = boto3.client("ssm") return cls(ssm_client) def create(self, title, source, category, severity, description): """ Create an OpsItem :param title: The OpsItem title. :param source: The OpsItem source. :param category: The OpsItem category. :param severity: The OpsItem severity. :param description: The OpsItem description. """ try: response = self.ssm_client.create_ops_item( Title=title, Source=source, Category=category, Severity=severity, Description=description, ) self.id = response["OpsItemId"] except self.ssm_client.exceptions.OpsItemLimitExceededException as err: logger.error( "Couldn't create ops item because you have exceeded your open OpsItem limit. " "Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise except ClientError as err: Actions 2616 AWS Systems Manager User Guide logger.error( "Couldn't create ops item %s. Here's why: %s: %s", title, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise • For API details, see CreateOpsItem in AWS SDK for Python (Boto3) API Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use CreatePatchBaseline with a CLI The following code examples show how to use CreatePatchBaseline. CLI AWS CLI Example 1: To create a patch baseline with auto-approval The following create-patch-baseline example creates a patch baseline for Windows Server that approves patches for a production environment seven days after they are released by Microsoft. aws ssm create-patch-baseline \ --name "Windows-Production-Baseline-AutoApproval" \ --operating-system "WINDOWS" \ --approval- rules "PatchRules=[{PatchFilterGroup={PatchFilters=[{Key=MSRC_SEVERITY,Values=[Critical,Important,Moderate]}, {Key=CLASSIFICATION,Values=[SecurityUpdates,Updates,UpdateRollups,CriticalUpdates]}]},ApproveAfterDays=7}]" \ --description "Baseline containing all updates approved for Windows Server production systems" Output: { Actions 2617 AWS Systems Manager User Guide "BaselineId": "pb-045f10b4f3EXAMPLE" } Example 2: To create a patch baseline with an approval cutoff date The following create-patch-baseline example creates a patch baseline for Windows Server that approves all patches for a production environment that are released on or before July 7, 2020. aws ssm create-patch-baseline \ --name "Windows-Production-Baseline-AutoApproval" \ --operating-system "WINDOWS" \ --approval- rules "PatchRules=[{PatchFilterGroup={PatchFilters=[{Key=MSRC_SEVERITY,Values=[Critical,Important,Moderate]}, {Key=CLASSIFICATION,Values=[SecurityUpdates,Updates,UpdateRollups,CriticalUpdates]}]},ApproveUntilDate=2020-07-07}]" \ --description "Baseline containing all updates approved for Windows Server production systems" Output: { "BaselineId": "pb-045f10b4f3EXAMPLE" } Example 3: To create a patch baseline with approval rules stored in a JSON file The following create-patch-baseline example creates a patch baseline for Amazon Linux 2017.09 that approves patches for a production environment seven days after they are released, specifies approval rules for the patch baseline, and specifies a custom repository for patches. aws ssm create-patch-baseline \ --cli-input-json file://my-amazon-linux-approval-rules-and-repo.json Contents of my-amazon-linux-approval-rules-and-repo.json: { "Name": "Amazon-Linux-2017.09-Production-Baseline", "Description": "My approval rules patch baseline for Amazon Linux 2017.09 instances", Actions 2618 AWS Systems Manager User Guide "OperatingSystem": "AMAZON_LINUX", "Tags": [ { "Key": "Environment", "Value": "Production" } ], "ApprovalRules": { "PatchRules": [ { "ApproveAfterDays": 7, "EnableNonSecurity": true, "PatchFilterGroup": { "PatchFilters": [ { "Key": "SEVERITY", "Values": [ "Important", "Critical" ] }, { "Key": "CLASSIFICATION", "Values": [ "Security", "Bugfix" ] }, { "Key": "PRODUCT", "Values": [ "AmazonLinux2017.09" ] } ] } } ] }, "Sources": [ { "Name": "My-AL2017.09", "Products": [ "AmazonLinux2017.09" Actions 2619 AWS Systems Manager ], User Guide "Configuration": "[amzn-main] \nname=amzn-main-Base \nmirrorlist=http://repo./$awsregion./$awsdomain//$releasever/main/ mirror.list //nmirrorlist_expire=300//nmetadata_expire=300 \npriority=10 \nfailovermethod=priority \nfastestmirror_enabled=0 \ngpgcheck=1 \ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-ga \nenabled=1 \nretries=3 \ntimeout=5\nreport_instanceid=yes" } ] } Example 4: To create a patch baseline that specifies approved and rejected patches The following create-patch-baseline example explicitly specifies patches to approve and
systems-manager-ug-761
systems-manager-ug.pdf
761
"ApprovalRules": { "PatchRules": [ { "ApproveAfterDays": 7, "EnableNonSecurity": true, "PatchFilterGroup": { "PatchFilters": [ { "Key": "SEVERITY", "Values": [ "Important", "Critical" ] }, { "Key": "CLASSIFICATION", "Values": [ "Security", "Bugfix" ] }, { "Key": "PRODUCT", "Values": [ "AmazonLinux2017.09" ] } ] } } ] }, "Sources": [ { "Name": "My-AL2017.09", "Products": [ "AmazonLinux2017.09" Actions 2619 AWS Systems Manager ], User Guide "Configuration": "[amzn-main] \nname=amzn-main-Base \nmirrorlist=http://repo./$awsregion./$awsdomain//$releasever/main/ mirror.list //nmirrorlist_expire=300//nmetadata_expire=300 \npriority=10 \nfailovermethod=priority \nfastestmirror_enabled=0 \ngpgcheck=1 \ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-ga \nenabled=1 \nretries=3 \ntimeout=5\nreport_instanceid=yes" } ] } Example 4: To create a patch baseline that specifies approved and rejected patches The following create-patch-baseline example explicitly specifies patches to approve and reject as exception to the default approval rules. aws ssm create-patch-baseline \ --name "Amazon-Linux-2017.09-Alpha-Baseline" \ --description "My custom approve/reject patch baseline for Amazon Linux 2017.09 instances" \ --operating-system "AMAZON_LINUX" \ --approved-patches "CVE-2018-1234567,example-pkg-EE-2018*.amzn1.noarch" \ --approved-patches-compliance-level "HIGH" \ --approved-patches-enable-non-security \ --tags "Key=Environment,Value=Alpha" For more information, see Create a Custom Patch Baseline in the AWS Systems Manager User Guide. • For API details, see CreatePatchBaseline in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example creates a patch baseline that approves patches, seven days after they are released by Microsoft, for managed instances running Windows Server 2019 in a production environment. $rule = New-Object Amazon.SimpleSystemsManagement.Model.PatchRule $rule.ApproveAfterDays = 7 Actions 2620 AWS Systems Manager User Guide $ruleFilters = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilterGroup $patchFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter $patchFilter.Key="PRODUCT" $patchFilter.Values="WindowsServer2019" $severityFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter $severityFilter.Key="MSRC_SEVERITY" $severityFilter.Values.Add("Critical") $severityFilter.Values.Add("Important") $severityFilter.Values.Add("Moderate") $classificationFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter $classificationFilter.Key = "CLASSIFICATION" $classificationFilter.Values.Add( "SecurityUpdates" ) $classificationFilter.Values.Add( "Updates" ) $classificationFilter.Values.Add( "UpdateRollups" ) $classificationFilter.Values.Add( "CriticalUpdates" ) $ruleFilters.PatchFilters.Add($severityFilter) $ruleFilters.PatchFilters.Add($classificationFilter) $ruleFilters.PatchFilters.Add($patchFilter) $rule.PatchFilterGroup = $ruleFilters New-SSMPatchBaseline -Name "Production-Baseline-Windows2019" -Description "Baseline containing all updates approved for production systems" - ApprovalRules_PatchRule $rule Output: pb-0z4z6221c4296b23z • For API details, see CreatePatchBaseline in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteActivation with a CLI The following code examples show how to use DeleteActivation. Actions 2621 AWS Systems Manager CLI AWS CLI User Guide To delete a managed instance activation The following delete-activation example deletes a managed instance activation. aws ssm delete-activation \ --activation-id "aa673477-d926-42c1-8757-1358cEXAMPLE" This command produces no output. For more information, see Setting Up AWS Systems Manager for Hybrid Environments in the AWS Systems Manager User Guide. • For API details, see DeleteActivation in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example deletes an activation. There is no output if the command succeeds. Remove-SSMActivation -ActivationId "08e51e79-1e36-446c-8e63-9458569c1363" • For API details, see DeleteActivation in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteAssociation with a CLI The following code examples show how to use DeleteAssociation. CLI AWS CLI Example 1: To delete an association using the association ID Actions 2622 AWS Systems Manager User Guide The following delete-association example deletes the association for the specified association ID. There is no output if the command succeeds. aws ssm delete-association \ --association-id "8dfe3659-4309-493a-8755-0123456789ab" This command produces no output. For more information, see Editing and creating a new version of an association in the AWS Systems Manager User Guide. Example 2: To delete an association The following delete-association example deletes the association between an instance and a document. There is no output if the command succeeds. aws ssm delete-association \ --instance-id "i-1234567890abcdef0" \ --name "AWS-UpdateSSMAgent" This command produces no output. For more information, see Working with associations in Systems Manager in the AWS Systems Manager User Guide. • For API details, see DeleteAssociation in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example deletes the association between an instance and a document. There is no output if the command succeeds. Remove-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS- UpdateSSMAgent" • For API details, see DeleteAssociation in AWS Tools for PowerShell Cmdlet Reference. Actions 2623 AWS Systems Manager User Guide For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteDocument with an AWS SDK or CLI The following code examples show how to use DeleteDocument. CLI AWS CLI To delete a document The following delete-document example deletes a Systems Manager document. aws ssm delete-document \ --name "Example" This command produces no output. For more information, see Creating Systems Manager Documents in the AWS Systems Manager User Guide. • For API details, see DeleteDocument in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up
systems-manager-ug-762
systems-manager-ug.pdf
762
information about getting started and details about previous SDK versions. Use DeleteDocument with an AWS SDK or CLI The following code examples show how to use DeleteDocument. CLI AWS CLI To delete a document The following delete-document example deletes a Systems Manager document. aws ssm delete-document \ --name "Example" This command produces no output. For more information, see Creating Systems Manager Documents in the AWS Systems Manager User Guide. • For API details, see DeleteDocument in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Deletes an AWS SSM document asynchronously. * * @param documentName The name of the document to delete. Actions 2624 AWS Systems Manager * <p> User Guide * This method initiates an asynchronous request to delete an SSM document. * If an exception occurs, it handles the error appropriately. */ public void deleteDoc(String documentName) { DeleteDocumentRequest documentRequest = DeleteDocumentRequest.builder() .name(documentName) .build(); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { getAsyncClient().deleteDocument(documentRequest) .thenAccept(response -> { System.out.println("The SSM document was successfully deleted."); }) .exceptionally(ex -> { throw new CompletionException(ex); }).join(); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw new RuntimeException("SSM error: " + cause.getMessage(), cause); } else { throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause); } }); try { future.join(); } catch (CompletionException ex) { throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex; } } • For API details, see DeleteDocument in AWS SDK for Java 2.x API Reference. Actions 2625 AWS Systems Manager JavaScript SDK for JavaScript (v3) Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { DeleteDocumentCommand, SSMClient } from "@aws-sdk/client-ssm"; import { parseArgs } from "node:util"; /** * Delete an SSM document. * @param {{ documentName: string }} */ export const main = async ({ documentName }) => { const client = new SSMClient({}); try { await client.send(new DeleteDocumentCommand({ Name: documentName })); console.log(`Document '${documentName}' deleted.`); return { Deleted: true }; } catch (caught) { if (caught instanceof Error && caught.name === "MissingParameter") { console.warn(`${caught.message}. Did you provide this value?`); } else { throw caught; } } }; • For API details, see DeleteDocument in AWS SDK for JavaScript API Reference. PowerShell Tools for PowerShell Example 1: This example deletes a document. There is no output if the command succeeds. Actions 2626 AWS Systems Manager User Guide Remove-SSMDocument -Name "RunShellScript" • For API details, see DeleteDocument in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class DocumentWrapper: """Encapsulates AWS Systems Manager Document actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.name = None @classmethod def from_client(cls): ssm_client = boto3.client("ssm") return cls(ssm_client) def delete(self): """ Deletes an AWS Systems Manager document. """ if self.name is None: return try: self.ssm_client.delete_document(Name=self.name) print(f"Deleted document {self.name}.") self.name = None Actions 2627 AWS Systems Manager User Guide except ClientError as err: logger.error( "Couldn't delete %s. Here's why: %s: %s", self.name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise • For API details, see DeleteDocument in AWS SDK for Python (Boto3) API Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteMaintenanceWindow with an AWS SDK or CLI The following code examples show how to use DeleteMaintenanceWindow. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics CLI AWS CLI To delete a maintenance window This delete-maintenance-window example removes the specified maintenance window. aws ssm delete-maintenance-window \ --window-id "mw-1a2b3c4d5e6f7g8h9" Output: { "WindowId":"mw-1a2b3c4d5e6f7g8h9" Actions 2628 AWS Systems Manager } User Guide For more information, see Delete a Maintenance Window (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see DeleteMaintenanceWindow in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Deletes an AWS SSM Maintenance Window asynchronously. * * @param winId The ID of the Maintenance Window to delete. * <p> * This method initiates an asynchronous request to delete an SSM Maintenance Window. * If an exception occurs, it handles the error appropriately. */ public void deleteMaintenanceWindow(String winId) { DeleteMaintenanceWindowRequest windowRequest = DeleteMaintenanceWindowRequest.builder() .windowId(winId) .build(); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { getAsyncClient().deleteMaintenanceWindow(windowRequest) .thenAccept(response ->
systems-manager-ug-763
systems-manager-ug.pdf
763
in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Deletes an AWS SSM Maintenance Window asynchronously. * * @param winId The ID of the Maintenance Window to delete. * <p> * This method initiates an asynchronous request to delete an SSM Maintenance Window. * If an exception occurs, it handles the error appropriately. */ public void deleteMaintenanceWindow(String winId) { DeleteMaintenanceWindowRequest windowRequest = DeleteMaintenanceWindowRequest.builder() .windowId(winId) .build(); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { getAsyncClient().deleteMaintenanceWindow(windowRequest) .thenAccept(response -> { System.out.println("The maintenance window was successfully deleted."); }) .exceptionally(ex -> { throw new CompletionException(ex); }).join(); }).exceptionally(ex -> { Actions 2629 AWS Systems Manager User Guide Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw new RuntimeException("SSM error: " + cause.getMessage(), cause); } else { throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause); } }); try { future.join(); } catch (CompletionException ex) { throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex; } } • For API details, see DeleteMaintenanceWindow in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { DeleteMaintenanceWindowCommand, SSMClient } from "@aws-sdk/client-ssm"; import { parseArgs } from "node:util"; /** * Delete an SSM maintenance window. * @param {{ windowId: string }} */ export const main = async ({ windowId }) => { const client = new SSMClient({}); try { Actions 2630 AWS Systems Manager User Guide await client.send( new DeleteMaintenanceWindowCommand({ WindowId: windowId }), ); console.log(`Maintenance window '${windowId}' deleted.`); return { Deleted: true }; } catch (caught) { if (caught instanceof Error && caught.name === "MissingParameter") { console.warn(`${caught.message}. Did you provide this value?`); } else { throw caught; } } }; • For API details, see DeleteMaintenanceWindow in AWS SDK for JavaScript API Reference. PowerShell Tools for PowerShell Example 1: This example removes a maintenance window. Remove-SSMMaintenanceWindow -WindowId "mw-06d59c1a07c022145" Output: mw-06d59c1a07c022145 • For API details, see DeleteMaintenanceWindow in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 2631 AWS Systems Manager User Guide class MaintenanceWindowWrapper: """Encapsulates AWS Systems Manager maintenance window actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.window_id = None self.name = None @classmethod def from_client(cls): ssm_client = boto3.client("ssm") return cls(ssm_client) def delete(self): """ Delete the associated AWS Systems Manager maintenance window. """ if self.window_id is None: return try: self.ssm_client.delete_maintenance_window(WindowId=self.window_id) logger.info("Deleted maintenance window %s.", self.window_id) print(f"Deleted maintenance window {self.name}") self.window_id = None except ClientError as err: logger.error( "Couldn't delete maintenance window %s. Here's why: %s: %s", self.window_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise • For API details, see DeleteMaintenanceWindow in AWS SDK for Python (Boto3) API Reference. Actions 2632 AWS Systems Manager User Guide For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteOpsItem with an AWS SDK The following code example shows how to use DeleteOpsItem. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class OpsItemWrapper: """Encapsulates AWS Systems Manager OpsItem actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.id = None @classmethod def from_client(cls): """ :return: A OpsItemWrapper instance. """ ssm_client = boto3.client("ssm") return cls(ssm_client) def delete(self): """ Delete the OpsItem. """ if self.id is None: Actions 2633 AWS Systems Manager return User Guide try: self.ssm_client.delete_ops_item(OpsItemId=self.id) print(f"Deleted ops item with id {self.id}") self.id = None except ClientError as err: logger.error( "Couldn't delete ops item %s. Here's why: %s: %s", self.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise • For API details, see DeleteOpsItem in AWS SDK for Python (Boto3) API Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteParameter with a CLI The following code examples show how to use DeleteParameter. CLI AWS CLI To delete a parameter The following delete-parameter example deletes the specified single parameter. aws ssm delete-parameter \ --name "MyParameter" This command produces no output. For more information, see Working with Parameter Store in the AWS Systems Manager User Guide. • For API details, see DeleteParameter in AWS CLI Command Reference. Actions 2634 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example
systems-manager-ug-764
systems-manager-ug.pdf
764
with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteParameter with a CLI The following code examples show how to use DeleteParameter. CLI AWS CLI To delete a parameter The following delete-parameter example deletes the specified single parameter. aws ssm delete-parameter \ --name "MyParameter" This command produces no output. For more information, see Working with Parameter Store in the AWS Systems Manager User Guide. • For API details, see DeleteParameter in AWS CLI Command Reference. Actions 2634 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example deletes a parameter. There is no output if the command succeeds. Remove-SSMParameter -Name "helloWorld" • For API details, see DeleteParameter in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeletePatchBaseline with a CLI The following code examples show how to use DeletePatchBaseline. CLI AWS CLI To delete a patch baseline The following delete-patch-baseline example deletes the specified patch baseline. aws ssm delete-patch-baseline \ --baseline-id "pb-045f10b4f382baeda" Output: { "BaselineId": "pb-045f10b4f382baeda" } For more information, see Update or Delete a Patch Baseline (Console) in the AWS Systems Manager User Guide. • For API details, see DeletePatchBaseline in AWS CLI Command Reference. Actions 2635 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example deletes a patch baseline. Remove-SSMPatchBaseline -BaselineId "pb-045f10b4f382baeda" Output: pb-045f10b4f382baeda • For API details, see DeletePatchBaseline in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeregisterManagedInstance with a CLI The following code examples show how to use DeregisterManagedInstance. CLI AWS CLI To deregister a managed instance The following deregister-managed-instance example deregisters the specified managed instance. aws ssm deregister-managed-instance \ --instance-id 'mi-08ab247cdfEXAMPLE' This command produces no output. For more information, see Deregistering managed nodes in a hybrid and multicloud environment in the AWS Systems Manager User Guide. • For API details, see DeregisterManagedInstance in AWS CLI Command Reference. Actions 2636 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example deregisters a managed instance. There is no output if the command succeeds. Unregister-SSMManagedInstance -InstanceId "mi-08ab247cdf1046573" • For API details, see DeregisterManagedInstance in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeregisterPatchBaselineForPatchGroup with a CLI The following code examples show how to use DeregisterPatchBaselineForPatchGroup. CLI AWS CLI To deregister a patch group from a patch baseline The following deregister-patch-baseline-for-patch-group example deregisters the specified patch group from the specified patch baseline. aws ssm deregister-patch-baseline-for-patch-group \ --patch-group "Production" \ --baseline-id "pb-0ca44a362fEXAMPLE" Output: { "PatchGroup":"Production", "BaselineId":"pb-0ca44a362fEXAMPLE" } Actions 2637 AWS Systems Manager User Guide For more information, see Add a Patch Group to a Patch Baseline in the AWS Systems Manager User Guide. • For API details, see DeregisterPatchBaselineForPatchGroup in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example deregisters a patch group from a patch baseline. Unregister-SSMPatchBaselineForPatchGroup -BaselineId "pb-045f10b4f382baeda" - PatchGroup "Production" Output: BaselineId PatchGroup ---------- ---------- pb-045f10b4f382baeda Production • For API details, see DeregisterPatchBaselineForPatchGroup in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeregisterTargetFromMaintenanceWindow with a CLI The following code examples show how to use DeregisterTargetFromMaintenanceWindow. CLI AWS CLI To remove a target from a maintenance window The following deregister-target-from-maintenance-window example removes the specified target from the specified maintenance window. Actions 2638 AWS Systems Manager User Guide aws ssm deregister-target-from-maintenance-window \ --window-id "mw-ab12cd34ef56gh78" \ --window-target-id "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2" Output: { "WindowId":"mw-ab12cd34ef56gh78", "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2" } For more information, see Update a Maintenance Window (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see DeregisterTargetFromMaintenanceWindow in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example removes a target from a maintenance window. Unregister-SSMTargetFromMaintenanceWindow -WindowTargetId "6ab5c208-9fc4-4697-84b7-b02a6cc25f7d" -WindowId "mw-06cf17cbefcb4bf4f" Output: WindowId WindowTargetId -------- -------------- mw-06cf17cbefcb4bf4f 6ab5c208-9fc4-4697-84b7-b02a6cc25f7d • For API details, see DeregisterTargetFromMaintenanceWindow in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 2639 AWS Systems Manager User Guide Use DeregisterTaskFromMaintenanceWindow with a CLI The following code examples show how to
systems-manager-ug-765
systems-manager-ug.pdf
765
see DeregisterTargetFromMaintenanceWindow in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example removes a target from a maintenance window. Unregister-SSMTargetFromMaintenanceWindow -WindowTargetId "6ab5c208-9fc4-4697-84b7-b02a6cc25f7d" -WindowId "mw-06cf17cbefcb4bf4f" Output: WindowId WindowTargetId -------- -------------- mw-06cf17cbefcb4bf4f 6ab5c208-9fc4-4697-84b7-b02a6cc25f7d • For API details, see DeregisterTargetFromMaintenanceWindow in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 2639 AWS Systems Manager User Guide Use DeregisterTaskFromMaintenanceWindow with a CLI The following code examples show how to use DeregisterTaskFromMaintenanceWindow. CLI AWS CLI To remove a task from a maintenance window The following deregister-task-from-maintenance-window example removes the specified task from the specified maintenance window. aws ssm deregister-task-from-maintenance-window \ --window-id "mw-ab12cd34ef56gh78" \ --window-task-id "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6c" Output: { "WindowTaskId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6c", "WindowId":"mw-ab12cd34ef56gh78" } For more information, see Systems Manager Maintenance Windows Tutorials (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see DeregisterTaskFromMaintenanceWindow in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example removes a task from a maintenance window. Unregister-SSMTaskFromMaintenanceWindow -WindowTaskId "f34a2c47-ddfd-4c85- a88d-72366b69af1b" -WindowId "mw-03a342e62c96d31b0" Output: WindowId WindowTaskId Actions 2640 AWS Systems Manager User Guide -------- ------------ mw-03a342e62c96d31b0 f34a2c47-ddfd-4c85-a88d-72366b69af1b • For API details, see DeregisterTaskFromMaintenanceWindow in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeActivations with a CLI The following code examples show how to use DescribeActivations. CLI AWS CLI To describe activations The following describe-activations example lists details about the activations in your AWS account. aws ssm describe-activations Output: { "ActivationList": [ { "ActivationId": "5743558d-563b-4457-8682-d16c3EXAMPLE", "Description": "Example1", "IamRole": "HybridWebServersRole, "RegistrationLimit": 5, "RegistrationsCount": 5, "ExpirationDate": 1584316800.0, "Expired": false, "CreatedDate": 1581954699.792 }, { "ActivationId": "3ee0322b-f62d-40eb-b672-13ebfEXAMPLE", Actions 2641 AWS Systems Manager User Guide "Description": "Example2", "IamRole": "HybridDatabaseServersRole", "RegistrationLimit": 5, "RegistrationsCount": 5, "ExpirationDate": 1580515200.0, "Expired": true, "CreatedDate": 1578064132.002 }, ] } For more information, see Step 4: Create a Managed-Instance Activation for a Hybrid Environment in the AWS Systems Manager User Guide. • For API details, see DescribeActivations in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example provides details about the activations on your account. Get-SSMActivation Output: ActivationId : 08e51e79-1e36-446c-8e63-9458569c1363 CreatedDate : 3/1/2017 12:01:51 AM DefaultInstanceName : MyWebServers Description : ExpirationDate : 3/2/2017 12:01:51 AM Expired : False IamRole : AutomationRole RegistrationLimit : 10 RegistrationsCount : 0 • For API details, see DescribeActivations in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 2642 AWS Systems Manager User Guide Use DescribeAssociation with a CLI The following code examples show how to use DescribeAssociation. CLI AWS CLI Example 1: To get details of an association The following describe-association example describes the association for the specified association ID. aws ssm describe-association \ --association-id "8dfe3659-4309-493a-8755-0123456789ab" Output: { "AssociationDescription": { "Name": "AWS-GatherSoftwareInventory", "AssociationVersion": "1", "Date": 1534864780.995, "LastUpdateAssociationDate": 1543235759.81, "Overview": { "Status": "Success", "AssociationStatusAggregatedCount": { "Success": 2 } }, "DocumentVersion": "$DEFAULT", "Parameters": { "applications": [ "Enabled" ], "awsComponents": [ "Enabled" ], "customInventory": [ "Enabled" ], "files": [ "" Actions 2643 AWS Systems Manager ], "instanceDetailedInformation": [ "Enabled" User Guide ], "networkConfig": [ "Enabled" ], "services": [ "Enabled" ], "windowsRegistry": [ "" ], "windowsRoles": [ "Enabled" ], "windowsUpdates": [ "Enabled" ] }, "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "Targets": [ { "Key": "InstanceIds", "Values": [ "*" ] } ], "ScheduleExpression": "rate(24 hours)", "LastExecutionDate": 1550501886.0, "LastSuccessfulExecutionDate": 1550501886.0, "AssociationName": "Inventory-Association" } } For more information, see Editing and creating a new version of an association in the AWS Systems Manager User Guide. Example 2: To get details of an association for a specific instance and document The following describe-association example describes the association between an instance and a document. Actions 2644 AWS Systems Manager User Guide aws ssm describe-association \ --instance-id "i-1234567890abcdef0" \ --name "AWS-UpdateSSMAgent" Output: { "AssociationDescription": { "Status": { "Date": 1487876122.564, "Message": "Associated with AWS-UpdateSSMAgent", "Name": "Associated" }, "Name": "AWS-UpdateSSMAgent", "InstanceId": "i-1234567890abcdef0", "Overview": { "Status": "Pending", "DetailedStatus": "Associated", "AssociationStatusAggregatedCount": { "Pending": 1 } }, "AssociationId": "d8617c07-2079-4c18-9847-1234567890ab", "DocumentVersion": "$DEFAULT", "LastUpdateAssociationDate": 1487876122.564, "Date": 1487876122.564, "Targets": [ { "Values": [ "i-1234567890abcdef0" ], "Key": "InstanceIds" } ] } } For more information, see Editing and creating a new version of an association in the AWS Systems Manager User Guide. • For API details, see DescribeAssociation in AWS CLI Command Reference. Actions 2645 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example describes the association between an instance and a document. Get-SSMAssociation -InstanceId "i-0000293ffd8c57862" -Name "AWS-UpdateSSMAgent" Output: Name : AWS-UpdateSSMAgent InstanceId : i-0000293ffd8c57862 Date : 2/23/2017 6:55:22 PM Status.Name :
systems-manager-ug-766
systems-manager-ug.pdf
766
{ "Pending": 1 } }, "AssociationId": "d8617c07-2079-4c18-9847-1234567890ab", "DocumentVersion": "$DEFAULT", "LastUpdateAssociationDate": 1487876122.564, "Date": 1487876122.564, "Targets": [ { "Values": [ "i-1234567890abcdef0" ], "Key": "InstanceIds" } ] } } For more information, see Editing and creating a new version of an association in the AWS Systems Manager User Guide. • For API details, see DescribeAssociation in AWS CLI Command Reference. Actions 2645 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example describes the association between an instance and a document. Get-SSMAssociation -InstanceId "i-0000293ffd8c57862" -Name "AWS-UpdateSSMAgent" Output: Name : AWS-UpdateSSMAgent InstanceId : i-0000293ffd8c57862 Date : 2/23/2017 6:55:22 PM Status.Name : Pending Status.Date : 2/20/2015 8:31:11 AM Status.Message : temp_status_change Status.AdditionalInfo : Additional-Config-Needed • For API details, see DescribeAssociation in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeAssociationExecutionTargets with a CLI The following code examples show how to use DescribeAssociationExecutionTargets. CLI AWS CLI To get details of an association execution The following describe-association-execution-targets example describes the specified association execution. aws ssm describe-association-execution-targets \ --association-id "8dfe3659-4309-493a-8755-0123456789ab" \ --execution-id "7abb6378-a4a5-4f10-8312-0123456789ab" Output: Actions 2646 AWS Systems Manager User Guide { "AssociationExecutionTargets": [ { "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "AssociationVersion": "1", "ExecutionId": "7abb6378-a4a5-4f10-8312-0123456789ab", "ResourceId": "i-1234567890abcdef0", "ResourceType": "ManagedInstance", "Status": "Success", "DetailedStatus": "Success", "LastExecutionDate": 1550505538.497, "OutputSource": { "OutputSourceId": "97fff367-fc5a-4299-aed8-0123456789ab", "OutputSourceType": "RunCommand" } } ] } For more information, see Viewing association histories in the AWS Systems Manager User Guide. • For API details, see DescribeAssociationExecutionTargets in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example displays the resource ID and its execution status that are part of the the association execution targets Get-SSMAssociationExecutionTarget -AssociationId 123a45a0- c678-9012-3456-78901234db5e -ExecutionId 123a45a0-c678-9012-3456-78901234db5e | Select-Object ResourceId, Status Output: ResourceId Status ---------- ------ i-0b1b2a3456f7a890b Success i-01c12a45d6fc7a89f Success i-0a1caf234f56d7dc8 Success Actions 2647 AWS Systems Manager User Guide i-012a3fd45af6dbcfe Failed i-0ddc1df23c4a5fb67 Success Example 2: This command checks the particular execution of a particular automation since yesterday, where a command document is associated. It further checkes if the association execution failed, and if so, it will display the command invocation details for the execution along with the instance id $AssociationExecution= Get-SSMAssociationExecutionTarget - AssociationId 1c234567-890f-1aca-a234-5a678d901cb0 -ExecutionId 12345ca12-3456-2345-2b45-23456789012 | Where-Object {$_.LastExecutionDate -gt (Get-Date -Hour 00 -Minute 00).AddDays(-1)} foreach ($execution in $AssociationExecution) { if($execution.Status -ne 'Success'){ Write-Output "There was an issue executing the association $($execution.AssociationId) on $($execution.ResourceId)" Get-SSMCommandInvocation -CommandId $execution.OutputSource.OutputSourceId -Detail:$true | Select-Object - ExpandProperty CommandPlugins } } Output: There was an issue executing the association 1c234567-890f-1aca-a234-5a678d901cb0 on i-0a1caf234f56d7dc8 Name : aws:runPowerShellScript Output : ----------ERROR------- failed to run commands: exit status 1 OutputS3BucketName : OutputS3KeyPrefix : OutputS3Region : eu-west-1 ResponseCode : 1 ResponseFinishDateTime : 5/29/2019 11:04:49 AM ResponseStartDateTime : 5/29/2019 11:04:49 AM StandardErrorUrl : StandardOutputUrl : Actions 2648 AWS Systems Manager User Guide Status : Failed StatusDetails : Failed • For API details, see DescribeAssociationExecutionTargets in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeAssociationExecutions with a CLI The following code examples show how to use DescribeAssociationExecutions. CLI AWS CLI Example 1: To get details of all executions for an association The following describe-association-executions example describes all executions of the specified association. aws ssm describe-association-executions \ --association-id "8dfe3659-4309-493a-8755-0123456789ab" Output: { "AssociationExecutions": [ { "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "AssociationVersion": "1", "ExecutionId": "474925ef-1249-45a2-b93d-0123456789ab", "Status": "Success", "DetailedStatus": "Success", "CreatedTime": 1550505827.119, "ResourceCountByStatus": "{Success=1}" }, { "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "AssociationVersion": "1", Actions 2649 AWS Systems Manager User Guide "ExecutionId": "7abb6378-a4a5-4f10-8312-0123456789ab", "Status": "Success", "DetailedStatus": "Success", "CreatedTime": 1550505536.843, "ResourceCountByStatus": "{Success=1}" }, ... ] } For more information, see Viewing association histories in the AWS Systems Manager User Guide. Example 2: To get details of all executions for an association after a specific date and time The following describe-association-executions example describes all executions of an association after the specified date and time. aws ssm describe-association-executions \ --association-id "8dfe3659-4309-493a-8755-0123456789ab" \ --filters "Key=CreatedTime,Value=2019-02-18T16:00:00Z,Type=GREATER_THAN" Output: { "AssociationExecutions": [ { "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "AssociationVersion": "1", "ExecutionId": "474925ef-1249-45a2-b93d-0123456789ab", "Status": "Success", "DetailedStatus": "Success", "CreatedTime": 1550505827.119, "ResourceCountByStatus": "{Success=1}" }, { "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "AssociationVersion": "1", "ExecutionId": "7abb6378-a4a5-4f10-8312-0123456789ab", "Status": "Success", "DetailedStatus": "Success", Actions 2650 AWS Systems Manager User Guide "CreatedTime": 1550505536.843, "ResourceCountByStatus": "{Success=1}" }, ... ] } For more information, see Viewing association histories in the AWS Systems Manager User Guide. • For API details, see DescribeAssociationExecutions in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example returns the executions for the association ID provided Get-SSMAssociationExecution -AssociationId 123a45a0-c678-9012-3456-78901234db5e Output: AssociationId : 123a45a0-c678-9012-3456-78901234db5e AssociationVersion : 2 CreatedTime : 3/2/2019 8:53:29 AM DetailedStatus : ExecutionId : 123a45a0-c678-9012-3456-78901234db5e LastExecutionDate : 1/1/0001 12:00:00 AM ResourceCountByStatus : {Success=4} Status : Success • For API details, see DescribeAssociationExecutions in AWS Tools for PowerShell Cmdlet Reference. For
systems-manager-ug-767
systems-manager-ug.pdf
767
2650 AWS Systems Manager User Guide "CreatedTime": 1550505536.843, "ResourceCountByStatus": "{Success=1}" }, ... ] } For more information, see Viewing association histories in the AWS Systems Manager User Guide. • For API details, see DescribeAssociationExecutions in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example returns the executions for the association ID provided Get-SSMAssociationExecution -AssociationId 123a45a0-c678-9012-3456-78901234db5e Output: AssociationId : 123a45a0-c678-9012-3456-78901234db5e AssociationVersion : 2 CreatedTime : 3/2/2019 8:53:29 AM DetailedStatus : ExecutionId : 123a45a0-c678-9012-3456-78901234db5e LastExecutionDate : 1/1/0001 12:00:00 AM ResourceCountByStatus : {Success=4} Status : Success • For API details, see DescribeAssociationExecutions in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeAutomationExecutions with a CLI The following code examples show how to use DescribeAutomationExecutions. Actions 2651 AWS Systems Manager CLI AWS CLI User Guide To describe an automation execution The following describe-automation-executions example displays details about an Automation execution. aws ssm describe-automation-executions \ --filters Key=ExecutionId,Values=73c8eef8-f4ee-4a05-820c-e354fEXAMPLE Output: { "AutomationExecutionMetadataList": [ { "AutomationExecutionId": "73c8eef8-f4ee-4a05-820c-e354fEXAMPLE", "DocumentName": "AWS-StartEC2Instance", "DocumentVersion": "1", "AutomationExecutionStatus": "Success", "ExecutionStartTime": 1583737233.748, "ExecutionEndTime": 1583737234.719, "ExecutedBy": "arn:aws:sts::29884EXAMPLE:assumed-role/ mw_service_role/OrchestrationService", "LogFile": "", "Outputs": {}, "Mode": "Auto", "Targets": [], "ResolvedTargets": { "ParameterValues": [], "Truncated": false }, "AutomationType": "Local" } ] } For more information, see Running a Simple Automation Workflow in the AWS Systems Manager User Guide. • For API details, see DescribeAutomationExecutions in AWS CLI Command Reference. Actions 2652 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example describes all active and terminated Automation Executions associated with your account. Get-SSMAutomationExecutionList Output: AutomationExecutionId : 4105a4fc-f944-11e6-9d32-8fb2db27a909 AutomationExecutionStatus : Failed DocumentName : AWS-UpdateLinuxAmi DocumentVersion : 1 ExecutedBy : admin ExecutionEndTime : 2/22/2017 9:17:08 PM ExecutionStartTime : 2/22/2017 9:17:02 PM LogFile : Outputs : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]} Example 2: This example displays ExecutionID, document, execution start/end timestamp for executions with AutomationExecutionStatus other than 'Success' Get-SSMAutomationExecutionList | Where-Object AutomationExecutionStatus -ne "Success" | Select-Object AutomationExecutionId, DocumentName, AutomationExecutionStatus, ExecutionStartTime, ExecutionEndTime | Format-Table - AutoSize Output: AutomationExecutionId DocumentName AutomationExecutionStatus ExecutionStartTime ExecutionEndTime --------------------- ------------ ------------------------- ------------------ ---------------- e1d2bad3-4567-8901-ae23-456c7c8901be AWS-UpdateWindowsAmi Cancelled 4/16/2019 5:37:04 AM 4/16/2019 5:47:29 AM 61234567-a7f8-90e1-2b34-567b8bf9012c Fixed-UpdateAmi Cancelled 4/16/2019 5:33:04 AM 4/16/2019 5:40:15 AM Actions 2653 AWS Systems Manager User Guide 91234d56-7e89-0ac1-2aee-34ea5d6a7c89 AWS-UpdateWindowsAmi Failed 4/16/2019 5:22:46 AM 4/16/2019 5:27:29 AM • For API details, see DescribeAutomationExecutions in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeAutomationStepExecutions with a CLI The following code examples show how to use DescribeAutomationStepExecutions. CLI AWS CLI Example 1: To describe all steps for an automation execution The following describe-automation-step-executions example displays details about the steps of an Automation execution. aws ssm describe-automation-step-executions \ --automation-execution-id 73c8eef8-f4ee-4a05-820c-e354fEXAMPLE Output: { "StepExecutions": [ { "StepName": "startInstances", "Action": "aws:changeInstanceState", "ExecutionStartTime": 1583737234.134, "ExecutionEndTime": 1583737234.672, "StepStatus": "Success", "Inputs": { "DesiredState": "\"running\"", "InstanceIds": "[\"i-0cb99161f6EXAMPLE\"]" }, "Outputs": { Actions 2654 AWS Systems Manager User Guide "InstanceStates": [ "running" ] }, "StepExecutionId": "95e70479-cf20-4d80-8018-7e4e2EXAMPLE", "OverriddenParameters": {} } ] } Example 2: To describe a specific step for an automation execution The following describe-automation-step-executions example displays details about a specific step of an Automation execution. aws ssm describe-automation-step-executions \ --automation-execution-id 73c8eef8-f4ee-4a05-820c-e354fEXAMPLE \ --filters Key=StepExecutionId,Values=95e70479-cf20-4d80-8018-7e4e2EXAMPLE For more information, see Running an Automation Workflow Step by Step (Command Line) in the AWS Systems Manager User Guide. • For API details, see DescribeAutomationStepExecutions in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This exmaple displays information about all active and terminated step executions in an Automation workflow. Get-SSMAutomationStepExecution -AutomationExecutionId e1d2bad3-4567-8901- ae23-456c7c8901be | Select-Object StepName, Action, StepStatus Output: StepName Action StepStatus -------- ------ ---------- LaunchInstance aws:runInstances Success OSCompatibilityCheck aws:runCommand Success RunPreUpdateScript aws:runCommand Success Actions 2655 AWS Systems Manager User Guide UpdateEC2Config aws:runCommand Cancelled UpdateSSMAgent aws:runCommand Pending UpdateAWSPVDriver aws:runCommand Pending UpdateAWSEnaNetworkDriver aws:runCommand Pending UpdateAWSNVMe aws:runCommand Pending InstallWindowsUpdates aws:runCommand Pending RunPostUpdateScript aws:runCommand Pending RunSysprepGeneralize aws:runCommand Pending StopInstance aws:changeInstanceState Pending CreateImage aws:createImage Pending TerminateInstance aws:changeInstanceState Pending • For API details, see DescribeAutomationStepExecutions in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeAvailablePatches with a CLI The following code examples show how to use DescribeAvailablePatches. CLI AWS CLI To get available patches The following describe-available-patches example retrieves details about all available patches for Windows Server 2019 that have a MSRC severity of Critical. aws ssm describe-available-patches \ -- filters "Key=PRODUCT,Values=WindowsServer2019" "Key=MSRC_SEVERITY,Values=Critical" Output: { "Patches": [ { Actions 2656 AWS Systems Manager User Guide "Id": "fe6bd8c2-3752-4c8b-ab3e-1a7ed08767ba", "ReleaseDate": 1544047205.0, "Title": "2018-11 Update for Windows Server 2019 for x64-based Systems (KB4470788)", "Description": "Install this update to resolve
systems-manager-ug-768
systems-manager-ug.pdf
768
an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeAvailablePatches with a CLI The following code examples show how to use DescribeAvailablePatches. CLI AWS CLI To get available patches The following describe-available-patches example retrieves details about all available patches for Windows Server 2019 that have a MSRC severity of Critical. aws ssm describe-available-patches \ -- filters "Key=PRODUCT,Values=WindowsServer2019" "Key=MSRC_SEVERITY,Values=Critical" Output: { "Patches": [ { Actions 2656 AWS Systems Manager User Guide "Id": "fe6bd8c2-3752-4c8b-ab3e-1a7ed08767ba", "ReleaseDate": 1544047205.0, "Title": "2018-11 Update for Windows Server 2019 for x64-based Systems (KB4470788)", "Description": "Install this update to resolve issues in Windows. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article for more information. After you install this item, you may have to restart your computer.", "ContentUrl": "https://support.microsoft.com/en-us/kb/4470788", "Vendor": "Microsoft", "ProductFamily": "Windows", "Product": "WindowsServer2019", "Classification": "SecurityUpdates", "MsrcSeverity": "Critical", "KbNumber": "KB4470788", "MsrcNumber": "", "Language": "All" }, { "Id": "c96115e1-5587-4115-b851-22baa46a3f11", "ReleaseDate": 1549994410.0, "Title": "2019-02 Security Update for Adobe Flash Player for Windows Server 2019 for x64-based Systems (KB4487038)", "Description": "A security issue has been identified in a Microsoft software product that could affect your system. You can help protect your system by installing this update from Microsoft. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article. After you install this update, you may have to restart your system.", "ContentUrl": "https://support.microsoft.com/en-us/kb/4487038", "Vendor": "Microsoft", "ProductFamily": "Windows", "Product": "WindowsServer2019", "Classification": "SecurityUpdates", "MsrcSeverity": "Critical", "KbNumber": "KB4487038", "MsrcNumber": "", "Language": "All" }, ... ] } To get details of a specific patch Actions 2657 AWS Systems Manager User Guide The following describe-available-patches example retrieves details about the specified patch. aws ssm describe-available-patches \ --filters "Key=PATCH_ID,Values=KB4480979" Output: { "Patches": [ { "Id": "680861e3-fb75-432e-818e-d72e5f2be719", "ReleaseDate": 1546970408.0, "Title": "2019-01 Security Update for Adobe Flash Player for Windows Server 2016 for x64-based Systems (KB4480979)", "Description": "A security issue has been identified in a Microsoft software product that could affect your system. You can help protect your system by installing this update from Microsoft. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article. After you install this update, you may have to restart your system.", "ContentUrl": "https://support.microsoft.com/en-us/kb/4480979", "Vendor": "Microsoft", "ProductFamily": "Windows", "Product": "WindowsServer2016", "Classification": "SecurityUpdates", "MsrcSeverity": "Critical", "KbNumber": "KB4480979", "MsrcNumber": "", "Language": "All" } ] } For more information, see How Patch Manager Operations Work in the AWS Systems Manager User Guide. • For API details, see DescribeAvailablePatches in AWS CLI Command Reference. Actions 2658 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example gets all available patches for Windows Server 2012 that have a MSRC severity of Critical. The syntax used by this example requires PowerShell version 3 or later. $filter1 = @{Key="PRODUCT";Values=@("WindowsServer2012")} $filter2 = @{Key="MSRC_SEVERITY";Values=@("Critical")} Get-SSMAvailablePatch -Filter $filter1,$filter2 Output: Classification : SecurityUpdates ContentUrl : https://support.microsoft.com/en-us/kb/2727528 Description : A security issue has been identified that could allow an unauthenticated remote attacker to compromise your system and gain control over it. You can help protect your system by installing this update from Microsoft. After you install this update, you may have to restart your system. Id : 1eb507be-2040-4eeb-803d-abc55700b715 KbNumber : KB2727528 Language : All MsrcNumber : MS12-072 MsrcSeverity : Critical Product : WindowsServer2012 ProductFamily : Windows ReleaseDate : 11/13/2012 6:00:00 PM Title : Security Update for Windows Server 2012 (KB2727528) Vendor : Microsoft ... Example 2: With PowerShell version 2, you must use New-Object to create each filter. $filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter $filter1.Key = "PRODUCT" $filter1.Values = "WindowsServer2012" $filter2 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter Actions 2659 AWS Systems Manager User Guide $filter2.Key = "MSRC_SEVERITY" $filter2.Values = "Critical" Get-SSMAvailablePatch -Filter $filter1,$filter2 Example 3: This example fetches all the updates which are released in last 20 days and applicable to products matching WindowsServer2019 Get-SSMAvailablePatch | Where-Object ReleaseDate -ge (Get-Date).AddDays(-20) | Where-Object Product -eq "WindowsServer2019" | Select-Object ReleaseDate, Product, Title Output: ReleaseDate Product Title ----------- ------- ----- 4/9/2019 5:00:12 PM WindowsServer2019 2019-04 Security Update for Adobe Flash Player for Windows Server 2019 for x64-based Systems (KB4493478) 4/9/2019 5:00:06 PM WindowsServer2019 2019-04 Cumulative Update for Windows Server 2019 for x64-based Systems (KB4493509) 4/2/2019 5:00:06 PM WindowsServer2019 2019-03 Servicing Stack Update for Windows Server 2019 for x64-based Systems (KB4493510) • For API details, see DescribeAvailablePatches in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeDocument with a CLI The following code examples show how to use DescribeDocument. CLI AWS CLI To display details of a document Actions 2660 AWS Systems Manager User Guide The following describe-document example displays details about a Systems Manager document in your AWS account.
systems-manager-ug-769
systems-manager-ug.pdf
769
for Windows Server 2019 for x64-based Systems (KB4493510) • For API details, see DescribeAvailablePatches in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeDocument with a CLI The following code examples show how to use DescribeDocument. CLI AWS CLI To display details of a document Actions 2660 AWS Systems Manager User Guide The following describe-document example displays details about a Systems Manager document in your AWS account. aws ssm describe-document \ --name "Example" Output: { "Document": { "Hash": "fc2410281f40779e694a8b95975d0f9f316da8a153daa94e3d9921102EXAMPLE", "HashType": "Sha256", "Name": "Example", "Owner": "29884EXAMPLE", "CreatedDate": 1583257938.266, "Status": "Active", "DocumentVersion": "1", "Description": "Document Example", "Parameters": [ { "Name": "AutomationAssumeRole", "Type": "String", "Description": "(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to execute this document.", "DefaultValue": "" }, { "Name": "InstanceId", "Type": "String", "Description": "(Required) The ID of the Amazon EC2 instance.", "DefaultValue": "" } ], "PlatformTypes": [ "Windows", "Linux" ], "DocumentType": "Automation", "SchemaVersion": "0.3", "LatestVersion": "1", "DefaultVersion": "1", Actions 2661 AWS Systems Manager User Guide "DocumentFormat": "YAML", "Tags": [] } } For more information, see Creating Systems Manager Documents in the AWS Systems Manager User Guide. • For API details, see DescribeDocument in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example returns information about a document. Get-SSMDocumentDescription -Name "RunShellScript" Output: CreatedDate : 2/24/2017 5:25:13 AM DefaultVersion : 1 Description : Run an updated script DocumentType : Command DocumentVersion : 1 Hash : f775e5df4904c6fa46686c4722fae9de1950dace25cd9608ff8d622046b68d9b HashType : Sha256 LatestVersion : 1 Name : RunShellScript Owner : 123456789012 Parameters : {commands} PlatformTypes : {Linux} SchemaVersion : 2.0 Sha1 : Status : Active • For API details, see DescribeDocument in AWS Tools for PowerShell Cmdlet Reference. Actions 2662 AWS Systems Manager User Guide For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeDocumentPermission with a CLI The following code examples show how to use DescribeDocumentPermission. CLI AWS CLI To describe document permissions The following describe-document-permission example displays permission details about a Systems Manager document that is shared publicly. aws ssm describe-document-permission \ --name "Example" \ --permission-type "Share" Output: { "AccountIds": [ "all" ], "AccountSharingInfoList": [ { "AccountId": "all", "SharedDocumentVersion": "$DEFAULT" } ] } For more information, see Share a Systems Manager Document in the AWS Systems Manager User Guide. • For API details, see DescribeDocumentPermission in AWS CLI Command Reference. Actions 2663 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example lists all the versions for a document. Get-SSMDocumentVersionList -Name "RunShellScript" Output: CreatedDate DocumentVersion IsDefaultVersion Name ----------- --------------- ---------------- ---- 2/24/2017 5:25:13 AM 1 True RunShellScript • For API details, see DescribeDocumentPermission in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeEffectiveInstanceAssociations with a CLI The following code examples show how to use DescribeEffectiveInstanceAssociations. CLI AWS CLI To get details of the effective associations for an instance The following describe-effective-instance-associations example retrieves details about the effective associations for an instance. Command: aws ssm describe-effective-instance-associations --instance- id "i-1234567890abcdef0" Output: Actions 2664 AWS Systems Manager User Guide { "Associations": [ { "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "InstanceId": "i-1234567890abcdef0", "Content": "{\n \"schemaVersion\": \"1.2\",\n \"description\": \"Update the Amazon SSM Agent to the latest version or specified version.\",\n \"parameters\": {\n \"version\": {\n \"default\": \"\",\n \"description\": \"(Optional) A specific version of the Amazon SSM Agent to install. If not specified, the agent will be updated to the latest version. \",\n \"type\": \"String\"\n },\n \"allowDowngrade \": {\n \"default\": \"false\",\n \"description\": \"(Optional) Allow the Amazon SSM Agent service to be downgraded to an earlier version. If set to false, the service can be upgraded to newer versions only (default). If set to true, specify the earlier version.\",\n \"type \": \"String\",\n \"allowedValues\": [\n \"true\",\n \"false\"\n ]\n }\n },\n \"runtimeConfig \": {\n \"aws:updateSsmAgent\": {\n \"properties\": [\n {\n \"agentName\": \"amazon-ssm-agent\",\n \"source\": \"https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent- manifest.json\",\n \"allowDowngrade\": \"{{ allowDowngrade }}\",\n \"targetVersion\": \"{{ version }}\"\n }\n ]\n }\n }\n}\n", "AssociationVersion": "1" } ] } • For API details, see DescribeEffectiveInstanceAssociations in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example describes the effective associations for an instance. Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" - MaxResult 5 Output: AssociationId Content Actions 2665 AWS Systems Manager User Guide ------------- ------- d8617c07-2079-4c18-9847-1655fc2698b0 {... Example 2: This example displays the contents of the effective associations for an instance. (Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" - MaxResult 5).Content Output: {
systems-manager-ug-770
systems-manager-ug.pdf
770
}\n },\n \"runtimeConfig \": {\n \"aws:updateSsmAgent\": {\n \"properties\": [\n {\n \"agentName\": \"amazon-ssm-agent\",\n \"source\": \"https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent- manifest.json\",\n \"allowDowngrade\": \"{{ allowDowngrade }}\",\n \"targetVersion\": \"{{ version }}\"\n }\n ]\n }\n }\n}\n", "AssociationVersion": "1" } ] } • For API details, see DescribeEffectiveInstanceAssociations in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example describes the effective associations for an instance. Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" - MaxResult 5 Output: AssociationId Content Actions 2665 AWS Systems Manager User Guide ------------- ------- d8617c07-2079-4c18-9847-1655fc2698b0 {... Example 2: This example displays the contents of the effective associations for an instance. (Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" - MaxResult 5).Content Output: { "schemaVersion": "1.2", "description": "Update the Amazon SSM Agent to the latest version or specified version.", "parameters": { "version": { "default": "", "description": "(Optional) A specific version of the Amazon SSM Agent to install. If not specified, the agen t will be updated to the latest version.", "type": "String" }, "allowDowngrade": { "default": "false", "description": "(Optional) Allow the Amazon SSM Agent service to be downgraded to an earlier version. If set to false, the service can be upgraded to newer versions only (default). If set to true, specify the earlier version.", "type": "String", "allowedValues": [ "true", "false" ] } }, "runtimeConfig": { "aws:updateSsmAgent": { "properties": [ { "agentName": "amazon-ssm-agent", "source": "https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ ssm-agent-manifest.json", Actions 2666 AWS Systems Manager User Guide "allowDowngrade": "{{ allowDowngrade }}", "targetVersion": "{{ version }}" } ] } } } • For API details, see DescribeEffectiveInstanceAssociations in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeEffectivePatchesForPatchBaseline with a CLI The following code examples show how to use DescribeEffectivePatchesForPatchBaseline. CLI AWS CLI Example 1: To get all patches defined by a custom patch baseline The following describe-effective-patches-for-patch-baseline example returns the patches defined by a custom patch baseline in the current AWS account. Note that for a custom baseline, only the ID is required for --baseline-id. aws ssm describe-effective-patches-for-patch-baseline \ --baseline-id "pb-08b654cf9b9681f04" Output: { "EffectivePatches": [ { "Patch": { "Id": "fe6bd8c2-3752-4c8b-ab3e-1a7ed08767ba", "ReleaseDate": 1544047205.0, Actions 2667 AWS Systems Manager User Guide "Title": "2018-11 Update for Windows Server 2019 for x64-based Systems (KB4470788)", "Description": "Install this update to resolve issues in Windows. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article for more information. After you install this item, you may have to restart your computer.", "ContentUrl": "https://support.microsoft.com/en-us/kb/4470788", "Vendor": "Microsoft", "ProductFamily": "Windows", "Product": "WindowsServer2019", "Classification": "SecurityUpdates", "MsrcSeverity": "Critical", "KbNumber": "KB4470788", "MsrcNumber": "", "Language": "All" }, "PatchStatus": { "DeploymentStatus": "APPROVED", "ComplianceLevel": "CRITICAL", "ApprovalDate": 1544047205.0 } }, { "Patch": { "Id": "915a6b1a-f556-4d83-8f50-b2e75a9a7e58", "ReleaseDate": 1549994400.0, "Title": "2019-02 Cumulative Update for .NET Framework 3.5 and 4.7.2 for Windows Server 2019 for x64 (KB4483452)", "Description": "A security issue has been identified in a Microsoft software product that could affect your system. You can help protect your system by installing this update from Microsoft. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article. After you install this update, you may have to restart your system.", "ContentUrl": "https://support.microsoft.com/en-us/kb/4483452", "Vendor": "Microsoft", "ProductFamily": "Windows", "Product": "WindowsServer2019", "Classification": "SecurityUpdates", "MsrcSeverity": "Important", "KbNumber": "KB4483452", "MsrcNumber": "", "Language": "All" }, Actions 2668 AWS Systems Manager User Guide "PatchStatus": { "DeploymentStatus": "APPROVED", "ComplianceLevel": "CRITICAL", "ApprovalDate": 1549994400.0 } }, ... ], "NextToken": "--token string truncated--" } Example 2: To get all patches defined by an AWS managed patch baseline The following describe-effective-patches-for-patch-baseline example returns the patches defined by an AWS managed patch baseline. Note that for an AWS managed baseline, the complete baseline ARN is required for --baseline-id aws ssm describe-effective-patches-for-patch-baseline \ --baseline-id "arn:aws:ssm:us-east-2:733109147000:patchbaseline/ pb-020d361a05defe4ed" See example 1 for sample output. For more information, see How Security Patches Are Selected in the AWS Systems Manager User Guide. • For API details, see DescribeEffectivePatchesForPatchBaseline in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists all patch baselines, with a maximum result list of 1. Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" - MaxResult 1 Output: Patch PatchStatus ----- ----------- Actions 2669 AWS Systems Manager User Guide Amazon.SimpleSystemsManagement.Model.Patch Amazon.SimpleSystemsManagement.Model.PatchStatus Example 2: This example displays the patch status for all patch baselines, with a maximum result list of 1. (Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" - MaxResult 1).PatchStatus Output: ApprovalDate DeploymentStatus ------------ ---------------- 12/21/2010 6:00:00 PM APPROVED • For API details, see DescribeEffectivePatchesForPatchBaseline in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeInstanceAssociationsStatus with a CLI The following code examples show how to use DescribeInstanceAssociationsStatus. CLI AWS CLI To describe the status of an instance's
systems-manager-ug-771
systems-manager-ug.pdf
771
the patch status for all patch baselines, with a maximum result list of 1. (Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" - MaxResult 1).PatchStatus Output: ApprovalDate DeploymentStatus ------------ ---------------- 12/21/2010 6:00:00 PM APPROVED • For API details, see DescribeEffectivePatchesForPatchBaseline in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeInstanceAssociationsStatus with a CLI The following code examples show how to use DescribeInstanceAssociationsStatus. CLI AWS CLI To describe the status of an instance's associations This example shows details of the associations for an instance. Command: aws ssm describe-instance-associations-status --instance-id "i-1234567890abcdef0" Output: { Actions 2670 AWS Systems Manager User Guide "InstanceAssociationStatusInfos": [ { "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "Name": "AWS-GatherSoftwareInventory", "DocumentVersion": "1", "AssociationVersion": "1", "InstanceId": "i-1234567890abcdef0", "ExecutionDate": 1550501886.0, "Status": "Success", "ExecutionSummary": "1 out of 1 plugin processed, 1 success, 0 failed, 0 timedout, 0 skipped. ", "AssociationName": "Inventory-Association" }, { "AssociationId": "5c5a31f6-6dae-46f9-944c-0123456789ab", "Name": "AWS-UpdateSSMAgent", "DocumentVersion": "1", "AssociationVersion": "1", "InstanceId": "i-1234567890abcdef0", "ExecutionDate": 1550505828.548, "Status": "Success", "DetailedStatus": "Success", "AssociationName": "UpdateSSMAgent" } ] } • For API details, see DescribeInstanceAssociationsStatus in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example shows details of the associations for an instance. Get-SSMInstanceAssociationsStatus -InstanceId "i-0000293ffd8c57862" Output: AssociationId : d8617c07-2079-4c18-9847-1655fc2698b0 DetailedStatus : Pending DocumentVersion : 1 Actions 2671 AWS Systems Manager User Guide ErrorCode : ExecutionDate : 2/20/2015 8:31:11 AM ExecutionSummary : temp_status_change InstanceId : i-0000293ffd8c57862 Name : AWS-UpdateSSMAgent OutputUrl : Status : Pending Example 2: This example checks the instance association status for the given instance id and further, displays the execution status of those associations Get-SSMInstanceAssociationsStatus -InstanceId i-012e3cb4df567e8aa | ForEach- Object {Get-SSMAssociationExecution -AssociationId .AssociationId} Output: AssociationId : 512a34a5-c678-1234-1234-12345678db9e AssociationVersion : 2 CreatedTime : 3/2/2019 8:53:29 AM DetailedStatus : ExecutionId : 512a34a5-c678-1234-1234-12345678db9e LastExecutionDate : 1/1/0001 12:00:00 AM ResourceCountByStatus : {Success=9} Status : Success • For API details, see DescribeInstanceAssociationsStatus in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeInstanceInformation with a CLI The following code examples show how to use DescribeInstanceInformation. CLI AWS CLI Example 1: To describe managed instance information Actions 2672 AWS Systems Manager User Guide The following describe-instance-information example retrieves details of each of your managed instances. aws ssm describe-instance-information Example 2: To describe information about a specific managed instance The following describe-instance-information example shows details of the managed instance i-028ea792daEXAMPLE. aws ssm describe-instance-information \ --filters "Key=InstanceIds,Values=i-028ea792daEXAMPLE" Example 3: To describe information about managed instances with a specific tag key The following describe-instance-information example shows details for managed instances that have the tag key DEV. aws ssm describe-instance-information \ --filters "Key=tag-key,Values=DEV" Output: { "InstanceInformationList": [ { "InstanceId": "i-028ea792daEXAMPLE", "PingStatus": "Online", "LastPingDateTime": 1582221233.421, "AgentVersion": "2.3.842.0", "IsLatestVersion": true, "PlatformType": "Linux", "PlatformName": "SLES", "PlatformVersion": "15.1", "ResourceType": "EC2Instance", "IPAddress": "192.0.2.0", "ComputerName": "ip-198.51.100.0.us-east-2.compute.internal", "AssociationStatus": "Success", "LastAssociationExecutionDate": 1582220806.0, "LastSuccessfulAssociationExecutionDate": 1582220806.0, "AssociationOverview": { Actions 2673 AWS Systems Manager User Guide "DetailedStatus": "Success", "InstanceAssociationStatusAggregatedCount": { "Success": 2 } } } ] } For more information, see Managed Instances in the AWS Systems Manager User Guide. • For API details, see DescribeInstanceInformation in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example shows details of each of your instances. Get-SSMInstanceInformation Output: ActivationId : AgentVersion : 2.0.672.0 AssociationOverview : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview AssociationStatus : Success ComputerName : ip-172-31-44-222.us- west-2.compute.internal IamRole : InstanceId : i-0cb2b964d3e14fd9f IPAddress : 172.31.44.222 IsLatestVersion : True LastAssociationExecutionDate : 2/24/2017 3:18:09 AM LastPingDateTime : 2/24/2017 3:35:03 AM LastSuccessfulAssociationExecutionDate : 2/24/2017 3:18:09 AM Name : PingStatus : ConnectionLost PlatformName : Amazon Linux AMI PlatformType : Linux PlatformVersion : 2016.09 RegistrationDate : 1/1/0001 12:00:00 AM Actions 2674 AWS Systems Manager User Guide ResourceType : EC2Instance Example 2: This example shows how to use the -Filter parameter to filter results to only those AWS Systems Manager instances in region us-east-1 with an AgentVersion of 2.2.800.0. You can find a list of valid -Filter key values in the InstanceInformation API reference topic (https://docs.aws.amazon.com/systems-manager/latest/APIReference/ API_InstanceInformation.html#systemsmanager-Type-InstanceInformation- ActivationId). $Filters = @{ Key="AgentVersion" Values="2.2.800.0" } Get-SSMInstanceInformation -Region us-east-1 -Filter $Filters Output: ActivationId : AgentVersion : 2.2.800.0 AssociationOverview : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview AssociationStatus : Success ComputerName : EXAMPLE-EXAMPLE.WORKGROUP IamRole : InstanceId : i-EXAMPLEb0792d98ce IPAddress : 10.0.0.01 IsLatestVersion : False LastAssociationExecutionDate : 8/16/2018 12:02:50 AM LastPingDateTime : 8/16/2018 7:40:27 PM LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM Name : PingStatus : Online PlatformName : Microsoft Windows Server 2016 Datacenter PlatformType : Windows PlatformVersion : 10.0.14393 RegistrationDate : 1/1/0001 12:00:00 AM ResourceType : EC2Instance ActivationId : AgentVersion : 2.2.800.0 AssociationOverview : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview Actions 2675 AWS Systems Manager User Guide AssociationStatus : Success ComputerName : EXAMPLE-EXAMPLE.WORKGROUP IamRole : InstanceId : i-EXAMPLEac7501d023 IPAddress : 10.0.0.02 IsLatestVersion : False LastAssociationExecutionDate : 8/16/2018 12:00:20 AM LastPingDateTime : 8/16/2018 7:40:35 PM
systems-manager-ug-772
systems-manager-ug.pdf
772
AssociationStatus : Success ComputerName : EXAMPLE-EXAMPLE.WORKGROUP IamRole : InstanceId : i-EXAMPLEb0792d98ce IPAddress : 10.0.0.01 IsLatestVersion : False LastAssociationExecutionDate : 8/16/2018 12:02:50 AM LastPingDateTime : 8/16/2018 7:40:27 PM LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM Name : PingStatus : Online PlatformName : Microsoft Windows Server 2016 Datacenter PlatformType : Windows PlatformVersion : 10.0.14393 RegistrationDate : 1/1/0001 12:00:00 AM ResourceType : EC2Instance ActivationId : AgentVersion : 2.2.800.0 AssociationOverview : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview Actions 2675 AWS Systems Manager User Guide AssociationStatus : Success ComputerName : EXAMPLE-EXAMPLE.WORKGROUP IamRole : InstanceId : i-EXAMPLEac7501d023 IPAddress : 10.0.0.02 IsLatestVersion : False LastAssociationExecutionDate : 8/16/2018 12:00:20 AM LastPingDateTime : 8/16/2018 7:40:35 PM LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM Name : PingStatus : Online PlatformName : Microsoft Windows Server 2016 Datacenter PlatformType : Windows PlatformVersion : 10.0.14393 RegistrationDate : 1/1/0001 12:00:00 AM ResourceType : EC2Instance Example 3: This example shows how to use the -InstanceInformationFilterList parameter to filter results to only those AWS Systems Manager instances in region us-east-1 with PlatformTypes of Windows or Linux. You can find a list of valid -InstanceInformationFilterList key values in the InstanceInformationFilter API reference topic (https://docs.aws.amazon.com/systems-manager/latest/APIReference/ API_InstanceInformationFilter.html). $Filters = @{ Key="PlatformTypes" ValueSet=("Windows","Linux") } Get-SSMInstanceInformation -Region us-east-1 -InstanceInformationFilterList $Filters Output: ActivationId : AgentVersion : 2.2.800.0 AssociationOverview : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview AssociationStatus : Success ComputerName : EXAMPLE-EXAMPLE.WORKGROUP IamRole : InstanceId : i-EXAMPLEb0792d98ce IPAddress : 10.0.0.27 Actions 2676 AWS Systems Manager User Guide IsLatestVersion : False LastAssociationExecutionDate : 8/16/2018 12:02:50 AM LastPingDateTime : 8/16/2018 7:40:27 PM LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM Name : PingStatus : Online PlatformName : Ubuntu Server 18.04 LTS PlatformType : Linux PlatformVersion : 18.04 RegistrationDate : 1/1/0001 12:00:00 AM ResourceType : EC2Instance ActivationId : AgentVersion : 2.2.800.0 AssociationOverview : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview AssociationStatus : Success ComputerName : EXAMPLE-EXAMPLE.WORKGROUP IamRole : InstanceId : i-EXAMPLEac7501d023 IPAddress : 10.0.0.100 IsLatestVersion : False LastAssociationExecutionDate : 8/16/2018 12:00:20 AM LastPingDateTime : 8/16/2018 7:40:35 PM LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM Name : PingStatus : Online PlatformName : Microsoft Windows Server 2016 Datacenter PlatformType : Windows PlatformVersion : 10.0.14393 RegistrationDate : 1/1/0001 12:00:00 AM ResourceType : EC2Instance Example 4: This example lists ssm managed instances and exports InstanceId, PingStatus, LastPingDateTime and PlatformName to a csv file. Get-SSMInstanceInformation | Select-Object InstanceId, PingStatus, LastPingDateTime, PlatformName | Export-Csv Instance-details.csv - NoTypeInformation • For API details, see DescribeInstanceInformation in AWS Tools for PowerShell Cmdlet Reference. Actions 2677 AWS Systems Manager User Guide For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeInstancePatchStates with a CLI The following code examples show how to use DescribeInstancePatchStates. CLI AWS CLI To get the patch summary states for instances This describe-instance-patch-states example gets the patch summary states for an instance. aws ssm describe-instance-patch-states \ --instance-ids "i-1234567890abcdef0" Output: { "InstancePatchStates": [ { "InstanceId": "i-1234567890abcdef0", "PatchGroup": "my-patch-group", "BaselineId": "pb-0713accee01234567", "SnapshotId": "521c3536-930c-4aa9-950e-01234567abcd", "CriticalNonCompliantCount": 2, "SecurityNonCompliantCount": 2, "OtherNonCompliantCount": 1, "InstalledCount": 123, "InstalledOtherCount": 334, "InstalledPendingRebootCount": 0, "InstalledRejectedCount": 0, "MissingCount": 1, "FailedCount": 2, "UnreportedNotApplicableCount": 11, "NotApplicableCount": 2063, "OperationStartTime": "2021-05-03T11:00:56-07:00", "OperationEndTime": "2021-05-03T11:01:09-07:00", Actions 2678 AWS Systems Manager User Guide "Operation": "Scan", "LastNoRebootInstallOperationTime": "2020-06-14T12:17:41-07:00", "RebootOption": "RebootIfNeeded" } ] } For more information, see About Patch Compliance in the AWS Systems Manager User Guide. • For API details, see DescribeInstancePatchStates in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example gets the patch summary states for an instance. Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407" Example 2: This example gets the patch summary states for two instances. Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407","i-09a618aec652973a9" • For API details, see DescribeInstancePatchStates in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeInstancePatchStatesForPatchGroup with a CLI The following code examples show how to use DescribeInstancePatchStatesForPatchGroup. CLI AWS CLI Example 1: To get the instance states for a patch group Actions 2679 AWS Systems Manager User Guide The following describe-instance-patch-states-for-patch-group example retrieves details about the patch summary states per-instance for the specified patch group. aws ssm describe-instance-patch-states-for-patch-group \ --patch-group "Production" Output: { "InstancePatchStates": [ { "InstanceId": "i-02573cafcfEXAMPLE", "PatchGroup": "Production", "BaselineId": "pb-0c10e65780EXAMPLE", "SnapshotId": "a3f5ff34-9bc4-4d2c-a665-4d1c1EXAMPLE", "OwnerInformation": "", "InstalledCount": 32, "InstalledOtherCount": 1, "InstalledPendingRebootCount": 0, "InstalledRejectedCount": 0, "MissingCount": 2, "FailedCount": 0, "UnreportedNotApplicableCount": 2671, "NotApplicableCount": 400, "OperationStartTime": "2021-08-04T11:03:50.590000-07:00", "OperationEndTime": "2021-08-04T11:04:21.555000-07:00", "Operation": "Scan", "RebootOption": "NoReboot", "CriticalNonCompliantCount": 0, "SecurityNonCompliantCount": 1, "OtherNonCompliantCount": 0 }, { "InstanceId": "i-0471e04240EXAMPLE", "PatchGroup": "Production", "BaselineId": "pb-09ca3fb51fEXAMPLE", "SnapshotId": "05d8ffb0-1bbe-4812-ba2d-d9b7bEXAMPLE", "OwnerInformation": "", "InstalledCount": 32, "InstalledOtherCount": 1, "InstalledPendingRebootCount": 0, "InstalledRejectedCount": 0, "MissingCount": 2, Actions 2680 AWS Systems Manager User Guide "FailedCount": 0, "UnreportedNotApplicableCount": 2671, "NotApplicableCount": 400, "OperationStartTime": "2021-08-04T22:06:20.340000-07:00", "OperationEndTime": "2021-08-04T22:07:11.220000-07:00", "Operation": "Scan", "RebootOption": "NoReboot", "CriticalNonCompliantCount": 0, "SecurityNonCompliantCount": 1, "OtherNonCompliantCount": 0 } ] } Example 2: To get the instance states for a patch group with more than five missing patches The following describe-instance-patch-states-for-patch-group example retrieves details about the patch summary states
systems-manager-ug-773
systems-manager-ug.pdf
773
"FailedCount": 0, "UnreportedNotApplicableCount": 2671, "NotApplicableCount": 400, "OperationStartTime": "2021-08-04T11:03:50.590000-07:00", "OperationEndTime": "2021-08-04T11:04:21.555000-07:00", "Operation": "Scan", "RebootOption": "NoReboot", "CriticalNonCompliantCount": 0, "SecurityNonCompliantCount": 1, "OtherNonCompliantCount": 0 }, { "InstanceId": "i-0471e04240EXAMPLE", "PatchGroup": "Production", "BaselineId": "pb-09ca3fb51fEXAMPLE", "SnapshotId": "05d8ffb0-1bbe-4812-ba2d-d9b7bEXAMPLE", "OwnerInformation": "", "InstalledCount": 32, "InstalledOtherCount": 1, "InstalledPendingRebootCount": 0, "InstalledRejectedCount": 0, "MissingCount": 2, Actions 2680 AWS Systems Manager User Guide "FailedCount": 0, "UnreportedNotApplicableCount": 2671, "NotApplicableCount": 400, "OperationStartTime": "2021-08-04T22:06:20.340000-07:00", "OperationEndTime": "2021-08-04T22:07:11.220000-07:00", "Operation": "Scan", "RebootOption": "NoReboot", "CriticalNonCompliantCount": 0, "SecurityNonCompliantCount": 1, "OtherNonCompliantCount": 0 } ] } Example 2: To get the instance states for a patch group with more than five missing patches The following describe-instance-patch-states-for-patch-group example retrieves details about the patch summary states for the specified patch group for instances with more than five missing patches. aws ssm describe-instance-patch-states-for-patch-group \ --filters Key=MissingCount,Type=GreaterThan,Values=5 \ --patch-group "Production" Output: { "InstancePatchStates": [ { "InstanceId": "i-02573cafcfEXAMPLE", "PatchGroup": "Production", "BaselineId": "pb-0c10e65780EXAMPLE", "SnapshotId": "a3f5ff34-9bc4-4d2c-a665-4d1c1EXAMPLE", "OwnerInformation": "", "InstalledCount": 46, "InstalledOtherCount": 4, "InstalledPendingRebootCount": 1, "InstalledRejectedCount": 1, "MissingCount": 7, "FailedCount": 0, "UnreportedNotApplicableCount": 232, Actions 2681 AWS Systems Manager User Guide "NotApplicableCount": 654, "OperationStartTime": "2021-08-04T11:03:50.590000-07:00", "OperationEndTime": "2021-08-04T11:04:21.555000-07:00", "Operation": "Scan", "RebootOption": "NoReboot", "CriticalNonCompliantCount": 0, "SecurityNonCompliantCount": 1, "OtherNonCompliantCount": 1 } ] } Example 3: To get the instance states for a patch group with fewer than ten instances that require a reboot The following describe-instance-patch-states-for-patch-group example retrieves details about the patch summary states for the specified patch group for instances with fewer than ten instances requiring a reboot. aws ssm describe-instance-patch-states-for-patch-group \ --filters Key=InstalledPendingRebootCount,Type=LessThan,Values=10 \ --patch-group "Production" Output: { "InstancePatchStates": [ { "InstanceId": "i-02573cafcfEXAMPLE", "BaselineId": "pb-0c10e65780EXAMPLE", "SnapshotId": "a3f5ff34-9bc4-4d2c-a665-4d1c1EXAMPLE", "PatchGroup": "Production", "OwnerInformation": "", "InstalledCount": 32, "InstalledOtherCount": 1, "InstalledPendingRebootCount": 4, "InstalledRejectedCount": 0, "MissingCount": 2, "FailedCount": 0, "UnreportedNotApplicableCount": 846, "NotApplicableCount": 212, "OperationStartTime": "2021-08-046T11:03:50.590000-07:00", Actions 2682 AWS Systems Manager User Guide "OperationEndTime": "2021-08-06T11:04:21.555000-07:00", "Operation": "Scan", "RebootOption": "NoReboot", "CriticalNonCompliantCount": 0, "SecurityNonCompliantCount": 1, "OtherNonCompliantCount": 0 } ] } For more information, see Understanding patch compliance state values in the AWS Systems Manager User Guide. • For API details, see DescribeInstancePatchStatesForPatchGroup in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example gets the patch summary states per-instance for a patch group. Get-SSMInstancePatchStatesForPatchGroup -PatchGroup "Production" • For API details, see DescribeInstancePatchStatesForPatchGroup in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeInstancePatches with a CLI The following code examples show how to use DescribeInstancePatches. CLI AWS CLI Example 1: To get the patch state details for an instance Actions 2683 AWS Systems Manager User Guide The following describe-instance-patches example retrieves details about the patches for the specified instance. aws ssm describe-instance-patches \ --instance-id "i-1234567890abcdef0" Output: { "Patches": [ { "Title": "2019-01 Security Update for Adobe Flash Player for Windows Server 2016 for x64-based Systems (KB4480979)", "KBId": "KB4480979", "Classification": "SecurityUpdates", "Severity": "Critical", "State": "Installed", "InstalledTime": "2019-01-09T00:00:00+00:00" }, { "Title": "", "KBId": "KB4481031", "Classification": "", "Severity": "", "State": "InstalledOther", "InstalledTime": "2019-02-08T00:00:00+00:00" }, ... ], "NextToken": "--token string truncated--" } Example 2: To get a list of patches in the Missing state for an instance The following describe-instance-patches example retrieves information about patches that are in the Missing state for the specified instance. aws ssm describe-instance-patches \ --instance-id "i-1234567890abcdef0" \ --filters Key=State,Values=Missing Output: Actions 2684 AWS Systems Manager User Guide { "Patches": [ { "Title": "Windows Malicious Software Removal Tool x64 - February 2019 (KB890830)", "KBId": "KB890830", "Classification": "UpdateRollups", "Severity": "Unspecified", "State": "Missing", "InstalledTime": "1970-01-01T00:00:00+00:00" }, ... ], "NextToken": "--token string truncated--" } For more information, see About Patch Compliance States in the AWS Systems Manager User Guide. Example 3: To get a list of patches installed since a specified InstalledTime for an instance The following describe-instance-patches example retrieves information about patches installed since a specified time for the specified instance by combining the use of -- filters and --query. aws ssm describe-instance-patches \ --instance-id "i-1234567890abcdef0" \ --filters Key=State,Values=Installed \ --query "Patches[?InstalledTime >= `2023-01-01T16:00:00`]" Output: { "Patches": [ { "Title": "2023-03 Cumulative Update for Windows Server 2019 (1809) for x64-based Systems (KB5023702)", "KBId": "KB5023702", "Classification": "SecurityUpdates", "Severity": "Critical", Actions 2685 AWS Systems Manager User Guide "State": "Installed", "InstalledTime": "2023-03-16T11:00:00+00:00" }, ... ], "NextToken": "--token string truncated--" } • For API details, see DescribeInstancePatches in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example gets the patch compliance details for an instance. Get-SSMInstancePatch -InstanceId "i-08ee91c0b17045407" • For API details, see DescribeInstancePatches in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeMaintenanceWindowExecutionTaskInvocations with a CLI The following code examples show how to use DescribeMaintenanceWindowExecutionTaskInvocations. CLI AWS CLI To get the specific task invocations performed for a maintenance window task execution The following describe-maintenance-window-execution-task-invocations example lists the invocations
systems-manager-ug-774
systems-manager-ug.pdf
774
PowerShell Example 1: This example gets the patch compliance details for an instance. Get-SSMInstancePatch -InstanceId "i-08ee91c0b17045407" • For API details, see DescribeInstancePatches in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeMaintenanceWindowExecutionTaskInvocations with a CLI The following code examples show how to use DescribeMaintenanceWindowExecutionTaskInvocations. CLI AWS CLI To get the specific task invocations performed for a maintenance window task execution The following describe-maintenance-window-execution-task-invocations example lists the invocations for the specified task executed as part of the specified maintenance window execution. aws ssm describe-maintenance-window-execution-task-invocations \ --window-execution-id "518d5565-5969-4cca-8f0e-da3b2a638355" \ Actions 2686 AWS Systems Manager User Guide --task-id "ac0c6ae1-daa3-4a89-832e-d384503b6586" Output: { "WindowExecutionTaskInvocationIdentities": [ { "Status": "SUCCESS", "Parameters": "{\"documentName\":\"AWS-RunShellScript\", \"instanceIds\":[\"i-0000293ffd8c57862\"],\"parameters\":{\"commands\":[\"df\"]}, \"maxConcurrency\":\"1\",\"maxErrors\":\"1\"}", "InvocationId": "e274b6e1-fe56-4e32-bd2a-8073c6381d8b", "StartTime": 1487692834.723, "EndTime": 1487692834.871, "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2a638355", "TaskExecutionId": "ac0c6ae1-daa3-4a89-832e-d384503b6586" } ] } For more information, see View Information About Tasks and Task Executions (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see DescribeMaintenanceWindowExecutionTaskInvocations in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists the invocations for a task executed as part of a maintenance window execution. Get-SSMMaintenanceWindowExecutionTaskInvocationList -TaskId "ac0c6ae1- daa3-4a89-832e-d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e- da3b2a638355" Output: EndTime : 2/21/2017 4:00:34 PM ExecutionId : Actions 2687 AWS Systems Manager User Guide InvocationId : e274b6e1-fe56-4e32-bd2a-8073c6381d8b OwnerInformation : Parameters : {"documentName":"AWS-RunShellScript","instanceIds": ["i-0000293ffd8c57862"],"parameters":{"commands":["df"]},"maxConcurrency":"1", "maxErrors":"1"} StartTime : 2/21/2017 4:00:34 PM Status : FAILED StatusDetails : The instance IDs list contains an invalid entry. TaskExecutionId : ac0c6ae1-daa3-4a89-832e-d384503b6586 WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355 WindowTargetId : • For API details, see DescribeMaintenanceWindowExecutionTaskInvocations in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeMaintenanceWindowExecutionTasks with a CLI The following code examples show how to use DescribeMaintenanceWindowExecutionTasks. CLI AWS CLI To list all tasks associated with a maintenance window execution The following ssm describe-maintenance-window-execution-tasks example lists the tasks associated with the specified maintenance window execution. aws ssm describe-maintenance-window-execution-tasks \ --window-execution-id "518d5565-5969-4cca-8f0e-da3b2EXAMPLE" Output: { "WindowExecutionTaskIdentities": [ { "Status": "SUCCESS", Actions 2688 AWS Systems Manager User Guide "TaskArn": "AWS-RunShellScript", "StartTime": 1487692834.684, "TaskType": "RUN_COMMAND", "EndTime": 1487692835.005, "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2EXAMPLE", "TaskExecutionId": "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE" } ] } For more information, see View Information About Tasks and Task Executions (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see DescribeMaintenanceWindowExecutionTasks in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists the tasks associated with a maintenance window execution. Get-SSMMaintenanceWindowExecutionTaskList -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355" Output: EndTime : 2/21/2017 4:00:35 PM StartTime : 2/21/2017 4:00:34 PM Status : SUCCESS TaskArn : AWS-RunShellScript TaskExecutionId : ac0c6ae1-daa3-4a89-832e-d384503b6586 TaskType : RUN_COMMAND WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355 • For API details, see DescribeMaintenanceWindowExecutionTasks in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 2689 AWS Systems Manager User Guide Use DescribeMaintenanceWindowExecutions with a CLI The following code examples show how to use DescribeMaintenanceWindowExecutions. CLI AWS CLI Example 1: To list all executions for a maintenance window The following describe-maintenance-window-executions example lists all of the executions for the specified maintenance window. aws ssm describe-maintenance-window-executions \ --window-id "mw-ab12cd34eEXAMPLE" Output: { "WindowExecutions": [ { "WindowId": "mw-ab12cd34eEXAMPLE", "WindowExecutionId": "6027b513-64fe-4cf0-be7d-1191aEXAMPLE", "Status": "IN_PROGRESS", "StartTime": "2021-08-04T11:00:00.000000-07:00" }, { "WindowId": "mw-ab12cd34eEXAMPLE", "WindowExecutionId": "ff75b750-4834-4377-8f61-b3cadEXAMPLE", "Status": "SUCCESS", "StartTime": "2021-08-03T11:00:00.000000-07:00", "EndTime": "2021-08-03T11:37:21.450000-07:00" }, { "WindowId": "mw-ab12cd34eEXAMPLE", "WindowExecutionId": "9fac7dd9-ff21-42a5-96ad-bbc4bEXAMPLE", "Status": "FAILED", "StatusDetails": "One or more tasks in the orchestration failed.", "StartTime": "2021-08-02T11:00:00.000000-07:00", "EndTime": "2021-08-02T11:22:36.190000-07:00" } ] Actions 2690 AWS Systems Manager } User Guide Example 2: To list all executions for a maintenance window before a specified date The following describe-maintenance-window-executions example lists all of the executions for the specified maintenance window before the specified date. aws ssm describe-maintenance-window-executions \ --window-id "mw-ab12cd34eEXAMPLE" \ --filters "Key=ExecutedBefore,Values=2021-08-03T00:00:00Z" Output: { "WindowExecutions": [ { "WindowId": "mw-ab12cd34eEXAMPLE", "WindowExecutionId": "9fac7dd9-ff21-42a5-96ad-bbc4bEXAMPLE", "Status": "FAILED", "StatusDetails": "One or more tasks in the orchestration failed.", "StartTime": "2021-08-02T11:00:00.000000-07:00", "EndTime": "2021-08-02T11:22:36.190000-07:00" } ] } Example 3: To list all executions for a maintenance window after a specified date The following describe-maintenance-window-executions example lists all of the executions for the specified maintenance window after the specified date. aws ssm describe-maintenance-window-executions \ --window-id "mw-ab12cd34eEXAMPLE" \ --filters "Key=ExecutedAfter,Values=2021-08-04T00:00:00Z" Output: { "WindowExecutions": [ { Actions 2691 AWS Systems Manager User Guide "WindowId": "mw-ab12cd34eEXAMPLE", "WindowExecutionId": "6027b513-64fe-4cf0-be7d-1191aEXAMPLE", "Status": "IN_PROGRESS", "StartTime": "2021-08-04T11:00:00.000000-07:00" } ] } For more information, see View information about tasks and task executions (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see DescribeMaintenanceWindowExecutions in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists all of the executions for a
systems-manager-ug-775
systems-manager-ug.pdf
775
after a specified date The following describe-maintenance-window-executions example lists all of the executions for the specified maintenance window after the specified date. aws ssm describe-maintenance-window-executions \ --window-id "mw-ab12cd34eEXAMPLE" \ --filters "Key=ExecutedAfter,Values=2021-08-04T00:00:00Z" Output: { "WindowExecutions": [ { Actions 2691 AWS Systems Manager User Guide "WindowId": "mw-ab12cd34eEXAMPLE", "WindowExecutionId": "6027b513-64fe-4cf0-be7d-1191aEXAMPLE", "Status": "IN_PROGRESS", "StartTime": "2021-08-04T11:00:00.000000-07:00" } ] } For more information, see View information about tasks and task executions (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see DescribeMaintenanceWindowExecutions in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists all of the executions for a maintenance window. Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" Output: EndTime : 2/20/2017 6:30:17 PM StartTime : 2/20/2017 6:30:16 PM Status : FAILED StatusDetails : One or more tasks in the orchestration failed. WindowExecutionId : 6f3215cf-4101-4fa0-9b7b-9523269599c7 WindowId : mw-03eb9db42890fb82d Example 2: This example lists all of the executions for a maintenance window before a specified date. $option1 = @{Key="ExecutedBefore";Values=@("2016-11-04T05:00:00Z")} Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1 Example 3: This example lists all of the executions for a maintenance window after a specified date. Actions 2692 AWS Systems Manager User Guide $option1 = @{Key="ExecutedAfter";Values=@("2016-11-04T05:00:00Z")} Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1 • For API details, see DescribeMaintenanceWindowExecutions in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeMaintenanceWindowTargets with a CLI The following code examples show how to use DescribeMaintenanceWindowTargets. CLI AWS CLI Example 1: To list all targets for a Maintenance Window The following describe-maintenance-window-targets example lists all of the targets for a maintenance window. aws ssm describe-maintenance-window-targets \ --window-id "mw-06cf17cbefEXAMPLE" Output: { "Targets": [ { "ResourceType": "INSTANCE", "OwnerInformation": "Single instance", "WindowId": "mw-06cf17cbefEXAMPLE", "Targets": [ { "Values": [ "i-0000293ffdEXAMPLE" ], Actions 2693 AWS Systems Manager User Guide "Key": "InstanceIds" } ], "WindowTargetId": "350d44e6-28cc-44e2-951f-4b2c9EXAMPLE" }, { "ResourceType": "INSTANCE", "OwnerInformation": "Two instances in a list", "WindowId": "mw-06cf17cbefEXAMPLE", "Targets": [ { "Values": [ "i-0000293ffdEXAMPLE", "i-0cb2b964d3EXAMPLE" ], "Key": "InstanceIds" } ], "WindowTargetId": "e078a987-2866-47be-bedd-d9cf4EXAMPLE" } ] } Example 2: To list all targets for a maintenance window matching a specific owner information value This describe-maintenance-window-targets example lists all of the targets for a maintenance window with a specific value. aws ssm describe-maintenance-window-targets \ --window-id "mw-0ecb1226ddEXAMPLE" \ --filters "Key=OwnerInformation,Values=CostCenter1" Output: { "Targets": [ { "WindowId": "mw-0ecb1226ddEXAMPLE", "WindowTargetId": "da89dcc3-7f9c-481d-ba2b-edcb7d0057f9", "ResourceType": "INSTANCE", "Targets": [ Actions 2694 AWS Systems Manager { User Guide "Key": "tag:Environment", "Values": [ "Prod" ] } ], "OwnerInformation": "CostCenter1", "Name": "ProdTarget1" } ] } For more information, see View Information About Maintenance Windows (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see DescribeMaintenanceWindowTargets in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists all of the targets for a maintenance window. Get-SSMMaintenanceWindowTarget -WindowId "mw-06cf17cbefcb4bf4f" Output: OwnerInformation : Single instance ResourceType : INSTANCE Targets : {InstanceIds} WindowId : mw-06cf17cbefcb4bf4f WindowTargetId : 350d44e6-28cc-44e2-951f-4b2c985838f6 OwnerInformation : Two instances in a list ResourceType : INSTANCE Targets : {InstanceIds} WindowId : mw-06cf17cbefcb4bf4f WindowTargetId : e078a987-2866-47be-bedd-d9cf49177d3a • For API details, see DescribeMaintenanceWindowTargets in AWS Tools for PowerShell Cmdlet Reference. Actions 2695 AWS Systems Manager User Guide For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeMaintenanceWindowTasks with a CLI The following code examples show how to use DescribeMaintenanceWindowTasks. CLI AWS CLI Example 1: To list all tasks for a maintenance window The following describe-maintenance-window-tasks example lists all of the tasks for the specified maintenance window. aws ssm describe-maintenance-window-tasks \ --window-id "mw-06cf17cbefEXAMPLE" Output: { "Tasks": [ { "WindowId": "mw-06cf17cbefEXAMPLE", "WindowTaskId": "018b31c3-2d77-4b9e-bd48-c91edEXAMPLE", "TaskArn": "AWS-RestartEC2Instance", "TaskParameters": {}, "Type": "AUTOMATION", "Description": "Restarting EC2 Instance for maintenance", "MaxConcurrency": "1", "MaxErrors": "1", "Name": "My-Automation-Example-Task", "Priority": 0, "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ ssm.amazonaws.com/AWSServiceRoleForAmazonSSM", "Targets": [ { "Key": "WindowTargetIds", "Values": [ "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE" Actions 2696 AWS Systems Manager User Guide ] } ] }, { "WindowId": "mw-06cf17cbefEXAMPLE", "WindowTaskId": "1943dee0-0a17-4978-9bf4-3cc2fEXAMPLE", "TaskArn": "AWS-DisableS3BucketPublicReadWrite", "TaskParameters": {}, "Type": "AUTOMATION", "Description": "Automation task to disable read/write access on public S3 buckets", "MaxConcurrency": "10", "MaxErrors": "5", "Name": "My-Disable-S3-Public-Read-Write-Access-Automation-Task", "Priority": 0, "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ ssm.amazonaws.com/AWSServiceRoleForAmazonSSM", "Targets": [ { "Key": "WindowTargetIds", "Values": [ "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE" ] } ] } ] } Example 2: To list all tasks for a maintenance window that invokes the AWS- RunPowerShellScript command document The following describe-maintenance-window-tasks example lists all of the tasks for the specified maintenance window that invokes the AWS-RunPowerShellScript command document. aws ssm describe-maintenance-window-tasks \ --window-id "mw-ab12cd34eEXAMPLE" \ --filters "Key=TaskArn,Values=AWS-RunPowerShellScript" Output: Actions 2697 AWS Systems Manager User Guide { "Tasks": [ { "WindowId": "mw-ab12cd34eEXAMPLE", "WindowTaskId": "0d36e6b4-3a4f-411e-adcb-3558eEXAMPLE", "TaskArn": "AWS-RunPowerShellScript", "Type": "RUN_COMMAND", "Targets": [ { "Key": "WindowTargetIds", "Values": [ "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE" ] } ], "TaskParameters": {}, "Priority": 1, "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ ssm.amazonaws.com/AWSServiceRoleForAmazonSSM", "MaxConcurrency": "1", "MaxErrors": "1", "Name": "MyTask" } ] }
systems-manager-ug-776
systems-manager-ug.pdf
776
"da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE" ] } ] } ] } Example 2: To list all tasks for a maintenance window that invokes the AWS- RunPowerShellScript command document The following describe-maintenance-window-tasks example lists all of the tasks for the specified maintenance window that invokes the AWS-RunPowerShellScript command document. aws ssm describe-maintenance-window-tasks \ --window-id "mw-ab12cd34eEXAMPLE" \ --filters "Key=TaskArn,Values=AWS-RunPowerShellScript" Output: Actions 2697 AWS Systems Manager User Guide { "Tasks": [ { "WindowId": "mw-ab12cd34eEXAMPLE", "WindowTaskId": "0d36e6b4-3a4f-411e-adcb-3558eEXAMPLE", "TaskArn": "AWS-RunPowerShellScript", "Type": "RUN_COMMAND", "Targets": [ { "Key": "WindowTargetIds", "Values": [ "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE" ] } ], "TaskParameters": {}, "Priority": 1, "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ ssm.amazonaws.com/AWSServiceRoleForAmazonSSM", "MaxConcurrency": "1", "MaxErrors": "1", "Name": "MyTask" } ] } Example 3: To list all tasks for a maintenance window that have a Priority of 3 The following describe-maintenance-window-tasks example lists all of the tasks for the specified maintenance window that have a Priority of 3. aws ssm describe-maintenance-window-tasks \ --window-id "mw-ab12cd34eEXAMPLE" \ --filters "Key=Priority,Values=3" Output: { "Tasks": [ { "WindowId": "mw-ab12cd34eEXAMPLE", "WindowTaskId": "0d36e6b4-3a4f-411e-adcb-3558eEXAMPLE", Actions 2698 AWS Systems Manager User Guide "TaskArn": "AWS-RunPowerShellScript", "Type": "RUN_COMMAND", "Targets": [ { "Key": "WindowTargetIds", "Values": [ "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE" ] } ], "TaskParameters": {}, "Priority": 3, "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ ssm.amazonaws.com/AWSServiceRoleForAmazonSSM", "MaxConcurrency": "1", "MaxErrors": "1", "Name": "MyRunCommandTask" }, { "WindowId": "mw-ab12cd34eEXAMPLE", "WindowTaskId": "ee45feff-ad65-4a6c-b478-5cab8EXAMPLE", "TaskArn": "AWS-RestartEC2Instance", "Type": "AUTOMATION", "Targets": [ { "Key": "WindowTargetIds", "Values": [ "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE" ] } ], "TaskParameters": {}, "Priority": 3, "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ ssm.amazonaws.com/AWSServiceRoleForAmazonSSM", "MaxConcurrency": "10", "MaxErrors": "5", "Name": "My-Automation-Task", "Description": "A description for my Automation task" } ] } Actions 2699 AWS Systems Manager User Guide Example 4: To list all tasks for a maintenance window that have a Priority of 1 and use Run Command This describe-maintenance-window-tasks example lists all of the tasks for the specified maintenance window that have a Priority of 1 and use Run Command. aws ssm describe-maintenance-window-tasks \ --window-id "mw-ab12cd34eEXAMPLE" \ --filters "Key=Priority,Values=1" "Key=TaskType,Values=RUN_COMMAND" Output: { "Tasks": [ { "WindowId": "mw-ab12cd34eEXAMPLE", "WindowTaskId": "0d36e6b4-3a4f-411e-adcb-3558eEXAMPLE", "TaskArn": "AWS-RunPowerShellScript", "Type": "RUN_COMMAND", "Targets": [ { "Key": "WindowTargetIds", "Values": [ "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE" ] } ], "TaskParameters": {}, "Priority": 1, "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ ssm.amazonaws.com/AWSServiceRoleForAmazonSSM", "MaxConcurrency": "1", "MaxErrors": "1", "Name": "MyRunCommandTask" } ] } For more information, see View information about maintenance windows (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see DescribeMaintenanceWindowTasks in AWS CLI Command Reference. Actions 2700 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example lists all of the tasks for a maintenance window. Get-SSMMaintenanceWindowTaskList -WindowId "mw-06cf17cbefcb4bf4f" Output: LoggingInfo : MaxConcurrency : 1 MaxErrors : 1 Priority : 10 ServiceRoleArn : arn:aws:iam::123456789012:role/MaintenanceWindowsRole Targets : {InstanceIds} TaskArn : AWS-RunShellScript TaskParameters : {[commands, Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression]} Type : RUN_COMMAND WindowId : mw-06cf17cbefcb4bf4f WindowTaskId : a23e338d-ff30-4398-8aa3-09cd052ebf17 • For API details, see DescribeMaintenanceWindowTasks in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeMaintenanceWindows with a CLI The following code examples show how to use DescribeMaintenanceWindows. CLI AWS CLI Example 1: To list all maintenance windows The following describe-maintenance-windows example lists all maintenance windows in your AWS account in the current Region. Actions 2701 AWS Systems Manager User Guide aws ssm describe-maintenance-windows Output: { "WindowIdentities": [ { "WindowId": "mw-0ecb1226ddEXAMPLE", "Name": "MyMaintenanceWindow-1", "Enabled": true, "Duration": 2, "Cutoff": 1, "Schedule": "rate(180 minutes)", "NextExecutionTime": "2020-02-12T23:19:20.596Z" }, { "WindowId": "mw-03eb9db428EXAMPLE", "Name": "MyMaintenanceWindow-2", "Enabled": true, "Duration": 3, "Cutoff": 1, "Schedule": "rate(7 days)", "NextExecutionTime": "2020-02-17T23:22:00.956Z" }, ] } Example 2: To list all enabled maintenance windows The following describe-maintenance-windows example lists all enabled maintenance windows. aws ssm describe-maintenance-windows \ --filters "Key=Enabled,Values=true" Example 3: To list maintenance windows matching a specific name This describe-maintenance-windows example lists all maintenance windows with the specified name. aws ssm describe-maintenance-windows \ Actions 2702 AWS Systems Manager User Guide --filters "Key=Name,Values=MyMaintenanceWindow" For more information, see View Information About Maintenance Windows (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see DescribeMaintenanceWindows in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists all maintenance windows on your account. Get-SSMMaintenanceWindowList Output: Cutoff : 1 Duration : 4 Enabled : True Name : My-First-Maintenance-Window WindowId : mw-06d59c1a07c022145 • For API details, see DescribeMaintenanceWindows in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeOpsItems with an AWS SDK or CLI The following code examples show how to use DescribeOpsItems. CLI AWS CLI To list a set of OpsItems Actions 2703 AWS Systems Manager User Guide The following describe-ops-items example displays a list of all open OpsItems in your AWS account. aws ssm describe-ops-items \ --ops-item-filters "Key=Status,Values=Open,Operator=Equal" Output: { "OpsItemSummaries": [ { "CreatedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE- Role/fbf77cbe264a33509569f23e4EXAMPLE", "CreatedTime": "2020-03-14T17:02:46.375000-07:00", "LastModifiedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem- CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE", "LastModifiedTime": "2020-03-14T17:02:46.375000-07:00", "Source": "SSM", "Status": "Open", "OpsItemId": "oi-7cfc5EXAMPLE",
systems-manager-ug-777
systems-manager-ug.pdf
777
and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeOpsItems with an AWS SDK or CLI The following code examples show how to use DescribeOpsItems. CLI AWS CLI To list a set of OpsItems Actions 2703 AWS Systems Manager User Guide The following describe-ops-items example displays a list of all open OpsItems in your AWS account. aws ssm describe-ops-items \ --ops-item-filters "Key=Status,Values=Open,Operator=Equal" Output: { "OpsItemSummaries": [ { "CreatedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE- Role/fbf77cbe264a33509569f23e4EXAMPLE", "CreatedTime": "2020-03-14T17:02:46.375000-07:00", "LastModifiedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem- CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE", "LastModifiedTime": "2020-03-14T17:02:46.375000-07:00", "Source": "SSM", "Status": "Open", "OpsItemId": "oi-7cfc5EXAMPLE", "Title": "SSM Maintenance Window execution failed", "OperationalData": { "/aws/dedup": { "Value": "{\"dedupString\":\"SSMOpsItems-SSM-maintenance- window-execution-failed\"}", "Type": "SearchableString" }, "/aws/resources": { "Value": "[{\"arn\":\"arn:aws:ssm:us- east-2:111222333444:maintenancewindow/mw-034093d322EXAMPLE\"}]", "Type": "SearchableString" } }, "Category": "Availability", "Severity": "3" }, { "CreatedBy": "arn:aws:sts::1112223233444:assumed-role/OpsItem-CWE- Role/fbf77cbe264a33509569f23e4EXAMPLE", "CreatedTime": "2020-02-26T11:43:15.426000-08:00", "LastModifiedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem- CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE", "LastModifiedTime": "2020-02-26T11:43:15.426000-08:00", Actions 2704 AWS Systems Manager User Guide "Source": "EC2", "Status": "Open", "OpsItemId": "oi-6f966EXAMPLE", "Title": "EC2 instance stopped", "OperationalData": { "/aws/automations": { "Value": "[ { \"automationType\": \"AWS:SSM:Automation\", \"automationId\": \"AWS-RestartEC2Instance\" } ]", "Type": "SearchableString" }, "/aws/dedup": { "Value": "{\"dedupString\":\"SSMOpsItems-EC2-instance-stopped \"}", "Type": "SearchableString" }, "/aws/resources": { "Value": "[{\"arn\":\"arn:aws:ec2:us- east-2:111222333444:instance/i-0beccfbc02EXAMPLE\"}]", "Type": "SearchableString" } }, "Category": "Availability", "Severity": "3" } ] } For more information, see Working with OpsItems in the AWS Systems Manager User Guide. • For API details, see DescribeOpsItems in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** Actions 2705 AWS Systems Manager User Guide * Describes AWS SSM OpsItems asynchronously. * * @param key The key to filter OpsItems by (e.g., OPS_ITEM_ID). * * This method initiates an asynchronous request to describe SSM OpsItems. * If the request is successful, it prints the title and status of each OpsItem. * If an exception occurs, it handles the error appropriately. */ public void describeOpsItems(String key) { OpsItemFilter filter = OpsItemFilter.builder() .key(OpsItemFilterKey.OPS_ITEM_ID) .values(key) .operator(OpsItemFilterOperator.EQUAL) .build(); DescribeOpsItemsRequest itemsRequest = DescribeOpsItemsRequest.builder() .maxResults(10) .opsItemFilters(filter) .build(); CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { getAsyncClient().describeOpsItems(itemsRequest) .thenAccept(itemsResponse -> { List<OpsItemSummary> items = itemsResponse.opsItemSummaries(); for (OpsItemSummary item : items) { System.out.println("The item title is " + item.title() + " and the status is " + item.status().toString()); } }) .exceptionally(ex -> { throw new CompletionException(ex); }).join(); }).exceptionally(ex -> { Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex; if (cause instanceof SsmException) { throw new RuntimeException("SSM error: " + cause.getMessage(), cause); } else { throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause); } Actions 2706 AWS Systems Manager }); User Guide try { future.join(); } catch (CompletionException ex) { throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex; } } • For API details, see DescribeOpsItems in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { OpsItemFilterOperator, OpsItemFilterKey, paginateDescribeOpsItems, SSMClient, } from "@aws-sdk/client-ssm"; import { parseArgs } from "node:util"; /** * Describe SSM OpsItems. * @param {{ opsItemId: string }} */ export const main = async ({ opsItemId }) => { const client = new SSMClient({}); try { const describeOpsItemsPaginated = []; for await (const page of paginateDescribeOpsItems( { client }, { Actions 2707 AWS Systems Manager User Guide OpsItemFilters: { Key: OpsItemFilterKey.OPSITEM_ID, Operator: OpsItemFilterOperator.EQUAL, Values: opsItemId, }, }, )) { describeOpsItemsPaginated.push(...page.OpsItemSummaries); } console.log("Here are the ops items:"); console.log(describeOpsItemsPaginated); return { OpsItemSummaries: describeOpsItemsPaginated }; } catch (caught) { if (caught instanceof Error && caught.name === "MissingParameter") { console.warn(`${caught.message}. Did you provide this value?`); } throw caught; } }; • For API details, see DescribeOpsItems in AWS SDK for JavaScript API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class OpsItemWrapper: """Encapsulates AWS Systems Manager OpsItem actions.""" def __init__(self, ssm_client): """ :param ssm_client: A Boto3 Systems Manager client. """ self.ssm_client = ssm_client self.id = None Actions 2708 AWS Systems Manager User Guide @classmethod def from_client(cls): """ :return: A OpsItemWrapper instance. """ ssm_client = boto3.client("ssm") return cls(ssm_client) def describe(self): """ Describe an OpsItem. """ try: paginator = self.ssm_client.get_paginator("describe_ops_items") ops_items = [] for page in paginator.paginate( OpsItemFilters=[ {"Key": "OpsItemId", "Values": [self.id], "Operator": "Equal"} ] ): ops_items.extend(page["OpsItemSummaries"]) for item in ops_items: print( f"The item title is {item['Title']} and the status is {item['Status']}" ) return len(ops_items) > 0 except ClientError as err: logger.error( "Couldn't describe ops item %s. Here's why: %s: %s", self.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise • For API details, see DescribeOpsItems in AWS SDK for Python (Boto3) API Reference. Actions 2709 AWS Systems Manager User Guide For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also
systems-manager-ug-778
systems-manager-ug.pdf
778
ops_items = [] for page in paginator.paginate( OpsItemFilters=[ {"Key": "OpsItemId", "Values": [self.id], "Operator": "Equal"} ] ): ops_items.extend(page["OpsItemSummaries"]) for item in ops_items: print( f"The item title is {item['Title']} and the status is {item['Status']}" ) return len(ops_items) > 0 except ClientError as err: logger.error( "Couldn't describe ops item %s. Here's why: %s: %s", self.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise • For API details, see DescribeOpsItems in AWS SDK for Python (Boto3) API Reference. Actions 2709 AWS Systems Manager User Guide For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribeParameters with an AWS SDK or CLI The following code examples show how to use DescribeParameters. CLI AWS CLI Example 1: To list all parameters The following describe-parameters example lists all parameters in the current AWS account and Region. aws ssm describe-parameters Output: { "Parameters": [ { "Name": "MySecureStringParameter", "Type": "SecureString", "KeyId": "alias/aws/ssm", "LastModifiedDate": 1582155479.205, "LastModifiedUser": "arn:aws:sts::111222333444:assumed-role/Admin/ Richard-Roe-Managed", "Description": "This is a SecureString parameter", "Version": 2, "Tier": "Advanced", "Policies": [ { "PolicyText": "{\"Type\":\"Expiration\",\"Version\":\"1.0\", \"Attributes\":{\"Timestamp\":\"2020-07-07T22:30:00Z\"}}", "PolicyType": "Expiration", "PolicyStatus": "Pending" }, { "PolicyText": "{\"Type\":\"ExpirationNotification\",\"Version \":\"1.0\",\"Attributes\":{\"Before\":\"12\",\"Unit\":\"Hours\"}}", Actions 2710 AWS Systems Manager User Guide "PolicyType": "ExpirationNotification", "PolicyStatus": "Pending" } ] }, { "Name": "MyStringListParameter", "Type": "StringList", "LastModifiedDate": 1582154764.222, "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major", "Description": "This is a StringList parameter", "Version": 1, "Tier": "Standard", "Policies": [] }, { "Name": "MyStringParameter", "Type": "String", "LastModifiedDate": 1582154711.976, "LastModifiedUser": "arn:aws:iam::111222333444:user/Alejandro- Rosalez", "Description": "This is a String parameter", "Version": 1, "Tier": "Standard", "Policies": [] }, { "Name": "latestAmi", "Type": "String", "LastModifiedDate": 1580862415.521, "LastModifiedUser": "arn:aws:sts::111222333444:assumed-role/lambda- ssm-role/Automation-UpdateSSM-Param", "Version": 3, "Tier": "Standard", "Policies": [] } ] } Example 2: To list all parameters matching specific metadata This describe-parameters example lists all parameters matching a filter. aws ssm describe-parameters --filters "Key=Type,Values=StringList" Actions 2711 AWS Systems Manager Output: { User Guide "Parameters": [ { "Name": "MyStringListParameter", "Type": "StringList", "LastModifiedDate": 1582154764.222, "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major", "Description": "This is a StringList parameter", "Version": 1, "Tier": "Standard", "Policies": [] } ] } For more information, see Searching for Systems Manager Parameters in the AWS Systems Manager User Guide. • For API details, see DescribeParameters in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ssm.SsmClient; import software.amazon.awssdk.services.ssm.model.GetParameterRequest; import software.amazon.awssdk.services.ssm.model.GetParameterResponse; import software.amazon.awssdk.services.ssm.model.SsmException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * Actions 2712 AWS Systems Manager User Guide * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class GetParameter { public static void main(String[] args) { final String usage = """ Usage: <paraName> Where: paraName - The name of the parameter. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String paraName = args[0]; Region region = Region.US_EAST_1; SsmClient ssmClient = SsmClient.builder() .region(region) .build(); getParaValue(ssmClient, paraName); ssmClient.close(); } public static void getParaValue(SsmClient ssmClient, String paraName) { try { GetParameterRequest parameterRequest = GetParameterRequest.builder() .name(paraName) .build(); GetParameterResponse parameterResponse = ssmClient.getParameter(parameterRequest); System.out.println("The parameter value is " + parameterResponse.parameter().value()); } catch (SsmException e) { System.err.println(e.getMessage()); Actions 2713 AWS Systems Manager User Guide System.exit(1); } } } • For API details, see DescribeParameters in AWS SDK for Java 2.x API Reference. PowerShell Tools for PowerShell Example 1: This example lists all parameters. Get-SSMParameterList Output: Description : KeyId : LastModifiedDate : 3/3/2017 6:58:23 PM LastModifiedUser : arn:aws:iam::123456789012:user/admin Name : Welcome Type : String • For API details, see DescribeParameters in AWS Tools for PowerShell Cmdlet Reference. Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. async fn show_parameters(client: &Client) -> Result<(), Error> { let resp = client.describe_parameters().send().await?; Actions 2714 AWS Systems Manager User Guide for param in resp.parameters() { println!(" {}", param.name().unwrap_or_default()); } Ok(()) } • For API details, see DescribeParameters in AWS SDK for Rust API reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribePatchBaselines with a CLI The following code examples show how to use DescribePatchBaselines. CLI AWS CLI Example 1: To list all patch baselines The following describe-patch-baselines example retreives details for all patch baselines in your account in the current Region. aws ssm describe-patch-baselines Output: { "BaselineIdentities": [ { "BaselineName": "AWS-SuseDefaultPatchBaseline", "DefaultBaseline": true, "BaselineDescription": "Default Patch Baseline for Suse Provided by AWS.", "BaselineId": "arn:aws:ssm:us-east-2:733109147000:patchbaseline/ pb-0123fdb36e334a3b2", Actions 2715 AWS Systems Manager User Guide "OperatingSystem": "SUSE" }, { "BaselineName": "AWS-DefaultPatchBaseline", "DefaultBaseline": false, "BaselineDescription": "Default Patch Baseline Provided by AWS.", "BaselineId": "arn:aws:ssm:us-east-2:733109147000:patchbaseline/ pb-020d361a05defe4ed", "OperatingSystem": "WINDOWS" }, ... { "BaselineName": "MyWindowsPatchBaseline", "DefaultBaseline": true, "BaselineDescription": "My patch baseline for EC2 instances
systems-manager-ug-779
systems-manager-ug.pdf
779
following code examples show how to use DescribePatchBaselines. CLI AWS CLI Example 1: To list all patch baselines The following describe-patch-baselines example retreives details for all patch baselines in your account in the current Region. aws ssm describe-patch-baselines Output: { "BaselineIdentities": [ { "BaselineName": "AWS-SuseDefaultPatchBaseline", "DefaultBaseline": true, "BaselineDescription": "Default Patch Baseline for Suse Provided by AWS.", "BaselineId": "arn:aws:ssm:us-east-2:733109147000:patchbaseline/ pb-0123fdb36e334a3b2", Actions 2715 AWS Systems Manager User Guide "OperatingSystem": "SUSE" }, { "BaselineName": "AWS-DefaultPatchBaseline", "DefaultBaseline": false, "BaselineDescription": "Default Patch Baseline Provided by AWS.", "BaselineId": "arn:aws:ssm:us-east-2:733109147000:patchbaseline/ pb-020d361a05defe4ed", "OperatingSystem": "WINDOWS" }, ... { "BaselineName": "MyWindowsPatchBaseline", "DefaultBaseline": true, "BaselineDescription": "My patch baseline for EC2 instances for Windows Server", "BaselineId": "pb-0ad00e0dd7EXAMPLE", "OperatingSystem": "WINDOWS" } ] } Example 2: To list all patch baselines provided by AWS The following describe-patch-baselines example lists all patch baselines provided by AWS. aws ssm describe-patch-baselines \ --filters "Key=OWNER,Values=[AWS]" Example 3: To list all patch baselines that you own The following describe-patch-baselines example lists all custom patch baselines created in your account in the current Region. aws ssm describe-patch-baselines \ --filters "Key=OWNER,Values=[Self]" For more information, see About Predefined and Custom Patch Baselines in the AWS Systems Manager User Guide. • For API details, see DescribePatchBaselines in AWS CLI Command Reference. Actions 2716 AWS Systems Manager PowerShell Tools for PowerShell Example 1: This example lists all patch baselines. Get-SSMPatchBaseline Output: User Guide BaselineDescription BaselineId BaselineName ------------------- ---------- ------------ Default Patch Baseline Provided by AWS. arn:aws:ssm:us- west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultP... Baseline containing all updates approved for production systems pb-045f10b4f382baeda Production-B... Baseline containing all updates approved for production systems pb-0a2f1059b670ebd31 Production-B... Example 2: This example lists all patch baselines provided by AWS. The syntax used by this example requires PowerShell version 3 or later. $filter1 = @{Key="OWNER";Values=@("AWS")} Output: Get-SSMPatchBaseline -Filter $filter1 Example 3: This example lists all patch baselines with you as the owner. The syntax used by this example requires PowerShell version 3 or later. $filter1 = @{Key="OWNER";Values=@("Self")} Output: Get-SSMPatchBaseline -Filter $filter1 Actions 2717 AWS Systems Manager User Guide Example 4: With PowerShell version 2, you must use New-Object to create each tag. $filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter $filter1.Key = "OWNER" $filter1.Values = "AWS" Get-SSMPatchBaseline -Filter $filter1 Output: BaselineDescription BaselineId BaselineName DefaultBaselin e ------------------- ---------- ------------ -------------- Default Patch Baseline Provided by AWS. arn:aws:ssm:us- west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultPatchBaseline True • For API details, see DescribePatchBaselines in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribePatchGroupState with a CLI The following code examples show how to use DescribePatchGroupState. CLI AWS CLI To get the state of a patch group The following describe-patch-group-state example retrieves the high-level patch compliance summary for a patch group. aws ssm describe-patch-group-state \ Actions 2718 AWS Systems Manager User Guide --patch-group "Production" Output: { "Instances": 21, "InstancesWithCriticalNonCompliantPatches": 1, "InstancesWithFailedPatches": 2, "InstancesWithInstalledOtherPatches": 3, "InstancesWithInstalledPatches": 21, "InstancesWithInstalledPendingRebootPatches": 2, "InstancesWithInstalledRejectedPatches": 1, "InstancesWithMissingPatches": 3, "InstancesWithNotApplicablePatches": 4, "InstancesWithOtherNonCompliantPatches": 1, "InstancesWithSecurityNonCompliantPatches": 1, "InstancesWithUnreportedNotApplicablePatches": 2 } For more information, see About patch groups <https://docs.aws.amazon.com/systems- manager/latest/userguide/sysman-patch-patchgroups.html>__ and Understanding patch compliance state values in the AWS Systems Manager User Guide. • For API details, see DescribePatchGroupState in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example gets the high-level patch compliance summary for a patch group. Get-SSMPatchGroupState -PatchGroup "Production" Output: Instances : 4 InstancesWithFailedPatches : 1 InstancesWithInstalledOtherPatches : 4 InstancesWithInstalledPatches : 3 InstancesWithMissingPatches : 0 Actions 2719 AWS Systems Manager User Guide InstancesWithNotApplicablePatches : 0 • For API details, see DescribePatchGroupState in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DescribePatchGroups with a CLI The following code examples show how to use DescribePatchGroups. CLI AWS CLI To display patch group registrations The following describe-patch-groups example lists the patch group registrations. aws ssm describe-patch-groups Output: { "Mappings": [ { "PatchGroup": "Production", "BaselineIdentity": { "BaselineId": "pb-0123456789abcdef0", "BaselineName": "ProdPatching", "OperatingSystem": "WINDOWS", "BaselineDescription": "Patches for Production", "DefaultBaseline": false } }, { "PatchGroup": "Development", "BaselineIdentity": { "BaselineId": "pb-0713accee01234567", Actions 2720 AWS Systems Manager User Guide "BaselineName": "DevPatching", "OperatingSystem": "WINDOWS", "BaselineDescription": "Patches for Development", "DefaultBaseline": true } }, ... ] } For more information, see Create a Patch Group <https://docs.aws.amazon.com/systems- manager/latest/userguide/sysman-patch-group-tagging.html>__ and Add a Patch Group to a Patch Baseline in the AWS Systems Manager User Guide. • For API details, see DescribePatchGroups in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists the patch group registrations. Get-SSMPatchGroup Output: BaselineIdentity PatchGroup ---------------- ---------- Amazon.SimpleSystemsManagement.Model.PatchBaselineIdentity Production • For API details, see DescribePatchGroups in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK.
systems-manager-ug-780
systems-manager-ug.pdf
780
for Development", "DefaultBaseline": true } }, ... ] } For more information, see Create a Patch Group <https://docs.aws.amazon.com/systems- manager/latest/userguide/sysman-patch-group-tagging.html>__ and Add a Patch Group to a Patch Baseline in the AWS Systems Manager User Guide. • For API details, see DescribePatchGroups in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists the patch group registrations. Get-SSMPatchGroup Output: BaselineIdentity PatchGroup ---------------- ---------- Amazon.SimpleSystemsManagement.Model.PatchBaselineIdentity Production • For API details, see DescribePatchGroups in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetAutomationExecution with a CLI The following code examples show how to use GetAutomationExecution. Actions 2721 AWS Systems Manager CLI AWS CLI User Guide To display details about an automation execution The following get-automation-execution example displays detailed information about an Automation execution. aws ssm get-automation-execution \ --automation-execution-id 73c8eef8-f4ee-4a05-820c-e354fEXAMPLE Output: { "AutomationExecution": { "AutomationExecutionId": "73c8eef8-f4ee-4a05-820c-e354fEXAMPLE", "DocumentName": "AWS-StartEC2Instance", "DocumentVersion": "1", "ExecutionStartTime": 1583737233.748, "ExecutionEndTime": 1583737234.719, "AutomationExecutionStatus": "Success", "StepExecutions": [ { "StepName": "startInstances", "Action": "aws:changeInstanceState", "ExecutionStartTime": 1583737234.134, "ExecutionEndTime": 1583737234.672, "StepStatus": "Success", "Inputs": { "DesiredState": "\"running\"", "InstanceIds": "[\"i-0cb99161f6EXAMPLE\"]" }, "Outputs": { "InstanceStates": [ "running" ] }, "StepExecutionId": "95e70479-cf20-4d80-8018-7e4e2EXAMPLE", "OverriddenParameters": {} } ], "StepExecutionsTruncated": false, Actions 2722 AWS Systems Manager User Guide "Parameters": { "AutomationAssumeRole": [ "" ], "InstanceId": [ "i-0cb99161f6EXAMPLE" ] }, "Outputs": {}, "Mode": "Auto", "ExecutedBy": "arn:aws:sts::29884EXAMPLE:assumed-role/mw_service_role/ OrchestrationService", "Targets": [], "ResolvedTargets": { "ParameterValues": [], "Truncated": false } } } For more information, see Walkthrough: Patch a Linux AMI (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see GetAutomationExecution in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example displays the details of an Automation Execution. Get-SSMAutomationExecution -AutomationExecutionId "4105a4fc- f944-11e6-9d32-8fb2db27a909" Output: AutomationExecutionId : 4105a4fc-f944-11e6-9d32-8fb2db27a909 AutomationExecutionStatus : Failed DocumentName : AWS-UpdateLinuxAmi DocumentVersion : 1 ExecutionEndTime : 2/22/2017 9:17:08 PM ExecutionStartTime : 2/22/2017 9:17:02 PM Actions 2723 AWS Systems Manager User Guide FailureMessage : Step launchInstance failed maximum allowed times. You are not authorized to perform this operation. Encoded authorization failure message: B_V2QyyN7NhSZQYpmVzpEc4oSnj2GLTNYnXUHsTbqJkNMoDgubmbtthLmZyaiUYekORIrA42- fv1x-04q5Fjff6glh Yb6TI5b0GQeeNrpwNvpDzmO- PSR1swlAbg9fdM9BcNjyrznspUkWpuKu9EC1Ou6v3OXU1KC9nZ7mPlWMFZNkSioQqpwWEvMw- GZktsQzm67qOhUhBNOLWYhbS pkfiqzY-5nw3S0obx30fhd3EJa5O_- GjV_a0nFXQJa70ik40bFOrEh3MtCSbrQT6--DvFy_FQ8TKvkIXadyVskeJI84XOF5WmA60f1pi5GI08i- nRfZS6oDeU gELBjjoFKD8s3L2aI0B6umWVxnQOjqhQRxwJ53b54sZJ2PW3v_mtg9-q0CK0ezS3xfh_y0ilaUGOAZG- xjQFuvU_JZedWpla3xi-MZsmblAifBI (Service: AmazonEC2; Status Code: 403; Error Code: UnauthorizedOperation; Request ID: 6a002f94-ba37-43fd-99e6-39517715fce5) Outputs : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]} Parameters : {[AutomationAssumeRole, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [InstanceIamRole, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [SourceAmiId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]} StepExecutions : {launchInstance, updateOSSoftware, stopInstance, createImage...} Example 2: This example lists step details for the given automation execution id Get-SSMAutomationExecution -AutomationExecutionId e1d2bad3-4567-8901- ae23-456c7c8901be | Select-Object -ExpandProperty StepExecutions | Select-Object StepName, Action, StepStatus, ValidNextSteps Output: StepName Action StepStatus ValidNextSteps -------- ------ ---------- -------------- LaunchInstance aws:runInstances Success {OSCompatibilityCheck} OSCompatibilityCheck aws:runCommand Success {RunPreUpdateScript} RunPreUpdateScript aws:runCommand Success {UpdateEC2Config} UpdateEC2Config aws:runCommand Cancelled {} Actions 2724 AWS Systems Manager User Guide UpdateSSMAgent aws:runCommand Pending {} UpdateAWSPVDriver aws:runCommand Pending {} UpdateAWSEnaNetworkDriver aws:runCommand Pending {} UpdateAWSNVMe aws:runCommand Pending {} InstallWindowsUpdates aws:runCommand Pending {} RunPostUpdateScript aws:runCommand Pending {} RunSysprepGeneralize aws:runCommand Pending {} StopInstance aws:changeInstanceState Pending {} CreateImage aws:createImage Pending {} TerminateInstance aws:changeInstanceState Pending {} • For API details, see GetAutomationExecution in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetCommandInvocation with a CLI The following code examples show how to use GetCommandInvocation. CLI AWS CLI To display the details of a command invocation The following get-command-invocation example lists all the invocations of the specified command on the specified instance. aws ssm get-command-invocation \ --command-id "ef7fdfd8-9b57-4151-a15c-db9a12345678" \ --instance-id "i-1234567890abcdef0" Output: { "CommandId": "ef7fdfd8-9b57-4151-a15c-db9a12345678", "InstanceId": "i-1234567890abcdef0", Actions 2725 AWS Systems Manager User Guide "Comment": "b48291dd-ba76-43e0-b9df-13e11ddaac26:6960febb-2907-4b59-8e1a- d6ce8EXAMPLE", "DocumentName": "AWS-UpdateSSMAgent", "DocumentVersion": "", "PluginName": "aws:updateSsmAgent", "ResponseCode": 0, "ExecutionStartDateTime": "2020-02-19T18:18:03.419Z", "ExecutionElapsedTime": "PT0.091S", "ExecutionEndDateTime": "2020-02-19T18:18:03.419Z", "Status": "Success", "StatusDetails": "Success", "StandardOutputContent": "Updating amazon-ssm-agent from 2.3.842.0 to latest \nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us- east-2/ssm-agent-manifest.json\namazon-ssm-agent 2.3.842.0 has already been installed, update skipped\n", "StandardOutputUrl": "", "StandardErrorContent": "", "StandardErrorUrl": "", "CloudWatchOutputConfig": { "CloudWatchLogGroupName": "", "CloudWatchOutputEnabled": false } } For more information, see Understanding Command Statuses in the AWS Systems Manager User Guide. • For API details, see GetCommandInvocation in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example displays the details of a command executed on an instance. Get-SSMCommandInvocationDetail -InstanceId "i-0cb2b964d3e14fd9f" -CommandId "b8eac879-0541-439d-94ec-47a80d554f44" Output: CommandId : b8eac879-0541-439d-94ec-47a80d554f44 Comment : IP config Actions 2726 AWS Systems Manager User Guide DocumentName : AWS-RunShellScript ExecutionElapsedTime : PT0.004S ExecutionEndDateTime : 2017-02-22T20:13:16.651Z ExecutionStartDateTime : 2017-02-22T20:13:16.651Z InstanceId : i-0cb2b964d3e14fd9f PluginName : aws:runShellScript ResponseCode : 0 StandardErrorContent : StandardErrorUrl : StandardOutputContent : StandardOutputUrl : Status : Success StatusDetails : Success • For API details, see GetCommandInvocation in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetConnectionStatus with a CLI The following
systems-manager-ug-781
systems-manager-ug.pdf
781
Comment : IP config Actions 2726 AWS Systems Manager User Guide DocumentName : AWS-RunShellScript ExecutionElapsedTime : PT0.004S ExecutionEndDateTime : 2017-02-22T20:13:16.651Z ExecutionStartDateTime : 2017-02-22T20:13:16.651Z InstanceId : i-0cb2b964d3e14fd9f PluginName : aws:runShellScript ResponseCode : 0 StandardErrorContent : StandardErrorUrl : StandardOutputContent : StandardOutputUrl : Status : Success StatusDetails : Success • For API details, see GetCommandInvocation in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetConnectionStatus with a CLI The following code examples show how to use GetConnectionStatus. CLI AWS CLI To display the connection status of a managed instance This get-connection-status example returns the connection status of the specified managed instance. aws ssm get-connection-status \ --target i-1234567890abcdef0 Output: { "Target": "i-1234567890abcdef0", "Status": "connected" Actions 2727 AWS Systems Manager } User Guide • For API details, see GetConnectionStatus in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example retrieves the Session Manager connection status for an instance to determine whether it is connected and ready to receive Session Manager connections. Get-SSMConnectionStatus -Target i-0a1caf234f12d3dc4 Output: Status Target ------ ------ Connected i-0a1caf234f12d3dc4 • For API details, see GetConnectionStatus in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetDefaultPatchBaseline with a CLI The following code examples show how to use GetDefaultPatchBaseline. CLI AWS CLI Example 1: To display the default Windows patch baseline The following get-default-patch-baseline example retrieves details for the default patch baseline for Windows Server. aws ssm get-default-patch-baseline Actions 2728 AWS Systems Manager Output: { "BaselineId": "pb-0713accee01612345", "OperatingSystem": "WINDOWS" } User Guide Example 2: To display the default patch baseline for Amazon Linux The following get-default-patch-baseline example retrieves details for the default patch baseline for Amazon Linux. aws ssm get-default-patch-baseline \ --operating-system AMAZON_LINUX Output: { "BaselineId": "pb-047c6eb9c8fc12345", "OperatingSystem": "AMAZON_LINUX" } For more information, see About Predefined and Custom Patch Baselines <https:// docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-baselines.html>__ and Set an Existing Patch Baseline as the Default in the AWS Systems Manager User Guide. • For API details, see GetDefaultPatchBaseline in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example displays the default patch baseline. Get-SSMDefaultPatchBaseline Output: arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 Actions 2729 AWS Systems Manager User Guide • For API details, see GetDefaultPatchBaseline in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetDeployablePatchSnapshotForInstance with a CLI The following code examples show how to use GetDeployablePatchSnapshotForInstance. CLI AWS CLI To retrieve the current snapshot for the patch baseline an instance uses The following get-deployable-patch-snapshot-for-instance example retrieves details for the current snapshot for the specified patch baseline used by an instance. This command must be run from the instance using the instance credentials. To ensure it uses the instance credentials, run aws configure and specify only the Region of your instance. Leave the Access Key and Secret Key fields empty. Tip: Use uuidgen to generate a snapshot-id. aws ssm get-deployable-patch-snapshot-for-instance \ --instance-id "i-1234567890abcdef0" \ --snapshot-id "521c3536-930c-4aa9-950e-01234567abcd" Output: { "InstanceId": "i-1234567890abcdef0", "SnapshotId": "521c3536-930c-4aa9-950e-01234567abcd", "Product": "AmazonLinux2018.03", "SnapshotDownloadUrl": "https://patch-baseline-snapshot-us- east-1.s3.amazonaws.com/ ed85194ef27214f5984f28b4d664d14f7313568fea7d4b6ac6c10ad1f729d7e7-773304212436/ AMAZON_LINUX-521c3536-930c-4aa9-950e-01234567abcd?X-Amz- Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190215T164031Z&X-Amz- SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=AKIAJ5C56P35AEBRX2QQ Actions 2730 AWS Systems Manager User Guide %2F20190215%2Fus-east-1%2Fs3%2Faws4_request&X-Amz- Signature=efaaaf6e3878e77f48a6697e015efdbda9c426b09c5822055075c062f6ad2149" } For more information, see Parameter name: Snapshot ID in the AWS Systems Manager User Guide. • For API details, see GetDeployablePatchSnapshotForInstance in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example displays the current snapshot for the patch baseline used by an Instance. This command must be run from the instance using the instance credentials. To ensure it uses the instance credentials, the example passes an Amazon.Runtime.InstanceProfileAWSCredentials object to the Credentials parameter. $credentials = [Amazon.Runtime.InstanceProfileAWSCredentials]::new() Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435- a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f" -Credentials $credentials Output: InstanceId SnapshotDownloadUrl ---------- ------------------- i-0cb2b964d3e14fd9f https://patch-baseline-snapshot-us-west-2.s3-us- west-2.amazonaws.com/853d0d3db0f0cafe...1692/4681775b-098f-4435... Example 2: This example shows how to get the full SnapshotDownloadUrl. This command must be run from the instance using the instance credentials. To ensure it uses the instance credentials, the example configures the PowerShell session to use an Amazon.Runtime.InstanceProfileAWSCredentials object. Set-AWSCredential -Credential ([Amazon.Runtime.InstanceProfileAWSCredentials]::new()) (Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435- a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f").SnapshotDownloadUrl Actions 2731 AWS Systems Manager Output: User Guide https://patch-baseline-snapshot-us-west-2.s3-us- west-2.amazonaws.com/853d0d3db0f0cafe... • For API details, see GetDeployablePatchSnapshotForInstance in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetDocument with a CLI The following code examples show how to use GetDocument. CLI AWS CLI To
systems-manager-ug-782
systems-manager-ug.pdf
782
it uses the instance credentials, the example configures the PowerShell session to use an Amazon.Runtime.InstanceProfileAWSCredentials object. Set-AWSCredential -Credential ([Amazon.Runtime.InstanceProfileAWSCredentials]::new()) (Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435- a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f").SnapshotDownloadUrl Actions 2731 AWS Systems Manager Output: User Guide https://patch-baseline-snapshot-us-west-2.s3-us- west-2.amazonaws.com/853d0d3db0f0cafe... • For API details, see GetDeployablePatchSnapshotForInstance in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetDocument with a CLI The following code examples show how to use GetDocument. CLI AWS CLI To get document content The following get-document example displays the content of a Systems Manager document. aws ssm get-document \ --name "AWS-RunShellScript" Output: { "Name": "AWS-RunShellScript", "DocumentVersion": "1", "Status": "Active", "Content": "{\n \"schemaVersion\":\"1.2\",\n \"description\":\"Run a shell script or specify the commands to run.\",\n \"parameters\":{\n \"commands\":{\n \"type\":\"StringList\",\n \"description\":\"(Required) Specify a shell script or a command to run.\", \n \"minItems\":1,\n \"displayType\":\"textarea\"\n },\n \"workingDirectory\":{\n \"type\":\"String\",\n \"default\":\"\",\n \"description\":\"(Optional) The Actions 2732 AWS Systems Manager User Guide path to the working directory on your instance.\",\n \"maxChars \":4096\n },\n \"executionTimeout\":{\n \"type\": \"String\",\n \"default\":\"3600\",\n \"description \":\"(Optional) The time in seconds for a command to complete before it is considered to have failed. Default is 3600 (1 hour). Maximum is 172800 (48 hours).\",\n \"allowedPattern\":\"([1-9][0-9]{0,4})|(1[0-6][0-9] {4})|(17[0-1][0-9]{3})|(172[0-7][0-9]{2})|(172800)\"\n }\n },\n \"runtimeConfig\":{\n \"aws:runShellScript\":{\n \"properties \":[\n {\n \"id\":\"0.aws:runShellScript \",\n \"runCommand\":\"{{ commands }}\",\n \"workingDirectory\":\"{{ workingDirectory }}\",\n \"timeoutSeconds\":\"{{ executionTimeout }}\"\n }\n ]\n }\n }\n}\n", "DocumentType": "Command", "DocumentFormat": "JSON" } For more information, see AWS Systems Manager Documents in the AWS Systems Manager User Guide. • For API details, see GetDocument in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example returns the content of a document. Get-SSMDocument -Name "RunShellScript" Output: Content ------- {... Example 2: This example displays the complete contents of a document. (Get-SSMDocument -Name "RunShellScript").Content { "schemaVersion":"2.0", "description":"Run an updated script", Actions 2733 AWS Systems Manager User Guide "parameters":{ "commands":{ "type":"StringList", "description":"(Required) Specify a shell script or a command to run.", "minItems":1, "displayType":"textarea" } }, "mainSteps":[ { "action":"aws:runShellScript", "name":"runShellScript", "inputs":{ "commands":"{{ commands }}" } }, { "action":"aws:runPowerShellScript", "name":"runPowerShellScript", "inputs":{ "commands":"{{ commands }}" } } ] } • For API details, see GetDocument in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetInventory with a CLI The following code examples show how to use GetInventory. CLI AWS CLI To view your inventory This example gets the custom metadata for your inventory. Actions 2734 User Guide AWS Systems Manager Command: aws ssm get-inventory Output: { "Entities": [ { "Data": { "AWS:InstanceInformation": { "Content": [ { "ComputerName": "ip-172-31-44-222.us- west-2.compute.internal", "InstanceId": "i-0cb2b964d3e14fd9f", "IpAddress": "172.31.44.222", "AgentType": "amazon-ssm-agent", "ResourceType": "EC2Instance", "AgentVersion": "2.0.672.0", "PlatformVersion": "2016.09", "PlatformName": "Amazon Linux AMI", "PlatformType": "Linux" } ], "TypeName": "AWS:InstanceInformation", "SchemaVersion": "1.0", "CaptureTime": "2017-02-20T18:03:58Z" } }, "Id": "i-0cb2b964d3e14fd9f" } ] } • For API details, see GetInventory in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example gets the custom metadata for your inventory. Actions 2735 AWS Systems Manager User Guide Get-SSMInventory Output: Data Id ---- -- {[AWS:InstanceInformation, Amazon.SimpleSystemsManagement.Model.InventoryResultItem]} i-0cb2b964d3e14fd9f • For API details, see GetInventory in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetInventorySchema with a CLI The following code examples show how to use GetInventorySchema. CLI AWS CLI To view your inventory schema This example returns a list of inventory type names for the account. Command: aws ssm get-inventory-schema Output: { "Schemas": [ { "TypeName": "AWS:AWSComponent", "Version": "1.0", Actions 2736 AWS Systems Manager User Guide "Attributes": [ { "Name": "Name", "DataType": "STRING" }, { "Name": "ApplicationType", "DataType": "STRING" }, { "Name": "Publisher", "DataType": "STRING" }, { "Name": "Version", "DataType": "STRING" }, { "Name": "InstalledTime", "DataType": "STRING" }, { "Name": "Architecture", "DataType": "STRING" }, { "Name": "URL", "DataType": "STRING" } ] }, ... ], "NextToken": "--token string truncated--" } To view the inventory schema for a specific inventory type This example return the inventory schema for a the AWS:AWSComponent inventory type. Command: aws ssm get-inventory-schema --type-name "AWS:AWSComponent" Actions 2737 AWS Systems Manager User Guide • For API details, see GetInventorySchema in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example returns a list of inventory type names for the account. Get-SSMInventorySchema • For API details, see GetInventorySchema in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use
systems-manager-ug-783
systems-manager-ug.pdf
783
the inventory schema for a the AWS:AWSComponent inventory type. Command: aws ssm get-inventory-schema --type-name "AWS:AWSComponent" Actions 2737 AWS Systems Manager User Guide • For API details, see GetInventorySchema in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example returns a list of inventory type names for the account. Get-SSMInventorySchema • For API details, see GetInventorySchema in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetMaintenanceWindow with a CLI The following code examples show how to use GetMaintenanceWindow. CLI AWS CLI To get information about a maintenance window The following get-maintenance-window example retrieves details about the specified maintenance window. aws ssm get-maintenance-window \ --window-id "mw-03eb9db428EXAMPLE" Output: { "AllowUnassociatedTargets": true, "CreatedDate": 1515006912.957, "Cutoff": 1, "Duration": 6, "Enabled": true, Actions 2738 AWS Systems Manager User Guide "ModifiedDate": 2020-01-01T10:04:04.099Z, "Name": "My-Maintenance-Window", "Schedule": "rate(3 days)", "WindowId": "mw-03eb9db428EXAMPLE", "NextExecutionTime": "2020-02-25T00:08:15.099Z" } For more information, see View information about maintenance windows (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see GetMaintenanceWindow in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example gets details about a maintenance window. Get-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" Output: AllowUnassociatedTargets : False CreatedDate : 2/20/2017 6:14:05 PM Cutoff : 1 Duration : 2 Enabled : True ModifiedDate : 2/20/2017 6:14:05 PM Name : TestMaintWin Schedule : cron(0 */30 * * * ? *) WindowId : mw-03eb9db42890fb82d • For API details, see GetMaintenanceWindow in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetMaintenanceWindowExecution with a CLI The following code examples show how to use GetMaintenanceWindowExecution. Actions 2739 AWS Systems Manager CLI AWS CLI User Guide To get information about a maintenance window task execution The following get-maintenance-window-execution example lists information about a task executed as part of the specified maintenance window execution. aws ssm get-maintenance-window-execution \ --window-execution-id "518d5565-5969-4cca-8f0e-da3b2EXAMPLE" Output: { "Status": "SUCCESS", "TaskIds": [ "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE" ], "StartTime": 1487692834.595, "EndTime": 1487692835.051, "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2EXAMPLE", } For more information, see View Information About Tasks and Task Executions (AWS CLI) in the AWS Systems Manager User Guide. • For API details, see GetMaintenanceWindowExecution in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists information about a task executed as part of a maintenance window execution. Get-SSMMaintenanceWindowExecution -WindowExecutionId "518d5565-5969-4cca-8f0e- da3b2a638355" Output: EndTime : 2/21/2017 4:00:35 PM Actions 2740 AWS Systems Manager User Guide StartTime : 2/21/2017 4:00:34 PM Status : FAILED StatusDetails : One or more tasks in the orchestration failed. TaskIds : {ac0c6ae1-daa3-4a89-832e-d384503b6586} WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355 • For API details, see GetMaintenanceWindowExecution in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetMaintenanceWindowExecutionTask with a CLI The following code examples show how to use GetMaintenanceWindowExecutionTask. CLI AWS CLI To get information about a maintenance window task execution The following get-maintenance-window-execution-task example lists information about a task that is part of the specified maintenance window execution. aws ssm get-maintenance-window-execution-task \ --window-execution-id "518d5565-5969-4cca-8f0e-da3b2EXAMPLE" \ --task-id "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE" Output: { "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2EXAMPLE", "TaskExecutionId": "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE", "TaskArn": "AWS-RunPatchBaseline", "ServiceRole": "arn:aws:iam::111222333444:role/aws-service-role/ ssm.amazonaws.com/AWSServiceRoleForAmazonSSM", "Type": "RUN_COMMAND", "TaskParameters": [ { "BaselineOverride": { Actions 2741 AWS Systems Manager User Guide "Values": [ "" ] }, "InstallOverrideList": { "Values": [ "" ] }, "Operation": { "Values": [ "Scan" ] }, "RebootOption": { "Values": [ "RebootIfNeeded" ] }, "SnapshotId": { "Values": [ "{{ aws:ORCHESTRATION_ID }}" ] }, "aws:InstanceId": { "Values": [ "i-02573cafcfEXAMPLE", "i-0471e04240EXAMPLE", "i-07782c72faEXAMPLE" ] } } ], "Priority": 1, "MaxConcurrency": "1", "MaxErrors": "3", "Status": "SUCCESS", "StartTime": "2021-08-04T11:45:35.088000-07:00", "EndTime": "2021-08-04T11:53:09.079000-07:00" } For more information, see View information about tasks and task executions (AWS CLI) in the AWS Systems Manager User Guide. Actions 2742 AWS Systems Manager User Guide • For API details, see GetMaintenanceWindowExecutionTask in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists information about a task that was part of a maintenance window execution. Get-SSMMaintenanceWindowExecutionTask -TaskId "ac0c6ae1-daa3-4a89-832e- d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355" Output: EndTime : 2/21/2017 4:00:35 PM MaxConcurrency : 1 MaxErrors : 1 Priority : 10 ServiceRole : arn:aws:iam::123456789012:role/MaintenanceWindowsRole StartTime : 2/21/2017 4:00:34 PM Status : FAILED StatusDetails : The maximum error count was exceeded. TaskArn : AWS-RunShellScript TaskExecutionId : ac0c6ae1-daa3-4a89-832e-d384503b6586 TaskParameters : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskPara meterValueExpression]} Type : RUN_COMMAND WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355 • For API details, see GetMaintenanceWindowExecutionTask in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This
systems-manager-ug-784
systems-manager-ug.pdf
784
a task that was part of a maintenance window execution. Get-SSMMaintenanceWindowExecutionTask -TaskId "ac0c6ae1-daa3-4a89-832e- d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355" Output: EndTime : 2/21/2017 4:00:35 PM MaxConcurrency : 1 MaxErrors : 1 Priority : 10 ServiceRole : arn:aws:iam::123456789012:role/MaintenanceWindowsRole StartTime : 2/21/2017 4:00:34 PM Status : FAILED StatusDetails : The maximum error count was exceeded. TaskArn : AWS-RunShellScript TaskExecutionId : ac0c6ae1-daa3-4a89-832e-d384503b6586 TaskParameters : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskPara meterValueExpression]} Type : RUN_COMMAND WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355 • For API details, see GetMaintenanceWindowExecutionTask in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 2743 AWS Systems Manager User Guide Use GetParameter with an AWS SDK or CLI The following code examples show how to use GetParameter. CLI AWS CLI Example 1: To display the value of a parameter The following get-parameter example lists the value for the specified single parameter. aws ssm get-parameter \ --name "MyStringParameter" Output: { "Parameter": { "Name": "MyStringParameter", "Type": "String", "Value": "Veni", "Version": 1, "LastModifiedDate": 1530018761.888, "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/MyStringParameter" "DataType": "text" } } For more information, see Working with Parameter Store in the AWS Systems Manager User Guide. Example 2: To decrypt the value of a SecureString parameter The following get-parameter example decrypts the value of the specified SecureString parameter. aws ssm get-parameter \ --name "MySecureStringParameter" \ --with-decryption Output: Actions 2744 AWS Systems Manager User Guide { "Parameter": { "Name": "MySecureStringParameter", "Type": "SecureString", "Value": "16679b88-310b-4895-a943-e0764EXAMPLE", "Version": 2, "LastModifiedDate": 1582155479.205, "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/ MySecureStringParameter" "DataType": "text" } } For more information, see Working with Parameter Store in the AWS Systems Manager User Guide. Example 3: To display the value of a parameter using labels The following get-parameter example lists the value for the specified single parameter with a specified label. aws ssm get-parameter \ --name "MyParameter:label" Output: { "Parameter": { "Name": "MyParameter", "Type": "String", "Value": "parameter version 2", "Version": 2, "Selector": ":label", "LastModifiedDate": "2021-07-12T09:49:15.865000-07:00", "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/MyParameter", "DataType": "text" } } For more information, see Working with parameter labels in the AWS Systems Manager User Guide. Actions 2745 AWS Systems Manager User Guide Example 4: To display the value of a parameter using versions The following get-parameter example lists the value for the specified single parameter version. aws ssm get-parameter \ --name "MyParameter:2" Output: { "Parameter": { "Name": "MyParameter", "Type": "String", "Value": "parameter version 2", "Version": 2, "Selector": ":2", "LastModifiedDate": "2021-07-12T09:49:15.865000-07:00", "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/MyParameter", "DataType": "text" } } For more information, see Working with parameter labels in the AWS Systems Manager User Guide. • For API details, see GetParameter in AWS CLI Command Reference. Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. pub async fn list_path(&self, path: &str) -> Result<Vec<Parameter>, EC2Error> { Actions 2746 AWS Systems Manager User Guide let maybe_params: Vec<Result<Parameter, _>> = TryFlatMap::new( self.inner .get_parameters_by_path() .path(path) .into_paginator() .send(), ) .flat_map(|item| item.parameters.unwrap_or_default()) .collect() .await; // Fail on the first error let params = maybe_params .into_iter() .collect::<Result<Vec<Parameter>, _>>()?; Ok(params) } • For API details, see GetParameter in AWS SDK for Rust API reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetParameterHistory with a CLI The following code examples show how to use GetParameterHistory. CLI AWS CLI To get a value history for a parameter The following get-parameter-history example lists the history of changes for the specified parameter, including its value. aws ssm get-parameter-history \ --name "MyStringParameter" Output: Actions 2747 AWS Systems Manager User Guide { "Parameters": [ { "Name": "MyStringParameter", "Type": "String", "LastModifiedDate": 1582154711.976, "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major", "Description": "This is the first version of my String parameter", "Value": "Veni", "Version": 1, "Labels": [], "Tier": "Standard", "Policies": [] }, { "Name": "MyStringParameter", "Type": "String", "LastModifiedDate": 1582156093.471, "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major", "Description": "This is the second version of my String parameter", "Value": "Vidi", "Version": 2, "Labels": [], "Tier": "Standard", "Policies": [] }, { "Name": "MyStringParameter", "Type": "String", "LastModifiedDate": 1582156117.545, "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major", "Description": "This is the third version of my String parameter", "Value": "Vici", "Version": 3, "Labels": [], "Tier": "Standard", "Policies": [] } ] } For more information, see Working with parameter versions in the AWS Systems Manager User Guide. Actions 2748 AWS Systems Manager User Guide • For API details, see GetParameterHistory in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists the value history for a parameter. Get-SSMParameterHistory -Name "Welcome" Output: Description : KeyId : LastModifiedDate : 3/3/2017 6:55:25 PM LastModifiedUser : arn:aws:iam::123456789012:user/admin Name : Welcome Type : String Value : helloWorld • For API details, see GetParameterHistory in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer
systems-manager-ug-785
systems-manager-ug.pdf
785
"Standard", "Policies": [] } ] } For more information, see Working with parameter versions in the AWS Systems Manager User Guide. Actions 2748 AWS Systems Manager User Guide • For API details, see GetParameterHistory in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists the value history for a parameter. Get-SSMParameterHistory -Name "Welcome" Output: Description : KeyId : LastModifiedDate : 3/3/2017 6:55:25 PM LastModifiedUser : arn:aws:iam::123456789012:user/admin Name : Welcome Type : String Value : helloWorld • For API details, see GetParameterHistory in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetParameters with a CLI The following code examples show how to use GetParameters. CLI AWS CLI Example 1: To list the values for a parameter The following get-parameters example lists the values for the three specified parameters. aws ssm get-parameters \ Actions 2749 AWS Systems Manager User Guide --names "MyStringParameter" "MyStringListParameter" "MyInvalidParameterName" Output: { "Parameters": [ { "Name": "MyStringListParameter", "Type": "StringList", "Value": "alpha,beta,gamma", "Version": 1, "LastModifiedDate": 1582154764.222, "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/ MyStringListParameter" "DataType": "text" }, { "Name": "MyStringParameter", "Type": "String", "Value": "Vici", "Version": 3, "LastModifiedDate": 1582156117.545, "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/ MyStringParameter" "DataType": "text" } ], "InvalidParameters": [ "MyInvalidParameterName" ] } For more information, see Working with Parameter Store in the AWS Systems Manager User Guide. Example 2: To list names and values of multiple parameters using the ``--query`` option The following get-parameters example lists the names and values for the specified parameters. aws ssm get-parameters \ Actions 2750 AWS Systems Manager User Guide --names MyStringParameter MyStringListParameter \ --query "Parameters[*].{Name:Name,Value:Value}" Output: [ { "Name": "MyStringListParameter", "Value": "alpha,beta,gamma" }, { "Name": "MyStringParameter", "Value": "Vidi" } ] For more information, see Working with Parameter Store in the AWS Systems Manager User Guide. Example 3: To display the value of a parameter using labels The following get-parameter example lists the value for the specified single parameter with a specified label. aws ssm get-parameter \ --name "MyParameter:label" Output: { "Parameters": [ { "Name": "MyLabelParameter", "Type": "String", "Value": "parameter by label", "Version": 1, "Selector": ":label", "LastModifiedDate": "2021-07-12T09:49:15.865000-07:00", "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/MyParameter", "DataType": "text" }, { Actions 2751 AWS Systems Manager User Guide "Name": "MyVersionParameter", "Type": "String", "Value": "parameter by version", "Version": 2, "Selector": ":2", "LastModifiedDate": "2021-03-24T16:20:28.236000-07:00", "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/unlabel-param", "DataType": "text" } ], "InvalidParameters": [] } For more information, see Working with parameter labels in the AWS Systems Manager User Guide. • For API details, see GetParameters in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists the values for a parameter. Get-SSMParameterValue -Name "Welcome" Output: InvalidParameters Parameters ----------------- ---------- {} {Welcome} Example 2: This example lists the details of the value. (Get-SSMParameterValue -Name "Welcome").Parameters Output: Name Type Value ---- ---- ----- Welcome String Good day, Sunshine! Actions 2752 AWS Systems Manager User Guide • For API details, see GetParameters in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetPatchBaseline with a CLI The following code examples show how to use GetPatchBaseline. CLI AWS CLI To display a patch baseline The following get-patch-baseline example retrieves the details for the specified patch baseline. aws ssm get-patch-baseline \ --baseline-id "pb-0123456789abcdef0" Output: { "BaselineId": "pb-0123456789abcdef0", "Name": "WindowsPatching", "OperatingSystem": "WINDOWS", "GlobalFilters": { "PatchFilters": [] }, "ApprovalRules": { "PatchRules": [ { "PatchFilterGroup": { "PatchFilters": [ { "Key": "PRODUCT", "Values": [ "WindowsServer2016" ] Actions 2753 AWS Systems Manager User Guide } ] }, "ComplianceLevel": "CRITICAL", "ApproveAfterDays": 0, "EnableNonSecurity": false } ] }, "ApprovedPatches": [], "ApprovedPatchesComplianceLevel": "UNSPECIFIED", "ApprovedPatchesEnableNonSecurity": false, "RejectedPatches": [], "RejectedPatchesAction": "ALLOW_AS_DEPENDENCY", "PatchGroups": [ "QA", "DEV" ], "CreatedDate": 1550244180.465, "ModifiedDate": 1550244180.465, "Description": "Patches for Windows Servers", "Sources": [] } For more information, see About Patch Baselines in the AWS Systems Manager User Guide. • For API details, see GetPatchBaseline in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example displays the details for a patch baseline. Get-SSMPatchBaselineDetail -BaselineId "pb-03da896ca3b68b639" Output: ApprovalRules : Amazon.SimpleSystemsManagement.Model.PatchRuleGroup ApprovedPatches : {} BaselineId : pb-03da896ca3b68b639 CreatedDate : 3/3/2017 5:02:19 PM Description : Baseline containing all updates approved for production systems Actions 2754 AWS Systems Manager User Guide GlobalFilters : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup ModifiedDate : 3/3/2017 5:02:19 PM Name : Production-Baseline PatchGroups : {} RejectedPatches : {} • For API details, see GetPatchBaseline in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetPatchBaselineForPatchGroup with a CLI The following code examples show how to use GetPatchBaselineForPatchGroup. CLI AWS CLI
systems-manager-ug-786
systems-manager-ug.pdf
786
5:02:19 PM Description : Baseline containing all updates approved for production systems Actions 2754 AWS Systems Manager User Guide GlobalFilters : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup ModifiedDate : 3/3/2017 5:02:19 PM Name : Production-Baseline PatchGroups : {} RejectedPatches : {} • For API details, see GetPatchBaseline in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetPatchBaselineForPatchGroup with a CLI The following code examples show how to use GetPatchBaselineForPatchGroup. CLI AWS CLI To display the patch baseline for a patch group The following get-patch-baseline-for-patch-group example retrieves details about the patch baseline for the specified patch group. aws ssm get-patch-baseline-for-patch-group \ --patch-group "DEV" Output: { "PatchGroup": "DEV", "BaselineId": "pb-0123456789abcdef0", "OperatingSystem": "WINDOWS" } For more information, see Create a Patch Group <https://docs.aws.amazon.com/systems- manager/latest/userguide/sysman-patch-group-tagging.html>__ and Add a Patch Group to a Patch Baseline in the AWS Systems Manager User Guide. • For API details, see GetPatchBaselineForPatchGroup in AWS CLI Command Reference. Actions 2755 AWS Systems Manager PowerShell Tools for PowerShell User Guide Example 1: This example displays the patch baseline for a patch group. Get-SSMPatchBaselineForPatchGroup -PatchGroup "Production" Output: BaselineId PatchGroup ---------- ---------- pb-045f10b4f382baeda Production • For API details, see GetPatchBaselineForPatchGroup in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use ListAssociationVersions with a CLI The following code examples show how to use ListAssociationVersions. CLI AWS CLI To list all versions of an association for a specific association ID The following list-association-versions example lists all versions of the specified associations. aws ssm list-association-versions \ --association-id "8dfe3659-4309-493a-8755-0123456789ab" Output: { "AssociationVersions": [ Actions 2756 AWS Systems Manager { User Guide "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "AssociationVersion": "1", "CreatedDate": 1550505536.726, "Name": "AWS-UpdateSSMAgent", "Parameters": { "allowDowngrade": [ "false" ], "version": [ "" ] }, "Targets": [ { "Key": "InstanceIds", "Values": [ "i-1234567890abcdef0" ] } ], "ScheduleExpression": "cron(0 00 12 ? * SUN *)", "AssociationName": "UpdateSSMAgent" } ] } For more information, see Working with associations in Systems Manager in the AWS Systems Manager User Guide. • For API details, see ListAssociationVersions in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example retrieves all versions of the association provided. Get-SSMAssociationVersionList -AssociationId 123a45a0-c678-9012-3456-78901234db5e Output: AssociationId : 123a45a0-c678-9012-3456-78901234db5e Actions 2757 AWS Systems Manager User Guide AssociationName : AssociationVersion : 2 ComplianceSeverity : CreatedDate : 3/12/2019 9:21:01 AM DocumentVersion : MaxConcurrency : MaxErrors : Name : AWS-GatherSoftwareInventory OutputLocation : Parameters : {} ScheduleExpression : Targets : {InstanceIds} AssociationId : 123a45a0-c678-9012-3456-78901234db5e AssociationName : test-case-1234567890 AssociationVersion : 1 ComplianceSeverity : CreatedDate : 3/2/2019 8:53:29 AM DocumentVersion : MaxConcurrency : MaxErrors : Name : AWS-GatherSoftwareInventory OutputLocation : Parameters : {} ScheduleExpression : rate(30minutes) Targets : {InstanceIds} • For API details, see ListAssociationVersions in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use ListAssociations with a CLI The following code examples show how to use ListAssociations. CLI AWS CLI Example 1: To list your associations for a specific instance Actions 2758 AWS Systems Manager User Guide The following list-associations example lists all associations with the AssociationName, UpdateSSMAgent. aws ssm list-associations / --association-filter-list "key=AssociationName,value=UpdateSSMAgent" Output: { "Associations": [ { "Name": "AWS-UpdateSSMAgent", "InstanceId": "i-1234567890abcdef0", "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "AssociationVersion": "1", "Targets": [ { "Key": "InstanceIds", "Values": [ "i-016648b75dd622dab" ] } ], "Overview": { "Status": "Pending", "DetailedStatus": "Associated", "AssociationStatusAggregatedCount": { "Pending": 1 } }, "ScheduleExpression": "cron(0 00 12 ? * SUN *)", "AssociationName": "UpdateSSMAgent" } ] } For more information, see Working with associations in Systems Manager in the Systems Manager User Guide. Example 2: To list your associations for a specific document The following list-associations example lists all associations for the specified document. Actions 2759 AWS Systems Manager User Guide aws ssm list-associations / --association-filter-list "key=Name,value=AWS-UpdateSSMAgent" Output: { "Associations": [ { "Name": "AWS-UpdateSSMAgent", "InstanceId": "i-1234567890abcdef0", "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab", "AssociationVersion": "1", "Targets": [ { "Key": "InstanceIds", "Values": [ "i-1234567890abcdef0" ] } ], "LastExecutionDate": 1550505828.548, "Overview": { "Status": "Success", "DetailedStatus": "Success", "AssociationStatusAggregatedCount": { "Success": 1 } }, "ScheduleExpression": "cron(0 00 12 ? * SUN *)", "AssociationName": "UpdateSSMAgent" }, { "Name": "AWS-UpdateSSMAgent", "InstanceId": "i-9876543210abcdef0", "AssociationId": "fbc07ef7-b985-4684-b82b-0123456789ab", "AssociationVersion": "1", "Targets": [ { "Key": "InstanceIds", "Values": [ "i-9876543210abcdef0" ] } Actions 2760 AWS Systems Manager ], "LastExecutionDate": 1550507531.0, "Overview": { "Status": "Success", "AssociationStatusAggregatedCount": { "Success": 1 User Guide } } } ] } For more information, see Working with associations in Systems Manager in the Systems Manager User Guide. • For API details, see ListAssociations in AWS CLI Command Reference. PowerShell Tools for PowerShell
systems-manager-ug-787
systems-manager-ug.pdf
787
} ], "LastExecutionDate": 1550505828.548, "Overview": { "Status": "Success", "DetailedStatus": "Success", "AssociationStatusAggregatedCount": { "Success": 1 } }, "ScheduleExpression": "cron(0 00 12 ? * SUN *)", "AssociationName": "UpdateSSMAgent" }, { "Name": "AWS-UpdateSSMAgent", "InstanceId": "i-9876543210abcdef0", "AssociationId": "fbc07ef7-b985-4684-b82b-0123456789ab", "AssociationVersion": "1", "Targets": [ { "Key": "InstanceIds", "Values": [ "i-9876543210abcdef0" ] } Actions 2760 AWS Systems Manager ], "LastExecutionDate": 1550507531.0, "Overview": { "Status": "Success", "AssociationStatusAggregatedCount": { "Success": 1 User Guide } } } ] } For more information, see Working with associations in Systems Manager in the Systems Manager User Guide. • For API details, see ListAssociations in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists all the associations for an instance. The syntax used by this example requires PowerShell version 3 or later. $filter1 = @{Key="InstanceId";Value=@("i-0000293ffd8c57862")} Get-SSMAssociationList -AssociationFilterList $filter1 Output: AssociationId : d8617c07-2079-4c18-9847-1655fc2698b0 DocumentVersion : InstanceId : i-0000293ffd8c57862 LastExecutionDate : 2/20/2015 8:31:11 AM Name : AWS-UpdateSSMAgent Overview : Amazon.SimpleSystemsManagement.Model.AssociationOverview ScheduleExpression : Targets : {InstanceIds} Example 2: This example lists all associations for a configuration document. The syntax used by this example requires PowerShell version 3 or later. $filter2 = @{Key="Name";Value=@("AWS-UpdateSSMAgent")} Actions 2761 AWS Systems Manager User Guide Get-SSMAssociationList -AssociationFilterList $filter2 Output: AssociationId : d8617c07-2079-4c18-9847-1655fc2698b0 DocumentVersion : InstanceId : i-0000293ffd8c57862 LastExecutionDate : 2/20/2015 8:31:11 AM Name : AWS-UpdateSSMAgent Overview : Amazon.SimpleSystemsManagement.Model.AssociationOverview ScheduleExpression : Targets : {InstanceIds} Example 3: With PowerShell version 2, you must use New-Object to create each filter. $filter1 = New-Object Amazon.SimpleSystemsManagement.Model.AssociationFilter $filter1.Key = "InstanceId" $filter1.Value = "i-0000293ffd8c57862" Get-SSMAssociationList -AssociationFilterList $filter1 Output: AssociationId : d8617c07-2079-4c18-9847-1655fc2698b0 DocumentVersion : InstanceId : i-0000293ffd8c57862 LastExecutionDate : 2/20/2015 8:31:11 AM Name : AWS-UpdateSSMAgent Overview : Amazon.SimpleSystemsManagement.Model.AssociationOverview ScheduleExpression : Targets : {InstanceIds} • For API details, see ListAssociations in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use ListCommandInvocations with an AWS SDK or CLI The following code examples show how to use ListCommandInvocations. Actions 2762 AWS Systems Manager User Guide Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Learn the basics CLI AWS CLI To list the invocations of a specific command The following list-command-invocations example lists all the invocations of a command. aws ssm list-command-invocations \ --command-id "ef7fdfd8-9b57-4151-a15c-db9a12345678" \ --details Output: { "CommandInvocations": [ { "CommandId": "ef7fdfd8-9b57-4151-a15c-db9a12345678", "InstanceId": "i-02573cafcfEXAMPLE", "InstanceName": "", "Comment": "b48291dd-ba76-43e0- b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE", "DocumentName": "AWS-UpdateSSMAgent", "DocumentVersion": "", "RequestedDateTime": 1582136283.089, "Status": "Success", "StatusDetails": "Success", "StandardOutputUrl": "", "StandardErrorUrl": "", "CommandPlugins": [ { "Name": "aws:updateSsmAgent", "Status": "Success", "StatusDetails": "Success", "ResponseCode": 0, "ResponseStartDateTime": 1582136283.419, Actions 2763 AWS Systems Manager User Guide "ResponseFinishDateTime": 1582136283.51, "Output": "Updating amazon-ssm-agent from 2.3.842.0 to latest \nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us- east-2/ssm-agent-manifest.json\namazon-ssm-agent 2.3.842.0 has already been installed, update skipped\n", "StandardOutputUrl": "", "StandardErrorUrl": "", "OutputS3Region": "us-east-2", "OutputS3BucketName": "", "OutputS3KeyPrefix": "" } ], "ServiceRole": "", "NotificationConfig": { "NotificationArn": "", "NotificationEvents": [], "NotificationType": "" }, "CloudWatchOutputConfig": { "CloudWatchLogGroupName": "", "CloudWatchOutputEnabled": false } }, { "CommandId": "ef7fdfd8-9b57-4151-a15c-db9a12345678", "InstanceId": "i-0471e04240EXAMPLE", "InstanceName": "", "Comment": "b48291dd-ba76-43e0- b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE", "DocumentName": "AWS-UpdateSSMAgent", "DocumentVersion": "", "RequestedDateTime": 1582136283.02, "Status": "Success", "StatusDetails": "Success", "StandardOutputUrl": "", "StandardErrorUrl": "", "CommandPlugins": [ { "Name": "aws:updateSsmAgent", "Status": "Success", "StatusDetails": "Success", "ResponseCode": 0, "ResponseStartDateTime": 1582136283.812, "ResponseFinishDateTime": 1582136295.031, Actions 2764 AWS Systems Manager User Guide "Output": "Updating amazon-ssm-agent from 2.3.672.0 to latest\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon- ssm-us-east-2/ssm-agent-manifest.json\nSuccessfully downloaded https://s3.us- east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent-updater/2.3.842.0/ amazon-ssm-agent-updater-snap-amd64.tar.gz\nSuccessfully downloaded https:// s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent/2.3.672.0/ amazon-ssm-agent-snap-amd64.tar.gz\nSuccessfully downloaded https://s3.us- east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent/2.3.842.0/amazon-ssm- agent-snap-amd64.tar.gz\nInitiating amazon-ssm-agent update to 2.3.842.0\namazon- ssm-agent updated successfully to 2.3.842.0", "StandardOutputUrl": "", "StandardErrorUrl": "", "OutputS3Region": "us-east-2", "OutputS3BucketName": "", "OutputS3KeyPrefix": "8bee3135-398c-4d31-99b6-e42d2EXAMPLE/ i-0471e04240EXAMPLE/awsupdateSsmAgent" } ], "ServiceRole": "", "NotificationConfig": { "NotificationArn": "", "NotificationEvents": [], "NotificationType": "" }, "CloudWatchOutputConfig": { "CloudWatchLogGroupName": "", "CloudWatchOutputEnabled": false } } ] } For more information, see Understanding Command Statuses in the AWS Systems Manager User Guide. • For API details, see ListCommandInvocations in AWS CLI Command Reference. Actions 2765 AWS Systems Manager JavaScript SDK for JavaScript (v3) Note User Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { paginateListCommandInvocations, SSMClient } from "@aws-sdk/client-ssm"; import { parseArgs } from "node:util"; /** * List SSM command invocations on an instance. * @param {{ instanceId: string }} */ export const main = async ({ instanceId }) => { const client = new SSMClient({}); try { const listCommandInvocationsPaginated = []; // The paginate function is a wrapper around the base command. const paginator = paginateListCommandInvocations( { client }, { InstanceId: instanceId, }, ); for await (const page of paginator) { listCommandInvocationsPaginated.push(...page.CommandInvocations); } console.log("Here is the list of command invocations:"); console.log(listCommandInvocationsPaginated); return { CommandInvocations: listCommandInvocationsPaginated }; } catch (caught) { if (caught instanceof Error && caught.name === "ValidationError") { console.warn(`${caught.message}. Did you provide a valid instance ID?`); } throw caught; } }; Actions 2766 AWS Systems Manager User Guide • For API details,