

• The AWS Systems Manager CloudWatch Dashboard will no longer be available after April 30, 2026. Customers can continue to use Amazon CloudWatch console to view, create, and manage their Amazon CloudWatch dashboards, just as they do today. For more information, see [Amazon CloudWatch Dashboard documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html). 

# AWS Systems Manager State Manager
State Manager

State Manager, a tool in AWS Systems Manager, is a secure and scalable configuration management service that automates the process of keeping your managed nodes and other AWS resources in a state that you define. To get started with State Manager, open the [Systems Manager console](https://console.aws.amazon.com//systems-manager/state-manager). In the navigation pane, choose **State Manager**.

**Note**  
State Manager and Maintenance Windows can perform some similar types of updates on your managed nodes. Which one you choose depends on whether you need to automate system compliance or perform high-priority, time-sensitive tasks during periods you specify.  
For more information, see [Choosing between State Manager and Maintenance Windows](state-manager-vs-maintenance-windows.md).

## How can State Manager benefit my organization?


By using pre-configured Systems Manager documents (SSM documents), State Manager offers the following benefits for managing your nodes:
+ Bootstrap nodes with specific software at start-up.
+ Download and update agents on a defined schedule, including the SSM Agent.
+ Configure network settings.
+ Join nodes to a Microsoft Active Directory domain.
+ Run scripts on Linux, macOS, and Windows Server managed nodes throughout their lifecycle.

To manage configuration drift across other AWS resources, you can use Automation, a tool in Systems Manager, with State Manager to perform the following types of tasks:
+ Attach a Systems Manager role to Amazon Elastic Compute Cloud (Amazon EC2) instances to make them *managed nodes*.
+ Enforce desired ingress and egress rules for a security group.
+ Create or delete Amazon DynamoDB backups.
+ Create or delete Amazon Elastic Block Store (Amazon EBS) snapshots.
+ Turn off read and write permissions on Amazon Simple Storage Service (Amazon S3) buckets.
+ Start, restart, or stop managed nodes and Amazon Relational Database Service (Amazon RDS) instances.
+ Apply patches to Linux, macOS, and Window AMIs.

For information about using State Manager with Automation runbooks, see [Scheduling automations with State Manager associations](scheduling-automations-state-manager-associations.md).

## Who should use State Manager?


State Manager is appropriate for any AWS customer that wants to improve the management and governance of their AWS resources and reduce configuration drift.

## What are the features of State Manager?


Key features of State Manager include the following:
+ 

**State Manager associations**  
A State Manager *association* is a configuration that you assign to your AWS resources. The configuration defines the state that you want to maintain on your resources. For example, an association can specify that antivirus software must be installed and running on a managed node, or that certain ports must be closed.

  An association specifies a schedule for when to apply the configuration and the targets for the association. For example, an association for antivirus software might run once a day on all managed nodes in an AWS account. If the software isn't installed on a node, then the association could instruct State Manager to install it. If the software is installed, but the service isn't running, then the association could instruct State Manager to start the service.
+ 

**Flexible scheduling options**  
State Manager offers the following options for scheduling when an association runs:
  + **Immediate or delayed processing**

    When you create an association, by default, the system immediately runs it on the specified resources. After the initial run, the association runs in intervals according to the schedule that you defined. 

    You can instruct State Manager not to run an association immediately by using the **Apply association only at the next specified Cron interval** option in the console or the `ApplyOnlyAtCronInterval` parameter from the command line.
  + **Cron and rate expressions**

    When you create an association, you specify a schedule for when State Manager applies the configuration. State Manager supports most standard cron and rate expressions for scheduling when an association runs. State Manager also supports cron expressions that include a day of the week and the number sign (\$1) to designate the *n*th day of a month to run an association and the (L) sign to indicate the last *X* day of the month.
**Note**  
State Manager doesn't currently support specifying months in cron expressions for associations.

    To further control when an association runs, for example if you want to run an association two days after patch Tuesday, you can specify an offset. An *offset* defines how many days to wait after the scheduled day to run an association.

    For information about building cron and rate expressions, see [Reference: Cron and rate expressions for Systems Manager](reference-cron-and-rate-expressions.md).
+ 

**Multiple targeting options**  
An association also specifies the targets for the association. State Manager supports targeting AWS resources by using tags, AWS Resource Groups, individual node IDs, or all managed nodes in the current AWS Region and AWS account.
+ 

**Amazon S3 support**  
Store the command output from association runs in an Amazon S3 bucket of your choice. For more information, see [Working with associations in Systems Manager](state-manager-associations.md).
+ 

**EventBridge support**  
This Systems Manager tool is supported as both an *event* type and a *target* type in Amazon EventBridge rules. For information, see [Monitoring Systems Manager events with Amazon EventBridge](monitoring-eventbridge-events.md) and [Reference: Amazon EventBridge event patterns and types for Systems Manager](reference-eventbridge-events.md).

## Is there a charge to use State Manager?


State Manager is available at no additional charge.

**Topics**
+ [

## How can State Manager benefit my organization?
](#state-manager-benefits)
+ [

## Who should use State Manager?
](#state-manager-who)
+ [

## What are the features of State Manager?
](#state-manager-features)
+ [

## Is there a charge to use State Manager?
](#state-manager-cost)
+ [

# Understanding how State Manager works
](state-manager-about.md)
+ [

# Working with associations in Systems Manager
](state-manager-associations.md)
+ [

# Creating associations that run MOF files
](systems-manager-state-manager-using-mof-file.md)
+ [

# Creating associations that run Ansible playbooks
](systems-manager-state-manager-ansible.md)
+ [

# Creating associations that run Chef recipes
](systems-manager-state-manager-chef.md)
+ [

# Walkthrough: Automatically update SSM Agent with the AWS CLI
](state-manager-update-ssm-agent-cli.md)
+ [

# Walkthrough: Automatically update PV drivers on EC2 instances for Windows Server
](state-manager-update-pv-drivers.md)

**More info**  
+ [Combating Configuration Drift Using Amazon EC2 Systems Manager and Windows PowerShell DSC](https://aws.amazon.com/blogs/mt/combating-configuration-drift-using-amazon-ec2-systems-manager-and-windows-powershell-dsc/)
+ [Configure Amazon EC2 Instances in an Auto Scaling Group Using State Manager](https://aws.amazon.com/blogs/mt/configure-amazon-ec2-instances-in-an-auto-scaling-group-using-state-manager/)

# Understanding how State Manager works


State Manager, a tool in AWS Systems Manager, is a secure and scalable service that automates the process of keeping managed nodes in a [hybrid and multicloud](operating-systems-and-machine-types.md#supported-machine-types) infrastructure in a state that you define.

Here's how State Manager works:

**1. Determine the state you want to apply to your AWS resources.**  
Do you want to guarantee that your managed nodes are configured with specific applications, such as antivirus or malware applications? Do you want to automate the process of updating the SSM Agent or other AWS packages such as `AWSPVDriver`? Do you need to guarantee that specific ports are closed or open? To get started with State Manager, determine the state that you want to apply to your AWS resources. The state that you want to apply determines which SSM document you use to create a State Manager association.  
A State Manager *association* is a configuration that you assign to your AWS resources. The configuration defines the state that you want to maintain on your resources. For example, an association can specify that antivirus software must be installed and running on a managed node, or that certain ports must be closed.  
An association specifies a schedule for when to apply the configuration and the targets for the association. For example, an association for antivirus software might run once a day on all managed nodes in an AWS account. If the software isn't installed on a node, then the association could instruct State Manager to install it. If the software is installed, but the service isn't running, then the association could instruct State Manager to start the service.

**2. Determine if a preconfigured SSM document can help you create the desired state on your AWS resources.**  
Systems Manager includes dozens of preconfigured SSM documents that you can use to create an association. Preconfigured documents are ready to perform common tasks like installing applications, configuring Amazon CloudWatch, running AWS Systems Manager automations, running PowerShell and Shell scripts, and joining managed nodes to a directory service domain for Active Directory.  
You can view all SSM documents in the [Systems Manager console](https://console.aws.amazon.com/systems-manager/documents). Choose the name of a document to learn more about each one. Here are two examples: [https://console.aws.amazon.com/systems-manager/documents/AWS-ConfigureAWSPackage/description](https://console.aws.amazon.com/systems-manager/documents/AWS-ConfigureAWSPackage/description) and [https://console.aws.amazon.com/systems-manager/documents/AWS-InstallApplication/description](https://console.aws.amazon.com/systems-manager/documents/AWS-InstallApplication/description).

**3. Create an association.**  
You can create an association by using the Systems Manager console, the AWS Command Line Interface (AWS CLI), AWS Tools for Windows PowerShell (Tools for Windows PowerShell), or the Systems Manager API. When you create an association, you specify the following information:  
+ A name for the association.
+ The parameters for the SSM document (for example, the path to the application to install or the script to run on the nodes).
+ Targets for the association. You can target managed nodes by specifying tags, by choosing individual node IDs, or by choosing a group in AWS Resource Groups. You can also target *all* managed nodes in the current AWS Region and AWS account. If your targets include more than 1,000 nodes, the system uses an hourly throttling mechanism. This means you might see inaccuracies in your status aggregation count since the aggregation process runs hourly and only when the execution status for a node changes.
+ A role used by association to take actions on your behalf. State Manager will assume this role and call required APIs when dispatching configurations to nodes. For information about setting up the custom-provided role, see [Setup roles for `AssociationDispatchAssumeRole`](#setup-assume-role). If no role is provided, [service-linked role for Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/using-service-linked-roles.html) will be used. 
**Note**  
It is recommended that you define a custom IAM role so that you have full control of the permissions that State Manager has when taking actions on your behalf.  
Service-linked role support in State Manager is being phased out. Associations relying on service-linked role may require updates in the future to continue functioning properly.  
For information about managing the usage of custom-provided role, see [Manage usage of AssociationDispatchAssumeRole with `ssm:AssociationDispatchAssumeRole`](#context-key-assume-role).
+ A schedule for when or how often to apply the state. You can specify a cron or rate expression. For more information about creating schedules by using cron and rate expressions, see [Cron and rate expressions for associations](reference-cron-and-rate-expressions.md#reference-cron-and-rate-expressions-association).
**Note**  
State Manager doesn't currently support specifying months in cron expressions for associations.
When you run the command to create the association, Systems Manager binds the information you specified (schedule, targets, SSM document, and parameters) to the targeted resources. The status of the association initially shows "Pending" as the system attempts to reach all targets and *immediately* apply the state specified in the association.   
If you create a new association that is scheduled to run while an earlier association is still running, the earlier association times out and the new association runs.
Systems Manager reports the status of the request to create associations on the resources. You can view status details in the console or (for managed nodes) by using the [DescribeInstanceAssociationsStatus](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstanceAssociationsStatus.html) API operation. If you choose to write the output of the command to Amazon Simple Storage Service (Amazon S3) when you create an association, you can also view the output in the Amazon S3 bucket you specified.  
For more information, see [Working with associations in Systems Manager](state-manager-associations.md).   
API operations that are initiated by the SSM document during an association run are not logged in AWS CloudTrail.

**4. Monitor and update.**  
After you create the association, State Manager reapplies the configuration according to the schedule that you defined in the association. You can view the status of your associations on the [State Manager page](https://console.aws.amazon.com/systems-manager/state-manager) in the console or by directly calling the association ID generated by Systems Manager when you created the association. For more information, see [Viewing association histories](state-manager-associations-history.md). You can update your association documents and reapply them as necessary. You can also create multiple versions of an association. For more information, see [Editing and creating a new version of an association](state-manager-associations-edit.md).

## Understanding when associations are applied to resources


When you create an association, you specify an SSM document that defines the configuration, a list of target resources, and a schedule for applying the configuration. By default, State Manager runs the association when you create it and then according to your schedule. State Manager also attempts to run the association in the following situations: 
+ **Association edit** – State Manager runs the association after a user edits and saves their changes to any of the following association fields: `DOCUMENT_VERSION`, `PARAMETERS`, `SCHEDULE_EXPRESSION`, `OUTPUT_S3_LOCATION`.
+ **Document edit** – State Manager runs the association after a user edits and saves changes to the SSM document that defines the association's configuration state. Specifically, the association runs after the following edits to the document:
  + A user specifies a new `$DEFAULT` document version and the association was created using the `$DEFAULT` version. 
  + A user updates a document and the association was created using the `$LATEST` version.
  + A user deletes the document that was specified when the association was created.
+ **Manual start** – State Manager runs the association when initiated by the user from either the Systems Manager console or programmatically.
+ **Target changes** – State Manager runs the association after any of the following activity occurs on a target node:
  + A managed node comes online for the first time.
  + A managed node comes online after missing a scheduled association run.
  + A managed node comes online after being stopped for more than 30 days.

     
**Note**  
State Manager doesn't monitor documents or packages used in associations across AWS accounts. If you update a document or package in one account, the update won't cause the association to run in the second account. You must manually run the association in the second account.

**Preventing associations from running when a target changes**  
In some cases, you might not want an association to run when a target that consists of managed nodes changes, but only according to its specified schedule.
**Note**  
Running an Automation runbook incurs a cost. If an association with an Automation runbook targets all instances in your account and you regularly launch a large number of instances, the runbook is run on each of the instances when it launches. This can lead to elevated automation charges.

  To prevent an association from running when the targets for that association change, select the **Apply association only at the next specified cron interval check box**. This check box is located in the **Specify schedule** area of the **Create association** and **Edit association** pages.

  This option applies to associations that incorporate either an Automation runbook or an SSM document.

## About target updates with Automation runbooks


In order for associations that are created with Automation runbooks to be applied when new target nodes are detected, the following conditions must be true:
+ The association must have been created by a [Quick Setup](systems-manager-quick-setup.md) configuration. Quick Setup is a tool in AWS Systems Manager. Associations created by other processes are not currently supported.
+ The Automation runbook must explicitly target the resource type `AWS::EC2::Instance` or `AWS::SSM::ManagedInstance`. 
+ The association must specify both parameters and targets.

  In the console, the **Parameter** and **Targets** fields are displayed when you choose a rate control execution.  
![\[Parameter and target options are presented in the console for rate control executions\]](http://docs.aws.amazon.com/systems-manager/latest/userguide/images/sm_Rate_control_execution_options.png)

  When you use the [https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociation.html](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociation.html), [https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociationBatch.html](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociationBatch.html), or [https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateAssociation.html](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateAssociation.html) API actions, you can specify these values using the `AutomationTargetParameterName` and `Targets` inputs. In each of these API actions, you can also prevent the association from running each time a target changes by setting the `ApplyOnlyAtCronInterval` parameter to `true`. 

  For information about using the console to control when associations run, including details for avoiding unexpectedly high costs for Automation executions, see [Understanding when associations are applied to resources](#state-manager-about-scheduling). 

## Setup roles for `AssociationDispatchAssumeRole`


To setup custom dispatch assume roles that State Manager assumes to perform actions on your behalf, the roles should trust `ssm.amazonaws.com` and have the required permission to call `ssm:SendCommand` or `ssm:StartAutomationExecution` based on association use cases. 

Sample trust policy: 

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

## Manage usage of AssociationDispatchAssumeRole with `ssm:AssociationDispatchAssumeRole`


To manage the usage of custom dispatch assume roles that State Manager assumes to perform actions on your behalf, use the `ssm:AssociationDispatchAssumeRole` condition key. This condition controls whether associations can be created or updated without specifying a custom dispatch assume role. 

In the following sample policy, the `"Allow"` statement grants permissions to association create and update APIs only when the `AssociationDispatchAssumeRole` parameter is specified. Without this parameter in API requests, the policy does not grant permission to create or update associations: 

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssm:CreateAssociation",
                "ssm:UpdateAssociation",
                "ssm:CreateAssociationBatch"
            ],
            "Resource": "*",
            "Condition": {
                "StringLike": {
                    "ssm:AssociationDispatchAssumeRole": "*"
                }
            }
        }
    ]
}
```

# Working with associations in Systems Manager
Working with associations

This section describes how to create and manage State Manager associations by using the AWS Systems Manager console, the AWS Command Line Interface (AWS CLI), and AWS Tools for PowerShell. 

**Topics**
+ [

# Understanding targets and rate controls in State Manager associations
](systems-manager-state-manager-targets-and-rate-controls.md)
+ [

# Creating associations
](state-manager-associations-creating.md)
+ [

# Editing and creating a new version of an association
](state-manager-associations-edit.md)
+ [

# Deleting associations
](systems-manager-state-manager-delete-association.md)
+ [

# Running Auto Scaling groups with associations
](systems-manager-state-manager-asg.md)
+ [

# Viewing association histories
](state-manager-associations-history.md)
+ [

# Working with associations using IAM
](systems-manager-state-manager-iam.md)

# Understanding targets and rate controls in State Manager associations
Understanding targets and rate controls

This topic describes State Manager features that help you deploy an association to dozens or hundreds of nodes while controlling the number of nodes that run the association at the scheduled time. State Manager is a tool in AWS Systems Manager.

## Using targets


When you create a State Manager association, you choose which nodes to configure with the association in the **Targets** section of the Systems Manager console, as shown here.

![\[Different options for targeting nodes when creating a State Manager association\]](http://docs.aws.amazon.com/systems-manager/latest/userguide/images/state-manager-targets.png)


If you create an association by using a command line tool such as the AWS Command Line Interface (AWS CLI), then you specify the `targets` parameter. Targeting nodes allows you to configure tens, hundreds, or thousands of nodes with an association without having to specify or choose individual node IDs. 

Each managed node can be targeted by a maximum of 20 associations.

State Manager includes the following target options when creating an association.

**Specify tags**  
Use this option to specify a tag key and (optionally) a tag value assigned to your nodes. When you run the request, the system locates and attempts to create the association on all nodes that match the specified tag key and value. If you specified multiple tag values, the association targets any node with at least one of those tag values. When the system initially creates the association, it runs the association. After this initial run, the system runs the association according to the schedule you specified.

If you create new nodes and assign the specified tag key and value to those nodes, the system automatically applies the association, runs it immediately, and then runs it according to the schedule. This applies when the association uses a Command or Policy document and doesn't apply if the association uses an Automation runbook. If you delete the specified tags from a node, the system no longer runs the association on those nodes.

**Note**  
If you use Automation runbooks with State Manager and the tagging limitation prevents you from achieving a specific goal, consider using Automation runbooks with Amazon EventBridge. For more information, see [Run automations based on EventBridge events](running-automations-event-bridge.md). For more information about using runbooks with State Manager, see [Scheduling automations with State Manager associations](scheduling-automations-state-manager-associations.md). 

As a best practice, we recommend using tags when creating associations that use a Command or Policy document. We also recommend using tags when creating associations to run Auto Scaling groups. For more information, see [Running Auto Scaling groups with associations](systems-manager-state-manager-asg.md).

**Note**  
Note the following information.  
When creating an association in the AWS Management Console that targets nodes by using tags, you can specify only one tag key for an automation association and five tag keys for a command association. *All* tag keys specified in the association must be currently assigned to the node. If they aren't, State Manager fails to target the node for an association.
If you want to use the console *and* you want to target your nodes by using more than one tag key for an automation association and five tag keys for a command association, assign the tag keys to an AWS Resource Groups group and add the nodes to it. You can then choose the **Resource Group** option in the **Targets** list when you create the State Manager association.
You can specify a maximum of five tag keys by using the AWS CLI. If you use the AWS CLI, *all* tag keys specified in the `create-association` command must be currently assigned to the node. If they aren't, State Manager fails to target the node for an association.

**Choose nodes manually**  
Use this option to manually select the nodes where you want to create the association. The **Instances** pane displays all Systems Manager managed nodes in the current AWS account and AWS Region. You can manually select as many nodes as you want. When the system initially creates the association, it runs the association. After this initial run, the system runs the association according to the schedule you specified.

**Note**  
If a managed node you expect to see isn't listed, see [Troubleshooting managed node availability](fleet-manager-troubleshooting-managed-nodes.md) for troubleshooting tips.

**Choose a resource group**  
Use this option to create an association on all nodes returned by an AWS Resource Groups tag-based or AWS CloudFormation stack-based query. 

Below are details about targeting resource groups for an association.
+ If you add new nodes to a group, the system automatically maps the nodes to the association that targets the resource group. The system applies the association to the nodes when it discovers the change. After this initial run, the system runs the association according to the schedule you specified.
+ If you create an association that targets a resource group and the `AWS::SSM::ManagedInstance` resource type was specified for that group, then by design, the association runs on both Amazon Elastic Compute Cloud (Amazon EC2) instances and non-EC2 nodes in a [hybrid and multicloud](operating-systems-and-machine-types.md#supported-machine-types) environment.

  The converse is also true. If you create an association that targets a resource group and the `AWS::EC2::Instance` resource type was specified for that group, then by design, the association runs on both non-EC2 nodes in a [hybrid and multicloud](operating-systems-and-machine-types.md#supported-machine-types) environment and (Amazon EC2) instances.
+ If you create an association that targets a resource group, the resource group must not have more than five tag keys assigned to it or more than five values specified for any one tag key. If either of these conditions applies to the tags and keys assigned to your resource group, the association fails to run and returns an `InvalidTarget` error. 
+ If you create an association that targets a resource group using tags, you can't choose the **(empty value)** option for the tag value.
+ If you delete a resource group, all instances in that group no longer run the association. As a best practice, delete associations targeting the group.
+ At most you can target a single resource group for an association. Multiple or nested groups aren't supported.
+ After you create an association, State Manager periodically updates the association with information about resources in the Resource Group. If you add new resources to a Resource Group, the schedule for when the system applies the association to the new resources depends on several factors. You can determine the status of the association in the State Manager page of the Systems Manager console.

**Warning**  
An AWS Identity and Access Management (IAM) user, group, or role with permission to create an association that targets a resource group of Amazon EC2 instances automatically has root-level control of all instances in the group. Only trusted administrators should be permitted to create associations. 

For more information about Resource Groups, see [What Is AWS Resource Groups?](https://docs.aws.amazon.com/ARG/latest/userguide/) in the *AWS Resource Groups User Guide*.

**Choose all nodes**  
Use this option to target all nodes in the current AWS account and AWS Region. When you run the request, the system locates and attempts to create the association on all nodes in the current AWS account and AWS Region. When the system initially creates the association, it runs the association. After this initial run, the system runs the association according to the schedule you specified. If you create new nodes, the system automatically applies the association, runs it immediately, and then runs it according to the schedule.

## Using rate controls


You can control the execution of an association on your nodes by specifying a concurrency value and an error threshold. The concurrency value specifies how many nodes can run the association simultaneously. An error threshold specifies how many association executions can fail before Systems Manager sends a command to each node configured with that association to stop running the association. The command stops the association from running until the next scheduled execution. The concurrency and error threshold features are collectively called *rate controls*. 

![\[Different rate control options when creating a State Manager association\]](http://docs.aws.amazon.com/systems-manager/latest/userguide/images/state-manager-rate-controls.png)


**Concurrency**  
Concurrency helps to limit the impact on your nodes by allowing you to specify that only a certain number of nodes can process an association at one time. You can specify either an absolute number of nodes, for example 20, or a percentage of the target set of nodes, for example 10%.

State Manager concurrency has the following restrictions and limitations:
+ If you choose to create an association by using targets, but you don't specify a concurrency value, then State Manager automatically enforces a maximum concurrency of 50 nodes.
+ If new nodes that match the target criteria come online while an association that uses concurrency is running, then the new nodes run the association if the concurrency value isn't exceeded. If the concurrency value is exceeded, then the nodes are ignored during the current association execution interval. The nodes run the association during the next scheduled interval while conforming to the concurrency requirements.
+ If you update an association that uses concurrency, and one or more nodes are processing that association when it's updated, then any node that is running the association is allowed to complete. Those associations that haven't started are stopped. After running associations complete, all target nodes immediately run the association again because it was updated. When the association runs again, the concurrency value is enforced. 

**Error thresholds**  
An error threshold specifies how many association executions are allowed to fail before Systems Manager sends a command to each node configured with that association. The command stops the association from running until the next scheduled execution. You can specify either an absolute number of errors, for example 10, or a percentage of the target set, for example 10%.

If you specify an absolute number of three errors, for example, State Manager sends the stop command when the fourth error is returned. If you specify 0, then State Manager sends the stop command after the first error result is returned.

If you specify an error threshold of 10% for 50 associations, then State Manager sends the stop command when the sixth error is returned. Associations that are already running when an error threshold is reached are allowed to complete, but some of these associations might fail. To ensure that there aren't more errors than the number specified for the error threshold, set the **Concurrency** value to 1 so that associations proceed one at a time. 

State Manager error thresholds have the following restrictions and limitations:
+ Error thresholds are enforced for the current interval.
+ Information about each error, including step-level details, is recorded in the association history.
+ If you choose to create an association by using targets, but you don't specify an error threshold, then State Manager automatically enforces a threshold of 100% failures.

# Creating associations


State Manager, a tool in AWS Systems Manager, helps you keep your AWS resources in a state that you define and reduce configuration drift. To do this, State Manager uses associations. An *association* is a configuration that you assign to your AWS resources. The configuration defines the state that you want to maintain on your resources. For example, an association can specify that antivirus software must be installed and running on a managed node, or that certain ports must be closed.

An association specifies a schedule for when to apply the configuration and the targets for the association. For example, an association for antivirus software might run once a day on all managed nodes in an AWS account. If the software isn't installed on a node, then the association could instruct State Manager to install it. If the software is installed, but the service isn't running, then the association could instruct State Manager to start the service.

**Warning**  
When you create an association, you can choose an AWS resource group of managed nodes as the target for the association. If an AWS Identity and Access Management (IAM) user, group, or role has permission to create an association that targets a resource group of managed nodes, then that user, group, or role automatically has root-level control of all nodes in the group. Permit only trusted administrators to create associations. 

**Association targets and rate controls**  
An association specifies which managed nodes, or targets, should receive the association. State Manager includes several features to help you target your managed nodes and control how the association is deployed to those targets. For more information about targets and rate controls, see [Understanding targets and rate controls in State Manager associations](systems-manager-state-manager-targets-and-rate-controls.md).

**Tagging associations**  
You can assign tags to an association when you create it by using a command line tool such as the AWS CLI or AWS Tools for PowerShell. Adding tags to an association by using the Systems Manager console isn't supported. 

**Running associations**  
By default, State Manager runs an association immediately after you create it, and then according to the schedule that you've defined. 

The system also runs associations according to the following rules:
+ State Manager attempts to run the association on all specified or targeted nodes during an interval.
+ If an association doesn't run during an interval (because, for example, a concurrency value limited the number of nodes that could process the association at one time), then State Manager attempts to run the association during the next interval.
+ State Manager runs the association after changes to the association's configuration, target nodes, documents, or parameters. For more information, see [Understanding when associations are applied to resources](state-manager-about.md#state-manager-about-scheduling)
+ State Manager records history for all skipped intervals. You can view the history on the **Execution History** tab.

## Scheduling associations


You can schedule associations to run at basic intervals such as *every 10 hours*, or you can create more advanced schedules using custom cron and rate expressions. You can also prevent associations from running when you first create them. 

**Using cron and rate expressions to schedule association runs**  
In addition to standard cron and rate expressions, State Manager also supports cron expressions that include a day of the week and the number sign (\$1) to designate the *n*th day of a month to run an association. Here is an example that runs a cron schedule on the third Tuesday of every month at 23:30 UTC:

`cron(30 23 ? * TUE#3 *)`

Here is an example that runs on the second Thursday of every month at midnight UTC:

`cron(0 0 ? * THU#2 *)`

State Manager also supports the (L) sign to indicate the last *X* day of the month. Here is an example that runs a cron schedule on the last Tuesday of every month at midnight UTC:

`cron(0 0 ? * 3L *)`

To further control when an association runs, for example if you want to run an association two days after patch Tuesday, you can specify an offset. An *offset* defines how many days to wait after the scheduled day to run an association. For example, if you specified a cron schedule of `cron(0 0 ? * THU#2 *)`, you could specify the number 3 in the **Schedule offset** field to run the association each Sunday after the second Thursday of the month.

**Note**  
To use offsets, you must either select **Apply association only at the next specified Cron interval** in the console or specify the `ApplyOnlyAtCronInterval` parameter from the command line. When either of these options are activated, State Manager doesn't run the association immediately after you create it.

For more information about cron and rate expressions, see [Reference: Cron and rate expressions for Systems Manager](reference-cron-and-rate-expressions.md).

## Create an association (console)


The following procedure describes how to use the Systems Manager console to create a State Manager association.

**Note**  
Note the following information.  
This procedure describes how to create an association that uses either a `Command` or a `Policy` document to target managed nodes. For information about creating an association that uses an Automation runbook to target nodes or other types of AWS resources, see [Scheduling automations with State Manager associations](scheduling-automations-state-manager-associations.md).
When creating an association, you can specify a maximum of five tag keys by using the AWS Management Console. *All* tag keys specified for the association must be currently assigned to the node. If they aren't, State Manager fails to target the node for the association.

**To create a State Manager association**

1. Open the AWS Systems Manager console at [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/).

1. In the navigation pane, choose **State Manager**.

1. Choose **Create association**.

1. In the **Name** field, specify a name.

1. In the **Document** list, choose the option next to a document name. Note the document type. This procedure applies to `Command` and `Policy` documents. For information about creating an association that uses an Automation runbook, see [Scheduling automations with State Manager associations](scheduling-automations-state-manager-associations.md).
**Important**  
State Manager doesn't support running associations that use a new version of a document if that document is shared from another account. State Manager always runs the `default` version of a document if shared from another account, even though the Systems Manager console shows that a new version was processed. If you want to run an association using a new version of a document shared from another account, you must set the document version to `default`.

1. For **Parameters**, specify the required input parameters.

1. (Optional) For **Association Dispatch Assume Role**, select a role from the drop-down. State Manager will take actions using this role on your behalf. For information about setting up the custom-provided role, see [Setup roles for `AssociationDispatchAssumeRole`](state-manager-about.md#setup-assume-role) 
**Note**  
It is recommended that you define a custom IAM role so that you have full control of the permissions that State Manager has when taking actions on your behalf.  
Service-linked role support in State Manager is being phased out. Associations relying on service-linked role may require updates in the future to continue functioning properly.  
For information about managing the usage of custom-provided role, see [Manage usage of AssociationDispatchAssumeRole with `ssm:AssociationDispatchAssumeRole`](state-manager-about.md#context-key-assume-role).

1. (Optional) Choose a CloudWatch alarm to apply to your association for monitoring. 
**Note**  
Note the following information about this step.  
The alarms list displays a maximum of 100 alarms. If you don't see your alarm in the list, use the AWS Command Line Interface to create the association. For more information, see [Create an association (command line)](#create-state-manager-association-commandline).
To attach a CloudWatch alarm to your command, the IAM principal that creates the association must have permission for the `iam:createServiceLinkedRole` action. For more information about CloudWatch alarms, see [Using Amazon CloudWatch alarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html).
If your alarm activates, any pending command invocations or automations do not run.

1. For **Targets**, choose an option. For information about using targets, see [Understanding targets and rate controls in State Manager associations](systems-manager-state-manager-targets-and-rate-controls.md).
**Note**  
In order for associations that are created with Automation runbooks to be applied when new target nodes are detected, certain conditions must be met. For information, see [About target updates with Automation runbooks](state-manager-about.md#runbook-target-updates).

1. In the **Specify schedule** section, choose either **On Schedule** or **No schedule**. If you choose **On Schedule**, use the buttons provided to create a cron or rate schedule for the association. 

   If you don't want the association to run immediately after you create it, choose **Apply association only at the next specified Cron interval**.

1. (Optional) In the **Schedule offset** field, specify a number between 1 and 6. 

1. In the **Advanced options** section use **Compliance severity** to choose a severity level for the association and use **Change Calendars** to choose a change calendar for the association.

   Compliance reporting indicates whether the association state is compliant or noncompliant, along with the severity level you indicate here. For more information, see [About State Manager association compliance](compliance-about.md#compliance-about-association).

   The change calendar determines when the association runs. If the calendar is closed, the association isn't applied. If the calendar is open, the association runs accordingly. For more information, see [AWS Systems Manager Change Calendar](systems-manager-change-calendar.md).

1. In the **Rate control** section, choose options to control how the association runs on multiple nodes. For more information about using rate controls, see [Understanding targets and rate controls in State Manager associations](systems-manager-state-manager-targets-and-rate-controls.md).

   In the **Concurrency** section, choose an option: 
   + Choose **targets** to enter an absolute number of targets that can run the association simultaneously.
   + Choose **percentage** to enter a percentage of the target set that can run the association simultaneously.

   In the **Error threshold** section, choose an option:
   + Choose **errors** to enter an absolute number of errors that are allowed before State Manager stops running associations on additional targets.
   + Choose **percentage** to enter a percentage of errors that are allowed before State Manager stops running associations on additional targets.

1. (Optional) For **Output options**, to save the command output to a file, select the **Enable writing output to S3** box. Enter the bucket and prefix (folder) names in the boxes.
**Note**  
The S3 permissions that grant the ability to write the data to an S3 bucket are those of the instance profile assigned to the managed node, not those of the IAM user performing this task. For more information, see [Configure instance permissions required for Systems Manager](setup-instance-permissions.md) or [Create an IAM service role for a hybrid environment](hybrid-multicloud-service-role.md). In addition, if the specified S3 bucket is in a different AWS account, verify that the instance profile or IAM service role associated with the managed node has the necessary permissions to write to that bucket.

   Following are the minimal permissions required to turn on Amazon S3 output for an association. You can further restrict access by attaching IAM policies to users or roles within an account. At minimum, an Amazon EC2 instance profile should have an IAM role with the `AmazonSSMManagedInstanceCore` managed policy and the following inline policy. 

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "s3:PutObject",
                   "s3:GetObject",
                   "s3:PutObjectAcl"
               ],
               "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*"
           }
       ]
   }
   ```

------

   For minimal permissions, the Amazon S3 bucket you export to must have the default settings defined by the Amazon S3 console. For more information about creating Amazon S3 buckets, see [Creating a bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html) in the *Amazon S3 User Guide*. 
**Note**  
API operations that are initiated by the SSM document during an association run are not logged in AWS CloudTrail.

1. Choose **Create Association**.

**Note**  
If you delete the association you created, the association no longer runs on any targets of that association.

## Create an association (command line)


The following procedure describes how to use the AWS CLI (on Linux or Windows Server) or Tools for PowerShell to create a State Manager association. This section includes several examples that show how to use targets and rate controls. Targets and rate controls allow you to assign an association to dozens or hundreds of nodes while controlling the execution of those associations. For more information about targets and rate controls, see [Understanding targets and rate controls in State Manager associations](systems-manager-state-manager-targets-and-rate-controls.md).

**Important**  
This procedure describes how to create an association that uses either a `Command` or a `Policy` document to target managed nodes. For information about creating an association that uses an Automation runbook to target nodes or other types of AWS resources, see [Scheduling automations with State Manager associations](scheduling-automations-state-manager-associations.md).

**Before you begin**  
The `targets` parameter is an array of search criteria that targets nodes using a `Key`,`Value` combination that you specify. If you plan to create an association on dozens or hundreds of node by using the `targets` parameter, review the following targeting options before you begin the procedure.

Target specific nodes by specifying IDs

```
--targets Key=InstanceIds,Values=instance-id-1,instance-id-2,instance-id-3
```

```
--targets Key=InstanceIds,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE,i-07782c72faEXAMPLE
```

Target instances by using tags

```
--targets Key=tag:tag-key,Values=tag-value-1,tag-value-2,tag-value-3
```

```
--targets Key=tag:Environment,Values=Development,Test,Pre-production
```

Target nodes by using AWS Resource Groups

```
--targets Key=resource-groups:Name,Values=resource-group-name
```

```
--targets Key=resource-groups:Name,Values=WindowsInstancesGroup
```

Target all instances in the current AWS account and AWS Region

```
--targets Key=InstanceIds,Values=*
```

**Note**  
Note the following information.  
State Manager doesn't support running associations that use a new version of a document if that document is shared from another account. State Manager always runs the `default` version of a document if shared from another account, even though the Systems Manager console shows that a new version was processed. If you want to run an association using a new version of a document shared form another account, you must set the document version to `default`.
State Manager doesn't support `IncludeChildOrganizationUnits`, `ExcludeAccounts`, `TargetsMaxErrors`, `TargetsMaxConcurrency`, `Targets`, `TargetLocationAlarmConfiguration` parameters for [TargetLocation](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_TargetLocation.html).
You can specify a maximum of five tag keys by using the AWS CLI. If you use the AWS CLI, *all* tag keys specified in the `create-association` command must be currently assigned to the node. If they aren't, State Manager fails to target the node for an association.
When you create an association, you specify when the schedule runs. Specify the schedule by using a cron or rate expression. For more information about cron and rate expressions, see [Cron and rate expressions for associations](reference-cron-and-rate-expressions.md#reference-cron-and-rate-expressions-association).
In order for associations that are created with Automation runbooks to be applied when new target nodes are detected, certain conditions must be met. For information, see [About target updates with Automation runbooks](state-manager-about.md#runbook-target-updates).

**To create an association**

1. Install and configure the AWS CLI or the AWS Tools for PowerShell, if you haven't already.

   For information, see [Installing or updating the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) and [Installing the AWS Tools for PowerShell](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html).

1. Use the following format to create a command that creates a State Manager association. Replace each *example resource placeholder* with your own information.

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
       --name document_name \
       --document-version version_of_document_applied \
       --instance-id instances_to_apply_association_on \
       --parameters (if any) \
       --targets target_options \
       --association-dispatch-assume-role arn_of_role_to_be_used_when_dispatching_configurations \
       --schedule-expression "cron_or_rate_expression" \
       --apply-only-at-cron-interval required_parameter_for_schedule_offsets \
       --schedule-offset number_between_1_and_6 \
       --output-location s3_bucket_to_store_output_details \
       --association-name association_name \
       --max-errors a_number_of_errors_or_a_percentage_of_target_set \
       --max-concurrency a_number_of_instances_or_a_percentage_of_target_set \
       --compliance-severity severity_level \
       --calendar-names change_calendar_names \
       --target-locations aws_region_or_account \
       --tags "Key=tag_key,Value=tag_value"
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
       --name document_name ^
       --document-version version_of_document_applied ^
       --instance-id instances_to_apply_association_on ^
       --parameters (if any) ^
       --targets target_options ^
       --association-dispatch-assume-role arn_of_role_to_be_used_when_dispatching_configurations ^
       --schedule-expression "cron_or_rate_expression" ^
       --apply-only-at-cron-interval required_parameter_for_schedule_offsets ^
       --schedule-offset number_between_1_and_6 ^
       --output-location s3_bucket_to_store_output_details ^
       --association-name association_name ^
       --max-errors a_number_of_errors_or_a_percentage_of_target_set ^
       --max-concurrency a_number_of_instances_or_a_percentage_of_target_set ^
       --compliance-severity severity_level ^
       --calendar-names change_calendar_names ^
       --target-locations aws_region_or_account ^
       --tags "Key=tag_key,Value=tag_value"
   ```

------
#### [ PowerShell ]

   ```
   New-SSMAssociation `
       -Name document_name `
       -DocumentVersion version_of_document_applied `
       -InstanceId instances_to_apply_association_on `
       -Parameters (if any) `
       -Target target_options `
       -AssociationDispatchAssumeRole arn_of_role_to_be_used_when_dispatching_configurations `
       -ScheduleExpression "cron_or_rate_expression" `
       -ApplyOnlyAtCronInterval required_parameter_for_schedule_offsets `
       -ScheduleOffSet number_between_1_and_6 `
       -OutputLocation s3_bucket_to_store_output_details `
       -AssociationName association_name `
       -MaxError  a_number_of_errors_or_a_percentage_of_target_set
       -MaxConcurrency a_number_of_instances_or_a_percentage_of_target_set `
       -ComplianceSeverity severity_level `
       -CalendarNames change_calendar_names `
       -TargetLocations aws_region_or_account `
       -Tags "Key=tag_key,Value=tag_value"
   ```

------

   The following example creates an association on nodes tagged with `"Environment,Linux"`. The association uses the `AWS-UpdateSSMAgent` document to update the SSM Agent on the targeted nodes at 2:00 UTC every Sunday morning. This association runs simultaneously on 10 nodes maximum at any given time. Also, this association stops running on more nodes for a particular execution interval if the error count exceeds 5. For compliance reporting, this association is assigned a severity level of Medium.

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
     --association-name Update_SSM_Agent_Linux \
     --targets Key=tag:Environment,Values=Linux \
     --name AWS-UpdateSSMAgent  \
     --association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole \
     --compliance-severity "MEDIUM" \
     --schedule-expression "cron(0 2 ? * SUN *)" \
     --max-errors "5" \
     --max-concurrency "10"
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
     --association-name Update_SSM_Agent_Linux ^
     --targets Key=tag:Environment,Values=Linux ^
     --name AWS-UpdateSSMAgent  ^
     --association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole ^
     --compliance-severity "MEDIUM" ^
     --schedule-expression "cron(0 2 ? * SUN *)" ^
     --max-errors "5" ^
     --max-concurrency "10"
   ```

------
#### [ PowerShell ]

   ```
   New-SSMAssociation `
     -AssociationName Update_SSM_Agent_Linux `
     -Name AWS-UpdateSSMAgent `
     -AssociationDispatchAssumeRole "arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole" `
     -Target @{
         "Key"="tag:Environment"
         "Values"="Linux"
       } `
     -ComplianceSeverity MEDIUM `
     -ScheduleExpression "cron(0 2 ? * SUN *)" `
     -MaxConcurrency 10 `
     -MaxError 5
   ```

------

   The following example targets node IDs by specifying a wildcard value (\$1). This allows Systems Manager to create an association on *all* nodes in the current AWS account and AWS Region. This association runs simultaneously on 10 nodes maximum at any given time. Also, this association stops running on more nodes for a particular execution interval if the error count exceeds 5. For compliance reporting, this association is assigned a severity level of Medium. This association uses a schedule offset, which means it runs two days after the specified cron schedule. It also includes the `ApplyOnlyAtCronInterval` parameter, which is required to use the schedule offset and which means the association won't run immediately after it is created.

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
     --association-name Update_SSM_Agent_Linux \
     --name "AWS-UpdateSSMAgent" \
     --association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole \
     --targets "Key=instanceids,Values=*" \
     --compliance-severity "MEDIUM" \
     --schedule-expression "cron(0 2 ? * SUN#2 *)" \
     --apply-only-at-cron-interval \
     --schedule-offset 2 \
     --max-errors "5" \
     --max-concurrency "10" \
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
     --association-name Update_SSM_Agent_Linux ^
     --name "AWS-UpdateSSMAgent" ^
     --association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole ^
     --targets "Key=instanceids,Values=*" ^
     --compliance-severity "MEDIUM" ^
     --schedule-expression "cron(0 2 ? * SUN#2 *)" ^
     --apply-only-at-cron-interval ^
     --schedule-offset 2 ^
     --max-errors "5" ^
     --max-concurrency "10" ^
     --apply-only-at-cron-interval
   ```

------
#### [ PowerShell ]

   ```
   New-SSMAssociation `
     -AssociationName Update_SSM_Agent_All `
     -Name AWS-UpdateSSMAgent `
     -AssociationDispatchAssumeRole "arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole" `
     -Target @{
         "Key"="InstanceIds"
         "Values"="*"
       } `
     -ScheduleExpression "cron(0 2 ? * SUN#2 *)" `
     -ApplyOnlyAtCronInterval `
     -ScheduleOffset 2 `
     -MaxConcurrency 10 `
     -MaxError 5 `
     -ComplianceSeverity MEDIUM `
     -ApplyOnlyAtCronInterval
   ```

------

   The following example creates an association on nodes in Resource Groups. The group is named "HR-Department". The association uses the `AWS-UpdateSSMAgent` document to update SSM Agent on the targeted nodes at 2:00 UTC every Sunday morning. This association runs simultaneously on 10 nodes maximum at any given time. Also, this association stops running on more nodes for a particular execution interval if the error count exceeds 5. For compliance reporting, this association is assigned a severity level of Medium. This association runs at the specified cron schedule. It doesn't run immediately after the association is created.

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
     --association-name Update_SSM_Agent_Linux \
     --targets Key=resource-groups:Name,Values=HR-Department \
     --name AWS-UpdateSSMAgent  \
     --association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole \
     --compliance-severity "MEDIUM" \
     --schedule-expression "cron(0 2 ? * SUN *)" \
     --max-errors "5" \
     --max-concurrency "10" \
     --apply-only-at-cron-interval
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
     --association-name Update_SSM_Agent_Linux ^
     --targets Key=resource-groups:Name,Values=HR-Department ^
     --name AWS-UpdateSSMAgent  ^
     -association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole ^
     --compliance-severity "MEDIUM" ^
     --schedule-expression "cron(0 2 ? * SUN *)" ^
     --max-errors "5" ^
     --max-concurrency "10" ^
     --apply-only-at-cron-interval
   ```

------
#### [ PowerShell ]

   ```
   New-SSMAssociation `
     -AssociationName Update_SSM_Agent_Linux `
     -Name AWS-UpdateSSMAgent `
     -AssociationDispatchAssumeRole "arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole" `
     -Target @{
         "Key"="resource-groups:Name"
         "Values"="HR-Department"
       } `
     -ScheduleExpression "cron(0 2 ? * SUN *)" `
     -MaxConcurrency 10 `
     -MaxError 5 `
     -ComplianceSeverity MEDIUM `
     -ApplyOnlyAtCronInterval
   ```

------

   The following example creates an association that runs on nodes tagged with a specific node ID. The association uses the SSM Agent document to update SSM Agent on the targeted nodes once when the change calendar is open. The association checks the calendar state when it runs. If the calendar is closed at launch time and the association is only run once, it won't run again because the association run window has passed. If the calendar is open, the association runs accordingly.
**Note**  
If you add new nodes to the tags or resource groups that an association acts on when the change calendar is closed, the association is applied to those nodes once the change calendar opens.

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
     --association-name CalendarAssociation \
     --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" \
     --name AWS-UpdateSSMAgent  \
     --association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole \
     --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" \
     --schedule-expression "rate(1day)"
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
     --association-name CalendarAssociation ^
     --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" ^
     --name AWS-UpdateSSMAgent  ^
     --association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole ^
     --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" ^
     --schedule-expression "rate(1day)"
   ```

------
#### [ PowerShell ]

   ```
   New-SSMAssociation `
     -AssociationName CalendarAssociation `
     -Target @{
         "Key"="tag:instanceids"
         "Values"="i-0cb2b964d3e14fd9f"
       } `
     -Name AWS-UpdateSSMAgent `
     -AssociationDispatchAssumeRole "arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole" `
     -CalendarNames "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" `
     -ScheduleExpression "rate(1day)"
   ```

------

   The following example creates an association that runs on nodes tagged with a specific node ID. The association uses the SSM Agent document to update SSM Agent on the targeted nodes on the targeted nodes at 2:00 AM every Sunday. This association runs only at the specified cron schedule when the change calendar is open. When the association is created, it checks the calendar state. If the calendar is closed, the association isn't applied. When the interval to apply the association starts at 2:00 AM on Sunday, the association checks to see if the calendar is open. If the calendar is open, the association runs accordingly.
**Note**  
If you add new nodes to the tags or resource groups that an association acts on when the change calendar is closed, the association is applied to those nodes once the change calendar opens.

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
     --association-name MultiCalendarAssociation \
     --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" \
     --name AWS-UpdateSSMAgent  \
     --association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole \
     --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2" \
     --schedule-expression "cron(0 2 ? * SUN *)"
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
     --association-name MultiCalendarAssociation ^
     --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" ^
     --name AWS-UpdateSSMAgent  ^
     --association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole ^
     --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2" ^
     --schedule-expression "cron(0 2 ? * SUN *)"
   ```

------
#### [ PowerShell ]

   ```
   New-SSMAssociation `
     -AssociationName MultiCalendarAssociation `
     -Name AWS-UpdateSSMAgent `
     -AssociationDispatchAssumeRole "arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole" `
     -Target @{
         "Key"="tag:instanceids"
         "Values"="i-0cb2b964d3e14fd9f"
       } `
     -CalendarNames "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2" `
     -ScheduleExpression "cron(0 2 ? * SUN *)"
   ```

------

**Note**  
If you delete the association you created, the association no longer runs on any targets of that association. Also, if you specified the `apply-only-at-cron-interval` parameter, you can reset this option. To do so, specify the `no-apply-only-at-cron-interval` parameter when you update the association from the command line. This parameter forces the association to run immediately after updating the association and according to the interval specified.

# Editing and creating a new version of an association
Editing an association

You can edit a State Manager association to specify a new name, schedule, severity level, targets, or other values. For associations based on SSM Command-type documents, you can also choose to write the output of the command to an Amazon Simple Storage Service (Amazon S3) bucket. After you edit an association, State Manager creates a new version. You can view different versions after editing, as described in the following procedures. 

**Note**  
In order for associations that are created with Automation runbooks to be applied when new target nodes are detected, certain conditions must be met. For information, see [About target updates with Automation runbooks](state-manager-about.md#runbook-target-updates).

The following procedures describe how to edit and create a new version of an association using the Systems Manager console, AWS Command Line Interface (AWS CLI), and AWS Tools for PowerShell (Tools for PowerShell). 

**Important**  
State Manager doesn't support running associations that use a new version of a document if that document is shared from another account. State Manager always runs the `default` version of a document if shared from another account, even though the Systems Manager console shows that a new version was processed. If you want to run an association using a new version of a document shared form another account, you must set the document version to `default`.

## Edit an association (console)


The following procedure describes how to use the Systems Manager console to edit and create a new version of an association.

**Note**  
For associations that use SSM Command documents, not Automation runbooks, this procedure requires that you have write access to an existing Amazon S3 bucket. If you haven't used Amazon S3 before, be aware that you will incur charges for using Amazon S3. For information about how to create a bucket, see [Create a Bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingABucket.html).

**To edit a State Manager association**

1. Open the AWS Systems Manager console at [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/).

1. In the navigation pane, choose **State Manager**.

1. Choose an existing association, and then choose **Edit**.

1. Reconfigure the association to meet your current requirements. 

   For information about association options with `Command` and `Policy` documents, see [Creating associations](state-manager-associations-creating.md). For information about association options with Automation runbooks, see [Scheduling automations with State Manager associations](scheduling-automations-state-manager-associations.md).

1. Choose **Save Changes**. 

1. (Optional) To view association information, in the **Associations** page, choose the name of the association you edited, and then choose the **Versions** tab. The system lists each version of the association you created and edited.

1. (Optional) To view output for associations based on SSM `Command` documents, do the following:

   1. Open the Amazon S3 console at [https://console.aws.amazon.com/s3/](https://console.aws.amazon.com/s3/).

   1. Choose the name of the Amazon S3 bucket you specified for storing command output, and then choose the folder named with the ID of the node that ran the association. (If you chose to store output in a folder in the bucket, open it first.)

   1. Drill down several levels, through the `awsrunPowerShell` folder, to the `stdout` file.

   1. Choose **Open** or **Download** to view the host name.

## Edit an association (command line)


The following procedure describes how to use the AWS CLI (on Linux or Windows Server) or AWS Tools for PowerShell to edit and create a new version of an association.

**To edit a State Manager association**

1. Install and configure the AWS CLI or the AWS Tools for PowerShell, if you haven't already.

   For information, see [Installing or updating the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) and [Installing the AWS Tools for PowerShell](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html).

1. Use the following format to create a command to edit and create a new version of an existing State Manager association. Replace each *example resource placeholder* with your own information.
**Important**  
When you call `[https://docs.aws.amazon.com/cli/latest/reference/ssm/desupdatecribe-association.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/desupdatecribe-association.html)`, the system drops all optional parameters from the request and overwrites the association with null values for those parameters. This is by design. You must specify all optional parameters in the call, even if you are not changing the parameters. This includes the `--name` parameter. Before calling this action, we recommend that you call the `[https://docs.aws.amazon.com/cli/latest/reference/ssm/describe-association.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/describe-association.html)` operation and make a note of all optional parameters required for your `update-association` call.

------
#### [ Linux & macOS ]

   ```
   aws ssm update-association \
       --name document_name \
       --document-version version_of_document_applied \
       --instance-id instances_to_apply_association_on \
       --parameters (if any) \
       --targets target_options \
       --association-dispatch-assume-role arn_of_role_to_be_used_when_dispatching_configurations \
       --schedule-expression "cron_or_rate_expression" \
       --schedule-offset "number_between_1_and_6" \
       --output-location s3_bucket_to_store_output_details \
       --association-name association_name \
       --max-errors a_number_of_errors_or_a_percentage_of_target_set \
       --max-concurrency a_number_of_instances_or_a_percentage_of_target_set \
       --compliance-severity severity_level \
       --calendar-names change_calendar_names \
       --target-locations aws_region_or_account
   ```

------
#### [ Windows ]

   ```
   aws ssm update-association ^
       --name document_name ^
       --document-version version_of_document_applied ^
       --instance-id instances_to_apply_association_on ^
       --parameters (if any) ^
       --targets target_options ^
       --association-dispatch-assume-role arn_of_role_to_be_used_when_dispatching_configurations ^
       --schedule-expression "cron_or_rate_expression" ^
       --schedule-offset "number_between_1_and_6" ^
       --output-location s3_bucket_to_store_output_details ^
       --association-name association_name ^
       --max-errors a_number_of_errors_or_a_percentage_of_target_set ^
       --max-concurrency a_number_of_instances_or_a_percentage_of_target_set ^
       --compliance-severity severity_level ^
       --calendar-names change_calendar_names ^
       --target-locations aws_region_or_account
   ```

------
#### [ PowerShell ]

   ```
   Update-SSMAssociation `
       -Name document_name `
       -DocumentVersion version_of_document_applied `
       -InstanceId instances_to_apply_association_on `
       -Parameters (if any) `
       -Target target_options `
       -AssociationDispatchAssumeRole arn_of_role_to_be_used_when_dispatching_configurations `
       -ScheduleExpression "cron_or_rate_expression" `
       -ScheduleOffset "number_between_1_and_6" `
       -OutputLocation s3_bucket_to_store_output_details `
       -AssociationName association_name `
       -MaxError  a_number_of_errors_or_a_percentage_of_target_set
       -MaxConcurrency a_number_of_instances_or_a_percentage_of_target_set `
       -ComplianceSeverity severity_level `
       -CalendarNames change_calendar_names `
       -TargetLocations aws_region_or_account
   ```

------

   The following example updates an existing association to change the name to `TestHostnameAssociation2`. The new association version runs every hour and writes the output of commands to the specified Amazon S3 bucket.

------
#### [ Linux & macOS ]

   ```
   aws ssm update-association \
     --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE \
     --association-name TestHostnameAssociation2 \
     --parameters commands="echo Association" \
     --association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole \
     --output-location S3Location='{OutputS3Region=us-east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' \
     --schedule-expression "cron(0 */1 * * ? *)"
   ```

------
#### [ Windows ]

   ```
   aws ssm update-association ^
     --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE ^
     --association-name TestHostnameAssociation2 ^
     --parameters commands="echo Association" ^
     --association-dispatch-assume-role arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole ^
     --output-location S3Location='{OutputS3Region=us-east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' ^
     --schedule-expression "cron(0 */1 * * ? *)"
   ```

------
#### [ PowerShell ]

   ```
   Update-SSMAssociation `
     -AssociationId b85ccafe-9f02-4812-9b81-01234EXAMPLE `
     -AssociationName TestHostnameAssociation2 `
     -Parameter @{"commands"="echo Association"} `
     -AssociationDispatchAssumeRole "arn:aws:iam::123456789012:role/myAssociationDispatchAssumeRole" `
     -S3Location_OutputS3BucketName amzn-s3-demo-bucket `
     -S3Location_OutputS3KeyPrefix logs `
     -S3Location_OutputS3Region us-east-1 `
     -ScheduleExpression "cron(0 */1 * * ? *)"
   ```

------

   The following example updates an existing association to change the name to `CalendarAssociation`. The new association runs when the calendar is open and writes command output to the specified Amazon S3 bucket. 

------
#### [ Linux & macOS ]

   ```
   aws ssm update-association \
     --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE \
     --association-name CalendarAssociation \
     --parameters commands="echo Association" \
     --output-location S3Location='{OutputS3Region=us-east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' \
     --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar2"
   ```

------
#### [ Windows ]

   ```
   aws ssm update-association ^
     --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE ^
     --association-name CalendarAssociation ^
     --parameters commands="echo Association" ^
     --output-location S3Location='{OutputS3Region=us-east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' ^
     --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar2"
   ```

------
#### [ PowerShell ]

   ```
   Update-SSMAssociation `
     -AssociationId b85ccafe-9f02-4812-9b81-01234EXAMPLE `
     -AssociationName CalendarAssociation `
     -AssociationName OneTimeAssociation `
     -Parameter @{"commands"="echo Association"} `
     -S3Location_OutputS3BucketName amzn-s3-demo-bucket `
     -CalendarNames "arn:aws:ssm:us-east-1:123456789012:document/testCalendar2"
   ```

------

   The following example updates an existing association to change the name to `MultiCalendarAssociation`. The new association runs when the calendars are open and writes command output to the specified Amazon S3 bucket. 

------
#### [ Linux & macOS ]

   ```
   aws ssm update-association \
     --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE \
     --association-name MultiCalendarAssociation \
     --parameters commands="echo Association" \
     --output-location S3Location='{OutputS3Region=us-east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' \
     --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2"
   ```

------
#### [ Windows ]

   ```
   aws ssm update-association ^
     --association-id 8dfe3659-4309-493a-8755-01234EXAMPLE ^
     --association-name MultiCalendarAssociation ^
     --parameters commands="echo Association" ^
     --output-location S3Location='{OutputS3Region=us-east-1,OutputS3BucketName=amzn-s3-demo-bucket,OutputS3KeyPrefix=logs}' ^
     --calendar-names "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2"
   ```

------
#### [ PowerShell ]

   ```
   Update-SSMAssociation `
     -AssociationId b85ccafe-9f02-4812-9b81-01234EXAMPLE `
     -AssociationName MultiCalendarAssociation `
     -Parameter @{"commands"="echo Association"} `
     -S3Location_OutputS3BucketName amzn-s3-demo-bucket `
     -CalendarNames "arn:aws:ssm:us-east-1:123456789012:document/testCalendar1" "arn:aws:ssm:us-east-2:123456789012:document/testCalendar2"
   ```

------

1. To view the new version of the association, run the following command.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-association \
     --association-id b85ccafe-9f02-4812-9b81-01234EXAMPLE
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-association ^
     --association-id b85ccafe-9f02-4812-9b81-01234EXAMPLE
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAssociation `
     -AssociationId b85ccafe-9f02-4812-9b81-01234EXAMPLE | Select-Object *
   ```

------

   The system returns information like the following.

------
#### [ Linux & macOS ]

   ```
   {
       "AssociationDescription": {
           "ScheduleExpression": "cron(0 */1 * * ? *)",
           "OutputLocation": {
               "S3Location": {
                   "OutputS3KeyPrefix": "logs",
                   "OutputS3BucketName": "amzn-s3-demo-bucket",
                   "OutputS3Region": "us-east-1"
               }
           },
           "Name": "AWS-RunPowerShellScript",
           "Parameters": {
               "commands": [
                   "echo Association"
               ]
           },
           "LastExecutionDate": 1559316400.338,
           "Overview": {
               "Status": "Success",
               "DetailedStatus": "Success",
               "AssociationStatusAggregatedCount": {}
           },
           "AssociationId": "b85ccafe-9f02-4812-9b81-01234EXAMPLE",
           "DocumentVersion": "$DEFAULT",
           "LastSuccessfulExecutionDate": 1559316400.338,
           "LastUpdateAssociationDate": 1559316389.753,
           "Date": 1559314038.532,
           "AssociationVersion": "2",
           "AssociationName": "TestHostnameAssociation2",
           "Targets": [
               {
                   "Values": [
                       "Windows"
                   ],
                   "Key": "tag:Environment"
               }
           ]
       }
   }
   ```

------
#### [ Windows ]

   ```
   {
       "AssociationDescription": {
           "ScheduleExpression": "cron(0 */1 * * ? *)",
           "OutputLocation": {
               "S3Location": {
                   "OutputS3KeyPrefix": "logs",
                   "OutputS3BucketName": "amzn-s3-demo-bucket",
                   "OutputS3Region": "us-east-1"
               }
           },
           "Name": "AWS-RunPowerShellScript",
           "Parameters": {
               "commands": [
                   "echo Association"
               ]
           },
           "LastExecutionDate": 1559316400.338,
           "Overview": {
               "Status": "Success",
               "DetailedStatus": "Success",
               "AssociationStatusAggregatedCount": {}
           },
           "AssociationId": "b85ccafe-9f02-4812-9b81-01234EXAMPLE",
           "DocumentVersion": "$DEFAULT",
           "LastSuccessfulExecutionDate": 1559316400.338,
           "LastUpdateAssociationDate": 1559316389.753,
           "Date": 1559314038.532,
           "AssociationVersion": "2",
           "AssociationName": "TestHostnameAssociation2",
           "Targets": [
               {
                   "Values": [
                       "Windows"
                   ],
                   "Key": "tag:Environment"
               }
           ]
       }
   }
   ```

------
#### [ PowerShell ]

   ```
   AssociationId                 : b85ccafe-9f02-4812-9b81-01234EXAMPLE
   AssociationName               : TestHostnameAssociation2
   AssociationVersion            : 2
   AutomationTargetParameterName : 
   ComplianceSeverity            : 
   Date                          : 5/31/2019 2:47:18 PM
   DocumentVersion               : $DEFAULT
   InstanceId                    : 
   LastExecutionDate             : 5/31/2019 3:26:40 PM
   LastSuccessfulExecutionDate   : 5/31/2019 3:26:40 PM
   LastUpdateAssociationDate     : 5/31/2019 3:26:29 PM
   MaxConcurrency                : 
   MaxErrors                     : 
   Name                          : AWS-RunPowerShellScript
   OutputLocation                : Amazon.SimpleSystemsManagement.Model.InstanceAssociationOutputLocation
   Overview                      : Amazon.SimpleSystemsManagement.Model.AssociationOverview
   Parameters                    : {[commands, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
   ScheduleExpression            : cron(0 */1 * * ? *)
   Status                        : 
   Targets                       : {tag:Environment}
   ```

------

# Deleting associations


Use the following procedure to delete an association by using the AWS Systems Manager console.

**To delete an association**

1. Open the AWS Systems Manager console at [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/).

1. In the navigation pane, choose **State Manager**.

1. Select an association and then choose **Delete**.

You can delete multiple associations in a single operation by running an automation from the AWS Systems Manager console. When you select multiple associations for deletion, State Manager launches the automation runbook start page with the association IDs entered as input parameter values. 

**To delete multiple associations in a single operation**

1. Open the AWS Systems Manager console at [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/).

1. In the navigation pane, choose **State Manager**.

1. Select each association that you want to delete and then choose **Delete**.

1. (Optional) In the **Additional input parameters** area, select the Amazon Resource Name (ARN) for the *assume role* that you want the automation to use while running. To create a new assume role, choose **Create**.

1. Choose **Submit**.

# Running Auto Scaling groups with associations


The best practice when using associations to run Auto Scaling groups is to use tag targets. Not using tags might cause you to reach the association limit. 

If all nodes are tagged with the same key and value, you only need one association to run your Auto Scaling group. The following procedure describes how to create such an association.

**To create an association that runs Auto Scaling groups**

1. Ensure all nodes in the Auto Scaling group are tagged with the same key and value. For more instructions on tagging nodes, see [Tagging Auto Scaling groups and instances](https://docs.aws.amazon.com//autoscaling/ec2/userguide/autoscaling-tagging.html) in the *AWS Auto Scaling User Guide*. 

1. Create an association by using the procedure in [Working with associations in Systems Manager](state-manager-associations.md). 

   If you're working in the console, choose **Specify instance tags** in the **Targets** field. For **Instance tags**, enter the **Tag** key and value for your Auto Scaling group.

   If you're using the AWS Command Line Interface (AWS CLI), specify `--targets Key=tag:tag-key,Values=tag-value` where the key and value match what you tagged your nodes with. 

# Viewing association histories


You can view all executions for a specific association ID by using the [DescribeAssociationExecutions](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeAssociationExecutions.html) API operation. Use this operation to see the status, detailed status, results, last execution time, and more information for a State Manager association. State Manager is a tool in AWS Systems Manager. This API operation also includes filters to help you locate associations according to the criteria you specify. For example, you can specify an exact date and time, and use a GREATER\$1THAN filter to view executions processed after the specified date and time.

If, for example, an association execution failed, you can drill down into the details of a specific execution by using the [DescribeAssociationExecutionTargets](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeAssociationExecutionTargets.html) API operation. This operation shows you the resources, such as node IDs, where the association ran and the various association statuses. You can then see which resource or node failed to run an association. With the resource ID you can then view the command execution details to see which step in a command failed.

The examples in this section also include information about how to use the [StartAssociationsOnce](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartAssociationsOnce.html) API operation to run an association once at the time of creation. You can use this API operation when you investigate failed association executions. If you see that an association failed, you can make a change on the resource, and then immediately run the association to see if the change on the resource allows the association to run successfully.

**Note**  
API operations that are initiated by the SSM document during an association run are not logged in AWS CloudTrail.

## Viewing association histories (console)


Use the following procedure to view the execution history for a specific association ID and then view execution details for one or more resources. 

**To view execution history for a specific association ID**

1. Open the AWS Systems Manager console at [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/).

1. Choose **State Manager**.

1. In the **Association id** field, choose an association for which you want to view the history.

1. Choose the **View details** button.

1. Choose the **Execution history** tab.

1. Choose an association for which you want to view resource-level execution details. For example, choose an association that shows a status of **Failed**. You can then view the execution details for the nodes that failed to run the association.

   Use the search box filters to locate the execution for which you want to view details.  
![\[Filtering the list of State Manager association executions.\]](http://docs.aws.amazon.com/systems-manager/latest/userguide/images/sysman-state-executions-filter.png)

1. Choose an execution ID. The **Association execution targets** page opens. This page shows all the resources that ran the association.

1. Choose a resource ID to view specific information about that resource.

   Use the search box filters to locate the resource for which you want to view details.  
![\[Filtering the list of State Manager association executions targets.\]](http://docs.aws.amazon.com/systems-manager/latest/userguide/images/sysman-state-executions-targets-filter.png)

1. If you're investigating an association that failed to run, you can use the **Apply association now** button to run an association once at the time of creation. After you made changes on the resource where the association failed to run, choose the **Association ID** link in the navigation breadcrumb.

1. Choose the **Apply association now** button. After the execution is complete, verify that the association execution succeeded.

## Viewing association histories (command line)


The following procedure describes how to use the AWS Command Line Interface (AWS CLI) (on Linux or Windows Server) or AWS Tools for PowerShell to view the execution history for a specific association ID. Following this, the procedure describes how to view execution details for one or more resources.

**To view execution history for a specific association ID**

1. Install and configure the AWS CLI or the AWS Tools for PowerShell, if you haven't already.

   For information, see [Installing or updating the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) and [Installing the AWS Tools for PowerShell](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html).

1. Run the following command to view a list of executions for a specific association ID.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-association-executions \
     --association-id ID \
     --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN
   ```

**Note**  
This command includes a filter to limit the results to only those executions that occurred after a specific date and time. If you want to view all executions for a specific association ID, remove the `--filters` parameter and ` Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN` value.

------
#### [ Windows ]

   ```
   aws ssm describe-association-executions ^
     --association-id ID ^
     --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN
   ```

**Note**  
This command includes a filter to limit the results to only those executions that occurred after a specific date and time. If you want to view all executions for a specific association ID, remove the `--filters` parameter and ` Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN` value.

------
#### [ PowerShell ]

   ```
   Get-SSMAssociationExecution `
     -AssociationId ID `
     -Filter @{"Key"="CreatedTime";"Value"="2019-06-01T19:15:38.372Z";"Type"="GREATER_THAN"}
   ```

**Note**  
This command includes a filter to limit the results to only those executions that occurred after a specific date and time. If you want to view all executions for a specific association ID, remove the `-Filter` parameter and ` @{"Key"="CreatedTime";"Value"="2019-06-01T19:15:38.372Z";"Type"="GREATER_THAN"}` value.

------

   The system returns information like the following.

------
#### [ Linux & macOS ]

   ```
   {
      "AssociationExecutions":[
         {
            "Status":"Success",
            "DetailedStatus":"Success",
            "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE",
            "ExecutionId":"76a5a04f-caf6-490c-b448-92c02EXAMPLE",
            "CreatedTime":1523986028.219,
            "AssociationVersion":"1"
         },
         {
            "Status":"Success",
            "DetailedStatus":"Success",
            "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE",
            "ExecutionId":"791b72e0-f0da-4021-8b35-f95dfEXAMPLE",
            "CreatedTime":1523984226.074,
            "AssociationVersion":"1"
         },
         {
            "Status":"Success",
            "DetailedStatus":"Success",
            "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE",
            "ExecutionId":"ecec60fa-6bb0-4d26-98c7-140308EXAMPLE",
            "CreatedTime":1523982404.013,
            "AssociationVersion":"1"
         }
      ]
   }
   ```

------
#### [ Windows ]

   ```
   {
      "AssociationExecutions":[
         {
            "Status":"Success",
            "DetailedStatus":"Success",
            "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE",
            "ExecutionId":"76a5a04f-caf6-490c-b448-92c02EXAMPLE",
            "CreatedTime":1523986028.219,
            "AssociationVersion":"1"
         },
         {
            "Status":"Success",
            "DetailedStatus":"Success",
            "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE",
            "ExecutionId":"791b72e0-f0da-4021-8b35-f95dfEXAMPLE",
            "CreatedTime":1523984226.074,
            "AssociationVersion":"1"
         },
         {
            "Status":"Success",
            "DetailedStatus":"Success",
            "AssociationId":"c336d2ab-09de-44ba-8f6a-6136cEXAMPLE",
            "ExecutionId":"ecec60fa-6bb0-4d26-98c7-140308EXAMPLE",
            "CreatedTime":1523982404.013,
            "AssociationVersion":"1"
         }
      ]
   }
   ```

------
#### [ PowerShell ]

   ```
   AssociationId         : c336d2ab-09de-44ba-8f6a-6136cEXAMPLE
   AssociationVersion    : 1
   CreatedTime           : 8/18/2019 2:00:50 AM
   DetailedStatus        : Success
   ExecutionId           : 76a5a04f-caf6-490c-b448-92c02EXAMPLE
   LastExecutionDate     : 1/1/0001 12:00:00 AM
   ResourceCountByStatus : {Success=1}
   Status                : Success
   
   AssociationId         : c336d2ab-09de-44ba-8f6a-6136cEXAMPLE
   AssociationVersion    : 1
   CreatedTime           : 8/11/2019 2:00:54 AM
   DetailedStatus        : Success
   ExecutionId           : 791b72e0-f0da-4021-8b35-f95dfEXAMPLE
   LastExecutionDate     : 1/1/0001 12:00:00 AM
   ResourceCountByStatus : {Success=1}
   Status                : Success
   
   AssociationId         : c336d2ab-09de-44ba-8f6a-6136cEXAMPLE
   AssociationVersion    : 1
   CreatedTime           : 8/4/2019 2:01:00 AM
   DetailedStatus        : Success
   ExecutionId           : ecec60fa-6bb0-4d26-98c7-140308EXAMPLE
   LastExecutionDate     : 1/1/0001 12:00:00 AM
   ResourceCountByStatus : {Success=1}
   Status                : Success
   ```

------

   You can limit the results by using one or more filters. The following example returns all associations that were run before a specific date and time. 

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-association-executions \
     --association-id ID \
     --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=LESS_THAN
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-association-executions ^
     --association-id ID ^
     --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=LESS_THAN
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAssociationExecution `
     -AssociationId 14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE `
     -Filter @{"Key"="CreatedTime";"Value"="2019-06-01T19:15:38.372Z";"Type"="LESS_THAN"}
   ```

------

   The following returns all associations that were *successfully* run after a specific date and time.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-association-executions \
     --association-id ID \
     --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN Key=Status,Value=Success,Type=EQUAL
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-association-executions ^
     --association-id ID ^
     --filters Key=CreatedTime,Value="2018-04-10T19:15:38.372Z",Type=GREATER_THAN Key=Status,Value=Success,Type=EQUAL
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAssociationExecution `
     -AssociationId 14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE `
     -Filter @{
         "Key"="CreatedTime";
         "Value"="2019-06-01T19:15:38.372Z";
         "Type"="GREATER_THAN"
       },
       @{
         "Key"="Status";
         "Value"="Success";
         "Type"="EQUAL"
       }
   ```

------

1. Run the following command to view all targets where the specific execution ran.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-association-execution-targets \
     --association-id ID \
     --execution-id ID
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-association-execution-targets ^
     --association-id ID ^
     --execution-id ID
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAssociationExecutionTarget `
     -AssociationId 14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE `
     -ExecutionId 76a5a04f-caf6-490c-b448-92c02EXAMPLE
   ```

------

   You can limit the results by using one or more filters. The following example returns information about all targets where the specific association failed to run.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-association-execution-targets \
     --association-id ID \
     --execution-id ID \
     --filters Key=Status,Value="Failed"
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-association-execution-targets ^
     --association-id ID ^
     --execution-id ID ^
     --filters Key=Status,Value="Failed"
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAssociationExecutionTarget `
     -AssociationId 14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE `
     -ExecutionId 76a5a04f-caf6-490c-b448-92c02EXAMPLE `
     -Filter @{
         "Key"="Status";
         "Value"="Failed"
       }
   ```

------

   The following example returns information about a specific managed node where an association failed to run.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-association-execution-targets \
     --association-id ID \
     --execution-id ID \
     --filters Key=Status,Value=Failed Key=ResourceId,Value="i-02573cafcfEXAMPLE" Key=ResourceType,Value=ManagedInstance
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-association-execution-targets ^
     --association-id ID ^
     --execution-id ID ^
     --filters Key=Status,Value=Failed Key=ResourceId,Value="i-02573cafcfEXAMPLE" Key=ResourceType,Value=ManagedInstance
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAssociationExecutionTarget `
     -AssociationId 14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE `
     -ExecutionId 76a5a04f-caf6-490c-b448-92c02EXAMPLE `
     -Filter @{
         "Key"="Status";
         "Value"="Success"
       },
       @{
         "Key"="ResourceId";
         "Value"="i-02573cafcfEXAMPLE"
       },
       @{
         "Key"="ResourceType";
         "Value"="ManagedInstance"
       }
   ```

------

1. If you're investigating an association that failed to run, you can use the [StartAssociationsOnce](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartAssociationsOnce.html) API operation to run an association immediately and only one time. After you change the resource where the association failed to run, run the following command to run the association immediately and only one time.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-associations-once \
     --association-id ID
   ```

------
#### [ Windows ]

   ```
   aws ssm start-associations-once ^
     --association-id ID
   ```

------
#### [ PowerShell ]

   ```
   Start-SSMAssociationsOnce `
     -AssociationId ID
   ```

------

# Working with associations using IAM


State Manager, a tool in AWS Systems Manager, uses [targets](systems-manager-state-manager-targets-and-rate-controls.md#systems-manager-state-manager-targets-and-rate-controls-about-targets) to choose which instances you configure your associations with. Originally, associations were created by specifying a document name (`Name`) and instance ID (`InstanceId`). This created an association between a document and an instance or managed node. Associations used to be identified by these parameters. These parameters are now deprecated, but they're still supported. The resources `instance` and `managed-instance` were added as resources to actions with `Name` and `InstanceId`.

AWS Identity and Access Management (IAM) policy enforcement behavior depends on the type of resource specified. Resources for State Manager operations are only enforced based on the passed-in request. State Manager doesn't perform a deep check for the properties of resources in your account. A request is only validated against policy resources if the request parameter contains the specified policy resources. For example, if you specify an instance in the resource block, the policy is enforced if the request uses the `InstanceId` parameter. The `Targets` parameter for each resource in the account isn't checked for that `InstanceId`. 

Following are some cases with confusing behavior:
+  [DescribeAssociation](https://docs.aws.amazon.com//systems-manager/latest/APIReference/API_DescribeActivations.html), [DeleteAssociation](https://docs.aws.amazon.com//systems-manager/latest/APIReference/API_DeleteAssociation.html), and [UpdateAssociation](https://docs.aws.amazon.com//systems-manager/latest/APIReference/API_UpdateAssociation.html) use `instance`, `managed-instance`, and `document` resources to specify the deprecated way of referring to associations. This includes all associations created with the deprecated `InstanceId` parameter.
+ [CreateAssociation](https://docs.aws.amazon.com//systems-manager/latest/APIReference/API_CreateAssociation.html), [CreateAssociationBatch](https://docs.aws.amazon.com//systems-manager/latest/APIReference/API_CreateAssociationBatch.html), and [UpdateAssociation](https://docs.aws.amazon.com//systems-manager/latest/APIReference/API_UpdateAssociation.html) use `instance` and `managed-instance` resources to specify the deprecated way of referring to associations. This includes all associations created with the deprecated `InstanceId` parameter. The `document` resource type is part of the deprecated way of referring to associations and is an actual property of an association. This means you can construct IAM policies with `Allow` or `Deny` permissions for both `Create` and `Update` actions based on document name.

For more information about using IAM policies with Systems Manager, see [Identity and access management for AWS Systems Manager](security-iam.md) or [Actions, resources, and condition keys for AWS Systems Manager](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awssystemsmanager.html) in the *Service Authorization Reference*.

# Creating associations that run MOF files


You can run Managed Object Format (MOF) files to enforce a target state on Windows Server managed nodes with State Manager, a tool in AWS Systems Manager, by using the `AWS-ApplyDSCMofs` SSM document. The `AWS-ApplyDSCMofs` document has two execution modes. With the first mode, you can configure the association to scan and report if the managed nodes are in the desired state defined in the specified MOF files. In the second mode, you can run the MOF files and change the configuration of your nodes based on the resources and their values defined in the MOF files. The `AWS-ApplyDSCMofs` document allows you to download and run MOF configuration files from Amazon Simple Storage Service (Amazon S3), a local share, or from a secure website with an HTTPS domain.

State Manager logs and reports the status of each MOF file execution during each association run. State Manager also reports the output of each MOF file execution as a compliance event which you can view on the [AWS Systems Manager Compliance](https://console.aws.amazon.com/systems-manager/compliance) page.

MOF file execution is built on Windows PowerShell Desired State Configuration (PowerShell DSC). PowerShell DSC is a declarative platform used for configuration, deployment, and management of Windows systems. PowerShell DSC allows administrators to describe, in simple text documents called DSC configurations, how they want a server to be configured. A PowerShell DSC configuration is a specialized PowerShell script that states what to do, but not how to do it. Running the configuration produces a MOF file. The MOF file can be applied to one or more servers to achieve the desired configuration for those servers. PowerShell DSC resources do the actual work of enforcing configuration. For more information, see [Windows PowerShell Desired State Configuration Overview](https://download.microsoft.com/download/4/3/1/43113F44-548B-4DEA-B471-0C2C8578FBF8/Quick_Reference_DSC_WS12R2.pdf).

**Topics**
+ [

## Using Amazon S3 to store artifacts
](#systems-manager-state-manager-using-mof-file-S3-storage)
+ [

## Resolving credentials in MOF files
](#systems-manager-state-manager-using-mof-file-credentials)
+ [

## Using tokens in MOF files
](#systems-manager-state-manager-using-mof-file-tokens)
+ [

## Prerequisites for creating associations that run MOF files
](#systems-manager-state-manager-using-mof-file-prereqs)
+ [

## Creating an association that runs MOF files
](#systems-manager-state-manager-using-mof-file-creating)
+ [

## Troubleshooting issues when creating associations that run MOF files
](#systems-manager-state-manager-using-mof-file-troubleshooting)
+ [

## Viewing DSC resource compliance details
](#systems-manager-state-manager-viewing-mof-file-compliance)

## Using Amazon S3 to store artifacts


If you're using Amazon S3 to store PowerShell modules, MOF files, compliance reports, or status reports, then the AWS Identity and Access Management (IAM) role used by AWS Systems Manager SSM Agent must have `GetObject` and `ListBucket` permissions on the bucket. If you don't provide these permissions, the system returns an *Access Denied* error. Below is important information about storing artifacts in Amazon S3.
+ If the bucket is in a different AWS account, create a bucket resource policy that grants the account (or the IAM role) `GetObject` and `ListBucket` permissions.
+ If you want to use custom DSC resources, you can download these resources from an Amazon S3 bucket. You can also install them automatically from the PowerShell gallery. 
+ If you're using Amazon S3 as a module source, upload the module as a Zip file in the following case-sensitive format: *ModuleName*\$1*ModuleVersion*.zip. For example: MyModule\$11.0.0.zip.
+ All files must be in the bucket root. Folder structures aren't supported.

## Resolving credentials in MOF files


Credentials are resolved by using [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/) or [AWS Systems Manager Parameter Store](systems-manager-parameter-store.md). This allows you to set up automatic credential rotation. This also allows DSC to automatically propagate credentials to your servers without redeploying MOFs.

To use an AWS Secrets Manager secret in a configuration, create a PSCredential object where the Username is the SecretId or SecretARN of the secret containing the credential. You can specify any value for the password. The value is ignored. Following is an example.

```
Configuration MyConfig
{
   $ss = ConvertTo-SecureString -String 'a_string' -AsPlaintext -Force
   $credential = New-Object PSCredential('a_secret_or_ARN', $ss)

    Node localhost
    {
       File file_name
       {
           DestinationPath = 'C:\MyFile.txt'
           SourcePath = '\\FileServer\Share\MyFile.txt'
           Credential = $credential
       }
    }
}
```

Compile your MOF using the PsAllowPlaintextPassword setting in configuration data. This is OK because the credential only contains a label. 

In Secrets Manager, ensure that the node has GetSecretValue access in an IAM Managed Policy, and optionally in the Secret Resource Policy if one exists. To work with DSC, the secret must be in the following format.

```
{ 'Username': 'a_name', 'Password': 'a_password' }
```

The secret can have other properties (for example, properties used for rotation), but it must at least have the username and password properties.

We recommended that you use a multi-user rotation method, where you have two different usernames and passwords, and the rotation AWS Lambda function flips between them. This method allows you to have multiple active accounts while eliminating the risk of locking out a user during rotation.

## Using tokens in MOF files


Tokens give you the ability to modify resource property values *after* the MOF has been compiled. This allows you to reuse common MOF files on multiple servers that require similar configurations.

Token substitution only works for Resource Properties of type `String`. However, if your resource has a nested CIM node property, it also resolves tokens from `String` properties in that CIM node. You can't use token substitution for numerals or arrays.

For example, consider a scenario where you're using the xComputerManagement resource and you want to rename the computer using DSC. Normally you would need a dedicated MOF file for that machine. However, with token support, you can create a single MOF file and apply it to all your nodes. In the `ComputerName` property, instead of hardcoding the computer name into the MOF, you can use an Instance Tag type token. The value is resolved during MOF parsing. See the following example.

```
Configuration MyConfig
{
    xComputer Computer
    {
        ComputerName = '{tag:ComputerName}'
    }
}
```

You then set a tag on either the managed node in the Systems Manager console, or an Amazon Elastic Compute Cloud (Amazon EC2) tag in the Amazon EC2 console. When you run the document, the script substitutes the \$1tag:ComputerName\$1 token for the value of the instance tag.

You can also combine multiple tags into a single property, as shown in the following example.

```
Configuration MyConfig
{
    File MyFile
    {
        DestinationPath = '{env:TMP}\{tag:ComputerName}'
        Type = 'Directory'
    }
}
```

There are five different types of tokens you can use:
+ **tag**: Amazon EC2 or managed node tags.
+ **tagb64**: This is the same as tag, but the system use base64 to decode the value. This allows you to use special characters in tag values.
+ **env**: Resolves Environment variables.
+ **ssm**: Parameter Store values. Only String and Secure String types are supported.
+ **tagssm**: This is the same as tag, but if the tag isn't set on the node, the system tries to resolve the value from a Systems Manager parameter with the same name. This is useful in situations when you want a 'default global value' but you want to be able to override it on a single node (for example, one-box deployments).

Here is a Parameter Store example that uses the `ssm` token type. 

```
File MyFile
{
    DestinationPath = "C:\ProgramData\ConnectionData.txt"
    Content = "{ssm:%servicePath%/ConnectionData}"
}
```

Tokens play an important role in reducing redundant code by making MOF files generic and reusable. If you can avoid server-specific MOF file, then there’s no need for a MOF building service. A MOF building service increases costs, slows provisioning time, and increases the risk of configuration drift between grouped nodes due to differing module versions being installed on the build server when their MOFs were compiled.

## Prerequisites for creating associations that run MOF files


Before you create an association that runs MOF files, verify that your managed nodes have the following prerequisites installed:
+ Windows PowerShell version 5.0 or later. For more information, see [Windows PowerShell System Requirements](https://docs.microsoft.com/en-us/powershell/scripting/install/windows-powershell-system-requirements?view=powershell-6) on Microsoft.com.
+ [AWS Tools for Windows PowerShell](https://aws.amazon.com/powershell/) version 3.3.261.0 or later.
+ SSM Agent version 2.2 or later.

## Creating an association that runs MOF files


**To create an association that runs MOF files**

1. Open the AWS Systems Manager console at [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/).

1. In the navigation pane, choose **State Manager**.

1. Choose **State Manager**, and then choose **Create association**.

1. In the **Name** field, specify a name. This is optional, but recommended. A name can help you understand the purpose of the association when you created it. Spaces aren't allowed in the name.

1. In the **Document** list, choose **`AWS-ApplyDSCMofs`**.

1. In the **Parameters** section, specify your choices for the required and optional input parameters.

   1. **Mofs To Apply**: Specify one or more MOF files to run when this association runs. Use commas to separate a list of MOF files. Systems Manager iterates through the list of MOF files and runs them in the order specified by the comma separated list.
      + An Amazon S3 bucket name. Bucket names must use lowercase letters. Specify this information by using the following format.

        ```
        s3:amzn-s3-demo-bucket:MOF_file_name.mof
        ```

        If you want to specify an AWS Region, then use the following format.

        ```
        s3:bucket_Region:amzn-s3-demo-bucket:MOF_file_name.mof
        ```
      + A secure website. Specify this information by using the following format.

        ```
        https://domain_name/MOF_file_name.mof
        ```

        Here is an example.

        ```
        https://www.example.com/TestMOF.mof
        ```
      + A file system on a local share. Specify this information by using the following format.

        ```
        \server_name\shared_folder_name\MOF_file_name.mof
        ```

        Here is an example.

        ```
        \StateManagerAssociationsBox\MOFs_folder\MyMof.mof
        ```

   1. **Service Path**: (Optional) A service path is either an Amazon S3 bucket prefix where you want to write reports and status information. Or, a service path is a path for Parameter Store parameter-based tags. When resolving parameter-based tags, the system uses \$1ssm:%servicePath%/*parameter\$1name*\$1 to inject the servicePath value into the parameter name. For example, if your service path is "WebServers/Production" then the systems resolves the parameter as: WebServers/Production/*parameter\$1name*. This is useful for when you're running multiple environments in the same account.

   1. **Report Bucket Name**: (Optional) Enter the name of an Amazon S3 bucket where you want to write compliance data. Reports are saved in this bucket in JSON format.
**Note**  
You can prefix the bucket name with a Region where the bucket is located. Here's an example: us-west-2:MyMOFBucket. If you're using a proxy for Amazon S3 endpoints in a specific Region that doesn't include us-east-1, prefix the bucket name with a Region. If the bucket name isn't prefixed, it automatically discovers the bucket Region by using the us-east-1 endpoint.

   1. **Mof Operation Mode**: Choose State Manager behavior when running the **`AWS-ApplyDSCMofs`** association:
      + **Apply**: Correct node configurations that aren't compliant. 
      + **ReportOnly**: Don't correct node configurations, but instead log all compliance data and report nodes that aren't compliant.

   1. **Status Bucket Name**: (Optional) Enter the name of an Amazon S3 bucket where you want to write MOF execution status information. These status reports are singleton summaries of the most recent compliance run of a node. This means that the report is overwritten the next time the association runs MOF files.
**Note**  
You can prefix the bucket name with a Region where the bucket is located. Here's an example: `us-west-2:amzn-s3-demo-bucket`. If you're using a proxy for Amazon S3 endpoints in a specific Region that doesn't include us-east-1, prefix the bucket name with a Region. If the bucket name isn't prefixed, it automatically discovers the bucket Region using the us-east-1 endpoint.

   1. **Module Source Bucket Name**: (Optional) Enter the name of an Amazon S3 bucket that contains PowerShell module files. If you specify **None**, choose **True** for the next option, **Allow PS Gallery Module Source**.
**Note**  
You can prefix the bucket name with a Region where the bucket is located. Here's an example: `us-west-2:amzn-s3-demo-bucket`. If you're using a proxy for Amazon S3 endpoints in a specific Region that doesn't include us-east-1, prefix the bucket name with a Region. If the bucket name isn't prefixed, it automatically discovers the bucket Region using the us-east-1 endpoint.

   1. **Allow PS Gallery Module Source**: (Optional) Choose **True** to download PowerShell modules from [https://www.powershellgallery.com/](https://www.powershellgallery.com/). If you choose **False**, specify a source for the previous option, **ModuleSourceBucketName**.

   1. **Proxy Uri**: (Optional) Use this option to download MOF files from a proxy server.

   1. **Reboot Behavior**: (Optional) Specify one of the following reboot behaviors if your MOF file execution requires rebooting:
      + **AfterMof**: Reboots the node after all MOF executions are complete. Even if multiple MOF executions request reboots, the system waits until all MOF executions are complete to reboot.
      + **Immediately**: Reboots the node whenever a MOF execution requests it. If running multiple MOF files that request reboots, then the nodes are rebooted multiple times.
      + **Never**: Nodes aren't rebooted, even if the MOF execution explicitly requests a reboot.

   1. **Use Computer Name For Reporting**: (Optional) Turn on this option to use the name of the computer when reporting compliance information. The default value is **false**, which means that the system uses the node ID when reporting compliance information.

   1. **Turn on Verbose Logging**: (Optional) We recommend that you turn on verbose logging when deploying MOF files for the first time.
**Important**  
When allowed, verbose logging writes more data to your Amazon S3 bucket than standard association execution logging. This might result in slower performance and higher storage charges for Amazon S3. To mitigate storage size issues, we recommend that you turn on lifecycle policies on your Amazon S3 bucket. For more information, see [How Do I Create a Lifecycle Policy for an S3 Bucket?](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-lifecycle.html) in the *Amazon Simple Storage Service User Guide*.

   1. **Turn on Debug Logging**: (Optional) We recommend that you turn on debug logging to troubleshoot MOF failures. We also recommend that you deactivate this option for normal use.
**Important**  
When allowed, debug logging writes more data to your Amazon S3 bucket than standard association execution logging. This might result in slower performance and higher storage charges for Amazon S3. To mitigate storage size issues, we recommend that you turn on lifecycle policies on your Amazon S3 bucket. For more information, see [How Do I Create a Lifecycle Policy for an S3 Bucket?](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-lifecycle.html) in the *Amazon Simple Storage Service User Guide*.

   1. **Compliance Type**: (Optional) Specify the compliance type to use when reporting compliance information. The default compliance type is **Custom:DSC**. If you create multiple associations that run MOF files, then be sure to specify a different compliance type for each association. If you don't, each additional association that uses **Custom:DSC** overwrites the existing compliance data.

   1. **Pre Reboot Script**: (Optional) Specify a script to run if the configuration has indicated that a reboot is necessary. The script runs before the reboot. The script must be a single line. Separate additional lines by using semicolons.

1. In the **Targets** section, choose either **Specifying tags** or **Manually Selecting Instance**. If you choose to target resources by using tags, then enter a tag key and a tag value in the fields provided. For more information about using targets, see [Understanding targets and rate controls in State Manager associations](systems-manager-state-manager-targets-and-rate-controls.md).

1. In the **Specify schedule** section, choose either **On Schedule** or **No schedule**. If you choose **On Schedule**, then use the buttons provided to create a cron or rate schedule for the association. 

1. In the **Advanced options** section:
   + In **Compliance severity**, choose a severity level for the association. Compliance reporting indicates whether the association state is compliant or noncompliant, along with the severity level you indicate here. For more information, see [About State Manager association compliance](compliance-about.md#compliance-about-association).

1. In the **Rate control** section, configure options for running State Manager associations across of fleet of managed nodes. For more information about these options, see [Understanding targets and rate controls in State Manager associations](systems-manager-state-manager-targets-and-rate-controls.md).

   In the **Concurrency** section, choose an option: 
   + Choose **targets** to enter an absolute number of targets that can run the association simultaneously.
   + Choose **percentage** to enter a percentage of the target set that can run the association simultaneously.

   In the **Error threshold** section, choose an option:
   + Choose **errors** to enter an absolute number of errors allowed before State Manager stops running associations on additional targets.
   + Choose **percentage** to enter a percentage of errors allowed before State Manager stops running associations on additional targets.

1. (Optional) For **Output options**, to save the command output to a file, select the **Enable writing output to S3** box. Enter the bucket and prefix (folder) names in the boxes.
**Note**  
The S3 permissions that grant the ability to write the data to an S3 bucket are those of the instance profile assigned to the managed node, not those of the IAM user performing this task. For more information, see [Configure instance permissions required for Systems Manager](setup-instance-permissions.md) or [Create an IAM service role for a hybrid environment](hybrid-multicloud-service-role.md). In addition, if the specified S3 bucket is in a different AWS account, verify that the instance profile or IAM service role associated with the managed node has the necessary permissions to write to that bucket.

1. Choose **Create Association**. 

State Manager creates and immediately runs the association on the specified nodes or targets. After the initial execution, the association runs in intervals according to the schedule that you defined and according to the following rules:
+ State Manager runs associations on nodes that are online when the interval starts and skips offline nodes.
+ State Manager attempts to run the association on all configured nodes during an interval.
+ If an association isn't run during an interval (because, for example, a concurrency value limited the number of nodes that could process the association at one time), then State Manager attempts to run the association during the next interval.
+ State Manager records history for all skipped intervals. You can view the history on the **Execution History** tab.

**Note**  
The `AWS-ApplyDSCMofs` is a Systems Manager Command document. This means that you can also run this document by using Run Command, a tool in AWS Systems Manager. For more information, see [AWS Systems Manager Run Command](run-command.md).

## Troubleshooting issues when creating associations that run MOF files


This section includes information to help you troubleshoot issues creating associations that run MOF files.

**Turn on enhanced logging**  
As a first step to troubleshooting, turn on enhanced logging. More specifically, do the following:

1. Verify that the association is configured to write command output to either Amazon S3 or Amazon CloudWatch Logs (CloudWatch).

1. Set the **Enable Verbose Logging** parameter to True.

1. Set the **Enable Debug Logging** parameter to True.

With verbose and debug logging turned on, the **Stdout** output file includes details about the script execution. This output file can help you identify where the script failed. The **Stderr** output file contains errors that occurred during the script execution. 

**Common problems when creating associations that run MOF files**  
This section includes information about common problems that can occur when creating associations that run MOF files and steps to troubleshoot these issues.

**My MOF wasn't applied**  
If State Manager failed to apply the association to your nodes, then start by reviewing the **Stderr** output file. This file can help you understand the root cause of the issue. Also, verify the following:
+ The node has the required access permissions to all MOF-related Amazon S3 buckets. Specifically:
  + **s3:GetObject permissions**: This is required for MOF files in private Amazon S3 buckets and custom modules in Amazon S3 buckets.
  + **s3:PutObject permission**: This is required to write compliance reports and compliance status to Amazon S3 buckets.
+ If you're using tags, then ensure that the node has the required IAM policy. Using tags requires the instance IAM role to have a policy allowing the `ec2:DescribeInstances` and `ssm:ListTagsForResource` actions.
+ Ensure that the node has the expected tags or SSM parameters assigned.
+ Ensure that the tags or SSM parameters aren't misspelled.
+ Try applying the MOF locally on the node to make sure there isn't an issue with the MOF file itself.

**My MOF seemed to fail, but the Systems Manager execution was successful**  
If the `AWS-ApplyDSCMofs` document successfully ran, then the Systems Manager execution status shows **Success**. This status doesn't reflect the compliance status of your node against the configuration requirements in the MOF file. To view the compliance status of your nodes, view the compliance reports. You can view a JSON report in the Amazon S3 Report Bucket. This applies to Run Command and State Manager executions. Also, for State Manager, you can view compliance details on the Systems Manager Compliance page.

**Stderr states: Name resolution failure attempting to reach service**  
This error indicates that the script can't reach a remote service. Most likely, the script can't reach Amazon S3. This issue most often occurs when the script attempts to write compliance reports or compliance status to the Amazon S3 bucket supplied in the document parameters. Typically, this error occurs when a computing environment uses a firewall or transparent proxy that includes an allow list. To resolve this issue:
+ Use Region-specific bucket syntax for all Amazon S3 bucket parameters. For example, the **Mofs to Apply** parameter should be formatted as follows:

  s3:*bucket-region*:*amzn-s3-demo-bucket*:*mof-file-name*.mof.

  Here is an example:` s3:us-west-2:amzn-s3-demo-bucket:my-mof.mof`

  The Report, Status, and Module Source bucket names should be formatted as follows.

  *bucket-region*:*amzn-s3-demo-bucket*. Here is an example: `us-west-1:amzn-s3-demo-bucket;`
+ If Region-specific syntax doesn't fix the problem, then make sure that the targeted nodes can access Amazon S3 in the desired Region. To verify this:

  1. Find the endpoint name for Amazon S3 in the appropriate Amazon S3 Region. For information, see [Amazon S3 Service Endpoints](https://docs.aws.amazon.com/general/latest/gr/s3.html#s3_region) in the *Amazon Web Services General Reference*.

  1. Log on to the target node and run the following ping command.

     ```
     ping s3.s3-region.amazonaws.com
     ```

     If the ping failed, it means that either Amazon S3 is down, or a firewall/transparent proxy is blocking access to the Amazon S3 Region, or the node can't access the internet.

## Viewing DSC resource compliance details


Systems Manager captures compliance information about DSC resource failures in the Amazon S3 **Status Bucket** you specified when you ran the `AWS-ApplyDSCMofs` document. Searching for information about DSC resource failures in an Amazon S3 bucket can be time consuming. Instead, you can view this information in the Systems Manager **Compliance** page. 

The **Compliance resources summary** section displays a count of resources that failed. In the following example, the **ComplianceType** is **Custom:DSC** and one resource is noncompliant.

**Note**  
Custom:DSC is the default **ComplianceType** value in the `AWS-ApplyDSCMofs` document. This value is customizable.

![\[Viewing counts in the Compliance resources summary section of the Compliance page.\]](http://docs.aws.amazon.com/systems-manager/latest/userguide/images/state-manager-mof-detailed-status-3.png)


The **Details overview for resources** section displays information about the AWS resource with the noncompliant DSC resource. This section also includes the MOF name, script execution steps, and (when applicable) a **View output** link to view detailed status information. 

![\[Viewing compliance details for a MOF execution resource failure\]](http://docs.aws.amazon.com/systems-manager/latest/userguide/images/state-manager-mof-detailed-status-1.png)


The **View output** link displays the last 4,000 characters of the detailed status. Systems Manager starts with the exception as the first element, and then scans back through the verbose messages and prepends as many as it can until it reaches the 4,000 character quota. This process displays the log messages that were output before the exception was thrown, which are the most relevant messages for troubleshooting.

![\[Viewing detailed output for MOF resource compliance issue\]](http://docs.aws.amazon.com/systems-manager/latest/userguide/images/state-manager-mof-detailed-status-2.png)


For information about how to view compliance information, see [AWS Systems Manager Compliance](systems-manager-compliance.md).

**Situations that affect compliance reporting**  
If the State Manager association fails, then no compliance data is reported. More specifically, if a MOF fails to process, then Systems Manager doesn’t report any compliance items because the associations fails. For example, if Systems Manager attempts to download a MOF from an Amazon S3 bucket that the node doesn't have permission to access, then the association fails and no compliance data is reported.

If a resource in a second MOF fails, then Systems Manager *does* report compliance data. For example, if a MOF tries to create a file on a drive that doesn’t exist, then Systems Manager reports compliance because the `AWS-ApplyDSCMofs` document is able to process completely, which means the association successfully runs. 

# Creating associations that run Ansible playbooks
Creating associations that run Ansible playbooks

You can create State Manager associations that run Ansible playbooks by using the `AWS-ApplyAnsiblePlaybooks` SSM document. State Manager is a tool in AWS Systems Manager. This document offers the following benefits for running playbooks:
+ Support for running complex playbooks
+ Support for downloading playbooks from GitHub and Amazon Simple Storage Service (Amazon S3)
+ Support for compressed playbook structure
+ Enhanced logging
+ Ability to specify which playbook to run when playbooks are bundled

**Note**  
Systems Manager includes two SSM documents that allow you to create State Manager associations that run Ansible playbooks: `AWS-RunAnsiblePlaybook` and `AWS-ApplyAnsiblePlaybooks`. The `AWS-RunAnsiblePlaybook` document is deprecated. It remains available in Systems Manager for legacy purposes. We recommend that you use the `AWS-ApplyAnsiblePlaybooks` document because of the enhancements described here.  
Associations that run Ansible playbooks aren't supported on macOS.

**Support for running complex playbooks**

The `AWS-ApplyAnsiblePlaybooks` document supports bundled, complex playbooks because it copies the entire file structure to a local directory before executing the specified main playbook. You can provide source playbooks in Zip files or in a directory structure. The Zip file or directory can be stored in GitHub or Amazon S3. 

**Support for downloading playbooks from GitHub**

The `AWS-ApplyAnsiblePlaybooks` document uses the `aws:downloadContent` plugin to download playbook files. Files can be stored in GitHub in a single file or as a combined set of playbook files. To download content from GitHub, specify information about your GitHub repository in JSON format. Here is an example.

```
{
   "owner":"TestUser",
   "repository":"GitHubTest",
   "path":"scripts/python/test-script",
   "getOptions":"branch:master",
   "tokenInfo":"{{ssm-secure:secure-string-token}}"
}
```

**Support for downloading playbooks from Amazon S3**

You can also store and download Ansible playbooks in Amazon S3 as either a single .zip file or a directory structure. To download content from Amazon S3, specify the path to the file. Here are two examples.

**Example 1: Download a specific playbook file**

```
{
   "path":"https://s3.amazonaws.com/amzn-s3-demo-bucket/playbook.yml"
}
```

**Example 2: Download the contents of a directory**

```
{
   "path":"https://s3.amazonaws.com/amzn-s3-demo-bucket/ansible/webservers/"
}
```

**Important**  
If you specify Amazon S3, then the AWS Identity and Access Management (IAM) instance profile on your managed nodes must include permissions for the S3 bucket. For more information, see [Configure instance permissions required for Systems Manager](setup-instance-permissions.md). 

**Support for compressed playbook structure**

The `AWS-ApplyAnsiblePlaybooks` document allows you to run compressed .zip files in the downloaded bundle. The document checks if the downloaded files contain a compressed file in .zip format. If a .zip is found, the document automatically decompresses the file and then runs the specified Ansible automation.

**Enhanced logging**

The `AWS-ApplyAnsiblePlaybooks` document includes an optional parameter for specifying different levels of logging. Specify -v for low verbosity, -vv or –vvv for medium verbosity, and -vvvv for debug level logging. These options directly map to Ansible verbosity options.

**Ability to specify which playbook to run when playbooks are bundled**

The `AWS-ApplyAnsiblePlaybooks` document includes a required parameter for specifying which playbook to run when multiple playbooks are bundled. This option provides flexibility for running playbooks to support different use cases.

## Understanding installed dependencies


If you specify **True** for the **InstallDependencies** parameter, then Systems Manager verifies that your nodes have the following dependencies installed:
+ **Ubuntu Server/Debian Server**: Apt-get (Package Management), Python 3, Ansible, Unzip
+ **Amazon Linux** supported versions: Ansible
+ **RHEL**: Python 3, Ansible, Unzip

If one or more of these dependencies aren't found, then Systems Manager automatically installs them.

## Create an association that runs Ansible playbooks (console)


The following procedure describes how to use the Systems Manager console to create a State Manager association that runs Ansible playbooks by using the `AWS-ApplyAnsiblePlaybooks` document.

**To create an association that runs Ansible playbooks (console)**

1. Open the AWS Systems Manager console at [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/).

1. In the navigation pane, choose **State Manager**.

1. Choose **State Manager**, and then choose **Create association**.

1. For **Name**, specify a name that helps you remember the purpose of the association.

1. In the **Document** list, choose **`AWS-ApplyAnsiblePlaybooks`**.

1. In the **Parameters** section, for **Source Type**, choose either **GitHub** or **S3**.

   **GitHub**

   If you choose **GitHub**, enter repository information in the following format.

   ```
   {
      "owner":"user_name",
      "repository":"name",
      "path":"path_to_directory_or_playbook_to_download",
      "getOptions":"branch:branch_name",
      "tokenInfo":"{{(Optional)_token_information}}"
   }
   ```

   **S3**

   If you choose **S3**, enter path information in the following format.

   ```
   {
      "path":"https://s3.amazonaws.com/path_to_directory_or_playbook_to_download"
   }
   ```

1. For **Install Dependencies**, choose an option.

1. (Optional) For **Playbook File**, enter a file name. If a Zip file contains the playbook, specify a relative path to the Zip file.

1. (Optional) For **Extra Variables**, enter variables that you want State Manager to send to Ansible at runtime.

1. (Optional) For **Check**, choose an option.

1. (Optional) For **Verbose**, choose an option.

1. For **Targets**, choose an option. For information about using targets, see [Understanding targets and rate controls in State Manager associations](systems-manager-state-manager-targets-and-rate-controls.md).

1. In the **Specify schedule** section, choose either **On schedule** or **No schedule**. If you choose **On schedule**, then use the buttons provided to create a cron or rate schedule for the association. 

1. In the **Advanced options** section, for **Compliance severity**, choose a severity level for the association. Compliance reporting indicates whether the association state is compliant or noncompliant, along with the severity level you indicate here. For more information, see [About State Manager association compliance](compliance-about.md#compliance-about-association).

1. In the **Rate control** section, configure options to run State Manager associations across a fleet of managed nodes. For information about using rate controls, see [Understanding targets and rate controls in State Manager associations](systems-manager-state-manager-targets-and-rate-controls.md).

   In the **Concurrency** section, choose an option: 
   + Choose **targets** to enter an absolute number of targets that can run the association simultaneously.
   + Choose **percentage** to enter a percentage of the target set that can run the association simultaneously.

   In the **Error threshold** section, choose an option:
   + Choose **errors** to enter an absolute number of errors that are allowed before State Manager stops running associations on additional targets.
   + Choose **percentage** to enter a percentage of errors that are allowed before State Manager stops running associations on additional targets.

1. (Optional) For **Output options**, to save the command output to a file, select the **Enable writing output to S3** box. Enter the bucket and prefix (folder) names in the boxes.
**Note**  
The S3 permissions that grant the ability to write the data to an S3 bucket are those of the instance profile assigned to the managed node, not those of the IAM user performing this task. For more information, see [Configure instance permissions required for Systems Manager](setup-instance-permissions.md) or [Create an IAM service role for a hybrid environment](hybrid-multicloud-service-role.md). In addition, if the specified S3 bucket is in a different AWS account, verify that the instance profile or IAM service role associated with the managed node has the necessary permissions to write to that bucket.

1. Choose **Create Association**.

**Note**  
If you use tags to create an association on one or more target nodes, and then you remove the tags from a node, that node no longer runs the association. The node is disassociated from the State Manager document. 

## Create an association that runs Ansible playbooks (CLI)


The following procedure describes how to use the AWS Command Line Interface (AWS CLI) to create a State Manager association that runs Ansible playbooks by using the `AWS-ApplyAnsiblePlaybooks` document. 

**To create an association that runs Ansible playbooks (CLI)**

1. Install and configure the AWS Command Line Interface (AWS CLI), if you haven't already.

   For information, see [Installing or updating the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).

1. Run one of the following commands to create an association that runs Ansible playbooks by targeting nodes using tags. Replace each *example resource placeholder* with your own information. Command (A) specifies GitHub as the source type. Command (B) specifies Amazon S3 as the source type.

   **(A) GitHub source**

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" \
       --targets Key=tag:TagKey,Values=TagValue \
       --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner\":\"owner_name\", \"repository\": \"name\", \"getOptions\": \"branch:master\"}"],"InstallDependencies":["True_or_False"],"PlaybookFile":["file_name.yml"],"ExtraVariables":["key/value_pairs_separated_by_a_space"],"Check":["True_or_False"],"Verbose":["-v,-vv,-vvv, or -vvvv"],"TimeoutSeconds":["3600"]}' \
       --association-name "name" \
       --schedule-expression "cron_or_rate_expression"
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" ^
       --targets Key=tag:TagKey,Values=TagValue ^
       --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner\":\"owner_name\", \"repository\": \"name\", \"getOptions\": \"branch:master\"}"],"InstallDependencies":["True_or_False"],"PlaybookFile":["file_name.yml"],"ExtraVariables":["key/value_pairs_separated_by_a_space"],"Check":["True_or_False"],"Verbose":["-v,-vv,-vvv, or -vvvv"], "TimeoutSeconds":["3600"]}' ^
       --association-name "name" ^
       --schedule-expression "cron_or_rate_expression"
   ```

------

   Here is an example.

   ```
   aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" \
       --targets "Key=tag:OS,Values=Linux" \
       --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner\":\"ansibleDocumentTest\", \"repository\": \"Ansible\", \"getOptions\": \"branch:master\"}"],"InstallDependencies":["True"],"PlaybookFile":["hello-world-playbook.yml"],"ExtraVariables":["SSM=True"],"Check":["False"],"Verbose":["-v"]}' \
       --association-name "AnsibleAssociation" \
       --schedule-expression "cron(0 2 ? * SUN *)"
   ```

   **(B) S3 source**

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" \
       --targets Key=tag:TagKey,Values=TagValue \
       --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https://s3.amazonaws.com/path_to_Zip_file,_directory,_or_playbook_to_download\"}"],"InstallDependencies":["True_or_False"],"PlaybookFile":["file_name.yml"],"ExtraVariables":["key/value_pairs_separated_by_a_space"],"Check":["True_or_False"],"Verbose":["-v,-vv,-vvv, or -vvvv"]}' \
       --association-name "name" \
       --schedule-expression "cron_or_rate_expression"
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" ^
       --targets Key=tag:TagKey,Values=TagValue ^
       --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https://s3.amazonaws.com/path_to_Zip_file,_directory,_or_playbook_to_download\"}"],"InstallDependencies":["True_or_False"],"PlaybookFile":["file_name.yml"],"ExtraVariables":["key/value_pairs_separated_by_a_space"],"Check":["True_or_False"],"Verbose":["-v,-vv,-vvv, or -vvvv"]}' ^
       --association-name "name" ^
       --schedule-expression "cron_or_rate_expression"
   ```

------

   Here is an example.

   ```
   aws ssm create-association --name "AWS-ApplyAnsiblePlaybooks" \
       --targets "Key=tag:OS,Values=Linux" \
       --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https://s3.amazonaws.com/amzn-s3-demo-bucket/playbook.yml\"}"],"InstallDependencies":["True"],"PlaybookFile":["playbook.yml"],"ExtraVariables":["SSM=True"],"Check":["False"],"Verbose":["-v"]}' \
       --association-name "AnsibleAssociation" \
       --schedule-expression "cron(0 2 ? * SUN *)"
   ```
**Note**  
State Manager associations don't support all cron and rate expressions. For more information about creating cron and rate expressions for associations, see [Reference: Cron and rate expressions for Systems Manager](reference-cron-and-rate-expressions.md).

   The system attempts to create the association on the nodes and immediately apply the state. 

1. Run the following command to view an updated status of the association you just created. 

   ```
   aws ssm describe-association --association-id "ID"
   ```

# Creating associations that run Chef recipes
Creating associations that run Chef recipes

You can create State Manager associations that run Chef recipes by using the `AWS-ApplyChefRecipes` SSM document. State Manager is a tool in AWS Systems Manager. You can target Linux-based Systems Manager managed nodes with the `AWS-ApplyChefRecipes` SSM document. This document offers the following benefits for running Chef recipes:
+ Supports multiple releases of Chef (Chef 11 through Chef 18).
+ Automatically installs the Chef client software on target nodes.
+ Optionally runs [Systems Manager compliance checks](systems-manager-compliance.md) on target nodes, and stores the results of compliance checks in an Amazon Simple Storage Service (Amazon S3) bucket.
+ Runs multiple cookbooks and recipes in a single run of the document.
+ Optionally runs recipes in `why-run` mode, to show which recipes change on target nodes without making changes.
+ Optionally applies custom JSON attributes to `chef-client` runs.
+ Optionally applies custom JSON attributes from a source file that is stored at a location that you specify.

You can use [Git](#state-manager-chef-git), [GitHub](#state-manager-chef-github), [HTTP](#state-manager-chef-http), or [Amazon S3](#state-manager-chef-s3) buckets as download sources for Chef cookbooks and recipes that you specify in an `AWS-ApplyChefRecipes` document.

**Note**  
Associations that run Chef recipes aren't supported on macOS.

## Getting started


Before you create an `AWS-ApplyChefRecipes` document, prepare your Chef cookbooks and cookbook repository. If you don't already have a Chef cookbook that you want to use, you can get started by using a test `HelloWorld` cookbook that AWS has prepared for you. The `AWS-ApplyChefRecipes` document already points to this cookbook by default. Your cookbooks should be set up similarly to the following directory structure. In the following example, `jenkins` and `nginx` are examples of Chef cookbooks that are available in the [https://supermarket.chef.io/](https://supermarket.chef.io/) on the Chef website.

Though AWS can't officially support cookbooks on the [https://supermarket.chef.io/](https://supermarket.chef.io/) website, many of them work with the `AWS-ApplyChefRecipes` document. The following are examples of criteria to determine when you're testing a community cookbook:
+ The cookbook should support the Linux-based operating systems of the Systems Manager managed nodes that you're targeting.
+ The cookbook should be valid for the Chef client version (Chef 11 through Chef 18) that you use.
+ The cookbook is compatible with Chef Infra Client, and, doesn't require a Chef server.

Verify that you can reach the `Chef.io` website, so that any cookbooks you specify in your run list can be installed when the Systems Manager document (SSM document) runs. Using a nested `cookbooks` folder is supported, but not required; you can store cookbooks directly under the root level.

```
<Top-level directory, or the top level of the archive file (ZIP or tgz or tar.gz)>
    └── cookbooks (optional level)
        ├── jenkins
        │   ├── metadata.rb
        │   └── recipes
        └── nginx
            ├── metadata.rb
            └── recipes
```

**Important**  
Before you create a State Manager association that runs Chef recipes, be aware that the document run installs the Chef client software on your Systems Manager managed nodes, unless you set the value of **Chef client version** to `None`. This operation uses an installation script from Chef to install Chef components on your behalf. Before you run an `AWS-ApplyChefRecipes` document, be sure your enterprise can comply with any applicable legal requirements, including license terms applicable to the use of Chef software. For more information, see the [Chef website](https://www.chef.io/).

Systems Manager can deliver compliance reports to an S3 bucket, the Systems Manager console, or make compliance results available in response to Systems Manager API commands. To run Systems Manager compliance reports, the instance profile attached to Systems Manager managed nodes must have permissions to write to the S3 bucket. The instance profile must have permissions to use the Systems Manager `PutComplianceItem` API. For more information about Systems Manager compliance, see [AWS Systems Manager Compliance](systems-manager-compliance.md).

### Logging the document run


When you run a Systems Manager document (SSM document) by using a State Manager association, you can configure the association to choose the output of the document run, and you can send the output to Amazon S3 or Amazon CloudWatch Logs (CloudWatch Logs). To help ease troubleshooting when an association has finished running, verify that the association is configured to write command output to either an Amazon S3 bucket or CloudWatch Logs. For more information, see [Working with associations in Systems Manager](state-manager-associations.md).

## Applying JSON attributes to targets when running a recipe


You can specify JSON attributes for your Chef client to apply to target nodes during an association run. When setting up the association, you can provide raw JSON or provide the path to a JSON file stored in Amazon S3.

Use JSON attributes when you want to customize how the recipe is run without having to modify the recipe itself, for example:
+ **Overriding a small number of attributes**

  Use custom JSON to avoid having to maintain multiple versions of a recipe to accommodate minor differences.
+ **Providing variable values**

  Use custom JSON to specify values that may change from run-to-run. For example, if your Chef cookbooks configure a third-party application that accepts payments, you might use custom JSON to specify the payment endpoint URL. 

**Specifying attributes in raw JSON**

The following is an example of the format you can use to specify custom JSON attributes for your Chef recipe.

```
{"filepath":"/tmp/example.txt", "content":"Hello, World!"}
```

**Specifying a path to a JSON file**  
The following is an example of the format you can use to specify the path to custom JSON attributes for your Chef recipe.

```
{"sourceType":"s3", "sourceInfo":"someS3URL1"}, {"sourceType":"s3", "sourceInfo":"someS3URL2"}
```

## Use Git as a cookbook source


The `AWS-ApplyChefRecipes` document uses the [aws:downloadContent](documents-command-ssm-plugin-reference.md#aws-downloadContent) plugin to download Chef cookbooks. To download content from Git, specify information about your Git repository in JSON format as in the following example. Replace each *example-resource-placeholder* with your own information.

```
{
   "repository":"GitCookbookRepository",
   "privateSSHKey":"{{ssm-secure:ssh-key-secure-string-parameter}}",
   "skipHostKeyChecking":"false",
   "getOptions":"branch:refs/head/main",
   "username":"{{ssm-secure:username-secure-string-parameter}}",
   "password":"{{ssm-secure:password-secure-string-parameter}}"
}
```

## Use GitHub as a cookbook source


The `AWS-ApplyChefRecipes` document uses the [aws:downloadContent](documents-command-ssm-plugin-reference.md#aws-downloadContent) plugin to download cookbooks. To download content from GitHub, specify information about your GitHub repository in JSON format as in the following example. Replace each *example-resource-placeholder* with your own information.

```
{
   "owner":"TestUser",
   "repository":"GitHubCookbookRepository",
   "path":"cookbooks/HelloWorld",
   "getOptions":"branch:refs/head/main",
   "tokenInfo":"{{ssm-secure:token-secure-string-parameter}}"
}
```

## Use HTTP as a cookbook source


You can store Chef cookbooks at a custom HTTP location as either a single `.zip` or `tar.gz` file, or a directory structure. To download content from HTTP, specify the path to the file or directory in JSON format as in the following example. Replace each *example-resource-placeholder* with your own information.

```
{
   "url":"https://my.website.com/chef-cookbooks/HelloWorld.zip",
   "allowInsecureDownload":"false",
   "authMethod":"Basic",
   "username":"{{ssm-secure:username-secure-string-parameter}}",
   "password":"{{ssm-secure:password-secure-string-parameter}}"
}
```

## Use Amazon S3 as a cookbook source


You can also store and download Chef cookbooks in Amazon S3 as either a single `.zip` or `tar.gz` file, or a directory structure. To download content from Amazon S3, specify the path to the file in JSON format as in the following examples. Replace each *example-resource-placeholder* with your own information.

**Example 1: Download a specific cookbook**

```
{
   "path":"https://s3.amazonaws.com/chef-cookbooks/HelloWorld.zip"
}
```

**Example 2: Download the contents of a directory**

```
{
   "path":"https://s3.amazonaws.com/chef-cookbooks-test/HelloWorld"
}
```

**Important**  
If you specify Amazon S3, the AWS Identity and Access Management (IAM) instance profile on your managed nodes must be configured with the `AmazonS3ReadOnlyAccess` policy. For more information, see [Configure instance permissions required for Systems Manager](setup-instance-permissions.md).

## Create an association that runs Chef recipes (console)


The following procedure describes how to use the Systems Manager console to create a State Manager association that runs Chef cookbooks by using the `AWS-ApplyChefRecipes` document.

1. Open the AWS Systems Manager console at [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/).

1. In the navigation pane, choose **State Manager**.

1. Choose **State Manager**, and then choose **Create association**.

1. For **Name**, enter a name that helps you remember the purpose of the association.

1. In the **Document** list, choose **`AWS-ApplyChefRecipes`**.

1. In **Parameters**, for **Source Type**, select either **Git**, **GitHub**, **HTTP**, or **S3**.

1. For **Source info**, enter cookbook source information using the appropriate format for the **Source Type** that you selected in step 6. For more information, see the following topics:
   + [Use Git as a cookbook source](#state-manager-chef-git)
   + [Use GitHub as a cookbook source](#state-manager-chef-github)
   + [Use HTTP as a cookbook source](#state-manager-chef-http)
   + [Use Amazon S3 as a cookbook source](#state-manager-chef-s3)

1. In **Run list**, list the recipes that you want to run in the following format, separating each recipe with a comma as shown. Don't include a space after the comma. Replace each *example-resource-placeholder* with your own information.

   ```
   recipe[cookbook-name1::recipe-name],recipe[cookbook-name2::recipe-name]
   ```

1. (Optional) Specify custom JSON attributes that you want the Chef client to pass to your target nodes.

   1. In **JSON attributes content**, add any attributes that you want the Chef client to pass to your target nodes.

   1. In **JSON attributes sources**, add the paths to any attributes that you want the Chef client to pass to your target nodes.

   For more information, see [Applying JSON attributes to targets when running a recipe](#apply-custom-json-attributes).

1. For **Chef client version**, specify a Chef version. Valid values are `11` through `18`, or `None`. If you specify a number between `11` `18` (inclusive), Systems Manager installs the correct Chef client version on your target nodes. If you specify `None`, Systems Manager doesn't install the Chef client on target nodes before running the document's recipes.

1. (Optional) For **Chef client arguments**, specify additional arguments that are supported for the version of Chef you're using. To learn more about supported arguments, run `chef-client -h` on a node that is running the Chef client.

1. (Optional) Turn on **Why-run** to show changes made to target nodes if the recipes are run, without actually changing target nodes.

1. For **Compliance severity**, choose the severity of Systems Manager Compliance results that you want reported. Compliance reporting indicates whether the association state is compliant or noncompliant, along with the severity level you specify. Compliance reports are stored in an S3 bucket that you specify as the value of the **Compliance report bucket** parameter (step 14). For more information about Compliance, see [Learn details about Compliance](compliance-about.md) in this guide.

   Compliance scans measure drift between configuration that is specified in your Chef recipes and node resources. Valid values are `Critical`, `High`, `Medium`, `Low`, `Informational`, `Unspecified`, or `None`. To skip compliance reporting, choose `None`.

1. For **Compliance type**, specify the compliance type for which you want results reported. Valid values are `Association` for State Manager associations, or `Custom:`*custom-type*. The default value is `Custom:Chef`.

1. For **Compliance report bucket**, enter the name of an S3 bucket in which to store information about every Chef run performed by this document, including resource configuration and Compliance results.

1. In **Rate control**, configure options to run State Manager associations across a fleet of managed nodes. For information about using rate controls, see [Understanding targets and rate controls in State Manager associations](systems-manager-state-manager-targets-and-rate-controls.md).

   In **Concurrency**, choose an option:
   + Choose **targets** to enter an absolute number of targets that can run the association simultaneously.
   + Choose **percentage** to enter a percentage of the target set that can run the association simultaneously.

   In **Error threshold**, choose an option:
   + Choose **errors** to enter an absolute number of errors that are allowed before State Manager stops running associations on additional targets.
   + Choose **percentage** to enter a percentage of errors that are allowed before State Manager stops running associations on additional targets.

1. (Optional) For **Output options**, to save the command output to a file, select the **Enable writing output to S3** box. Enter the bucket and prefix (folder) names in the boxes.
**Note**  
The S3 permissions that grant the ability to write the data to an S3 bucket are those of the instance profile assigned to the managed node, not those of the IAM user performing this task. For more information, see [Configure instance permissions required for Systems Manager](setup-instance-permissions.md) or [Create an IAM service role for a hybrid environment](hybrid-multicloud-service-role.md). In addition, if the specified S3 bucket is in a different AWS account, verify that the instance profile or IAM service role associated with the managed node has the necessary permissions to write to that bucket.

1. Choose **Create Association**.

## Create an association that runs Chef recipes (CLI)


The following procedure describes how to use the AWS Command Line Interface (AWS CLI) to create a State Manager association that runs Chef cookbooks by using the `AWS-ApplyChefRecipes` document.

1. Install and configure the AWS Command Line Interface (AWS CLI), if you haven't already.

   For information, see [Installing or updating the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).

1. Run one of the following commands to create an association that runs Chef cookbooks on target nodes that have the specified tags. Use the command that is appropriate for your cookbook source type and operating system. Replace each *example-resource-placeholder* with your own information.

   1. **Git source**

------
#### [ Linux & macOS ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" \
          --targets Key=tag:TagKey,Values=TagValue \
          --parameters '{"SourceType":["Git"],"SourceInfo":["{\"repository\":\"repository-name\", \"getOptions\": \"branch:branch-name\", \"username\": \"{{ ssm-secure:username-secure-string-parameter }}\", \"password\": \"{{ ssm-secure:password-secure-string-parameter }}\"}"], "RunList":["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook-name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json-content}"], "JsonAttributesSources": "{\"sourceType\":\"s3\", \"sourceInfo\":\"s3-bucket-endpoint-1\"}, {\"sourceType\":\"s3\", \"sourceInfo\":\"s3-bucket-endpoint-2\"}", "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef-client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity-value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3-bucket-name"]}' \
          --association-name "name" \
          --schedule-expression "cron-or-rate-expression"
      ```

------
#### [ Windows ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" ^
          --targets Key=tag:TagKey,Values=TagValue ^
          --parameters '{"SourceType":["Git"],"SourceInfo":["{\"repository\":\"repository-name\", \"getOptions\": \"branch:branch-name\", \"username\": \"{{ ssm-secure:username-secure-string-parameter }}\", \"password\": \"{{ ssm-secure:password-secure-string-parameter }}\"}"], "RunList":["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook-name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json}"], "JsonAttributesSources": "{\"sourceType\":\"s3\", \"sourceInfo\":\"s3-bucket-endpoint-1\"}, {\"sourceType\":\"s3\", \"sourceInfo\":\"s3-bucket-endpoint-2\"}", "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef-client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity-value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3-bucket-name"]}' ^
          --association-name "name" ^
          --schedule-expression "cron-or-rate-expression"
      ```

------

   1. **GitHub source**

------
#### [ Linux & macOS ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" \
          --targets Key=tag:TagKey,Values=TagValue \
          --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner\":\"owner-name\", \"repository\": \"name\", \"path\": \"path-to-directory-or-cookbook-to-download\", \"getOptions\": \"branch:branch-name\"}"], "RunList":["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook-name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json}"], "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef-client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity-value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3-bucket-name"]}' \
          --association-name "name" \
          --schedule-expression "cron-or-rate-expression"
      ```

------
#### [ Windows ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" ^
          --targets Key=tag:TagKey,Values=TagValue \
          --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner\":\"owner-name\", \"repository\": \"name\", \"path\": \"path-to-directory-or-cookbook-to-download\", \"getOptions\": \"branch:branch-name\"}"], "RunList":["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook-name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json}"], "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef-client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity-value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3-bucket-name"]}' ^
          --association-name "name" ^
          --schedule-expression "cron-or-rate-expression"
      ```

------

      Here is an example.

------
#### [ Linux & macOS ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" \
          --targets Key=tag:OS,Values=Linux \
          --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner\":\"ChefRecipeTest\", \"repository\": \"ChefCookbooks\", \"path\": \"cookbooks/HelloWorld\", \"getOptions\": \"branch:master\"}"], "RunList":["{\"recipe[HelloWorld::HelloWorldRecipe]\", \"recipe[HelloWorld::InstallApp]\"}"], "JsonAttributesContent": ["{\"state\": \"visible\",\"colors\": {\"foreground\": \"light-blue\",\"background\": \"dark-gray\"}}"], "ChefClientVersion": ["14"], "ChefClientArguments":["{--fips}"], "WhyRun": false, "ComplianceSeverity": ["Medium"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["ChefComplianceResultsBucket"]}' \
          --association-name "MyChefAssociation" \
          --schedule-expression "cron(0 2 ? * SUN *)"
      ```

------
#### [ Windows ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" ^
          --targets Key=tag:OS,Values=Linux ^
          --parameters '{"SourceType":["GitHub"],"SourceInfo":["{\"owner\":\"ChefRecipeTest\", \"repository\": \"ChefCookbooks\", \"path\": \"cookbooks/HelloWorld\", \"getOptions\": \"branch:master\"}"], "RunList":["{\"recipe[HelloWorld::HelloWorldRecipe]\", \"recipe[HelloWorld::InstallApp]\"}"], "JsonAttributesContent": ["{\"state\": \"visible\",\"colors\": {\"foreground\": \"light-blue\",\"background\": \"dark-gray\"}}"], "ChefClientVersion": ["14"], "ChefClientArguments":["{--fips}"], "WhyRun": false, "ComplianceSeverity": ["Medium"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["ChefComplianceResultsBucket"]}' ^
          --association-name "MyChefAssociation" ^
          --schedule-expression "cron(0 2 ? * SUN *)"
      ```

------

   1. **HTTP source**

------
#### [ Linux & macOS ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" \
          --targets Key=tag:TagKey,Values=TagValue \
          --parameters '{"SourceType":["HTTP"],"SourceInfo":["{\"url\":\"url-to-zip-file|directory|cookbook\", \"authMethod\": \"auth-method\", \"username\": \"{{ ssm-secure:username-secure-string-parameter }}\", \"password\": \"{{ ssm-secure:password-secure-string-parameter }}\"}"], "RunList":["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook-name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json-content}"], "JsonAttributesSources": "{\"sourceType\":\"s3\", \"sourceInfo\":\"s3-bucket-endpoint-1\"}, {\"sourceType\":\"s3\", \"sourceInfo\":\"s3-bucket-endpoint-2\"}", "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef-client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity-value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3-bucket-name"]}' \
          --association-name "name" \
          --schedule-expression "cron-or-rate-expression"
      ```

------
#### [ Windows ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" ^
          --targets Key=tag:TagKey,Values=TagValue ^
          --parameters '{"SourceType":["HTTP"],"SourceInfo":["{\"url\":\"url-to-zip-file|directory|cookbook\", \"authMethod\": \"auth-method\", \"username\": \"{{ ssm-secure:username-secure-string-parameter }}\", \"password\": \"{{ ssm-secure:password-secure-string-parameter }}\"}"], "RunList":["{\"recipe[cookbook-name-1::recipe-name]\", \"recipe[cookbook-name-2::recipe-name]\"}"], "JsonAttributesContent": ["{custom-json-content}"], "JsonAttributesSources": "{\"sourceType\":\"s3\", \"sourceInfo\":\"s3-bucket-endpoint-1\"}, {\"sourceType\":\"s3\", \"sourceInfo\":\"s3-bucket-endpoint-2\"}", "ChefClientVersion": ["version-number"], "ChefClientArguments":["{chef-client-arguments}"], "WhyRun": boolean, "ComplianceSeverity": ["severity-value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["s3-bucket-name"]}' \
          --association-name "name" ^
          --schedule-expression "cron-or-rate-expression"
      ```

------

   1. **Amazon S3 source**

------
#### [ Linux & macOS ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" \
          --targets Key=tag:TagKey,Values=TagValue \
          --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https://s3.amazonaws.com/path_to_Zip_file,_directory,_or_cookbook_to_download\"}"], "RunList":["{\"recipe[cookbook_name1::recipe_name]\", \"recipe[cookbook_name2::recipe_name]\"}"], "JsonAttributesContent": ["{Custom_JSON}"], "ChefClientVersion": ["version_number"], "ChefClientArguments":["{chef_client_arguments}"], "WhyRun": true_or_false, "ComplianceSeverity": ["severity_value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["amzn-s3-demo-bucket"]}' \
          --association-name "name" \
          --schedule-expression "cron_or_rate_expression"
      ```

------
#### [ Windows ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" ^
          --targets Key=tag:TagKey,Values=TagValue ^
          --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https://s3.amazonaws.com/path_to_Zip_file,_directory,_or_cookbook_to_download\"}"], "RunList":["{\"recipe[cookbook_name1::recipe_name]\", \"recipe[cookbook_name2::recipe_name]\"}"], "JsonAttributesContent": ["{Custom_JSON}"], "ChefClientVersion": ["version_number"], "ChefClientArguments":["{chef_client_arguments}"], "WhyRun": true_or_false, "ComplianceSeverity": ["severity_value"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["amzn-s3-demo-bucket"]}' ^
          --association-name "name" ^
          --schedule-expression "cron_or_rate_expression"
      ```

------

      Here is an example.

------
#### [ Linux & macOS ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" \
          --targets "Key=tag:OS,Values= Linux" \
          --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https://s3.amazonaws.com/amzn-s3-demo-bucket/HelloWorld\"}"], "RunList":["{\"recipe[HelloWorld::HelloWorldRecipe]\", \"recipe[HelloWorld::InstallApp]\"}"], "JsonAttributesContent": ["{\"state\": \"visible\",\"colors\": {\"foreground\": \"light-blue\",\"background\": \"dark-gray\"}}"], "ChefClientVersion": ["14"], "ChefClientArguments":["{--fips}"], "WhyRun": false, "ComplianceSeverity": ["Medium"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["ChefComplianceResultsBucket"]}' \
          --association-name "name" \
          --schedule-expression "cron(0 2 ? * SUN *)"
      ```

------
#### [ Windows ]

      ```
      aws ssm create-association --name "AWS-ApplyChefRecipes" ^
          --targets "Key=tag:OS,Values= Linux" ^
          --parameters '{"SourceType":["S3"],"SourceInfo":["{\"path\":\"https://s3.amazonaws.com/amzn-s3-demo-bucket/HelloWorld\"}"], "RunList":["{\"recipe[HelloWorld::HelloWorldRecipe]\", \"recipe[HelloWorld::InstallApp]\"}"], "JsonAttributesContent": ["{\"state\": \"visible\",\"colors\": {\"foreground\": \"light-blue\",\"background\": \"dark-gray\"}}"], "ChefClientVersion": ["14"], "ChefClientArguments":["{--fips}"], "WhyRun": false, "ComplianceSeverity": ["Medium"], "ComplianceType": ["Custom:Chef"], "ComplianceReportBucket": ["ChefComplianceResultsBucket"]}' ^
          --association-name "name" ^
          --schedule-expression "cron(0 2 ? * SUN *)"
      ```

------

      The system creates the association, and unless your specified cron or rate expression prevents it, the system runs the association on the target nodes.
**Note**  
State Manager associations don't support all cron and rate expressions. For more information about creating cron and rate expressions for associations, see [Reference: Cron and rate expressions for Systems Manager](reference-cron-and-rate-expressions.md).

1. Run the following command to view the status of the association you just created. 

   ```
   aws ssm describe-association --association-id "ID"
   ```

## Viewing Chef resource compliance details


Systems Manager captures compliance information about Chef-managed resources in the Amazon S3 **Compliance report bucket** value that you specified when you ran the `AWS-ApplyChefRecipes` document. Searching for information about Chef resource failures in an S3 bucket can be time consuming. Instead, you can view this information on the Systems Manager **Compliance** page.

A Systems Manager Compliance scan collects information about resources on your managed nodes that were created or checked in the most recent Chef run. The resources can include files, directories, `systemd` services, `yum` packages, templated files, `gem` packages, and dependent cookbooks, among others.

The **Compliance resources summary** section displays a count of resources that failed. In the following example, the **ComplianceType** is **Custom:Chef** and one resource is noncompliant.

**Note**  
`Custom:Chef` is the default **ComplianceType** value in the `AWS-ApplyChefRecipes` document. This value is customizable.

![\[Viewing counts in the Compliance resources summary section of the Compliance page.\]](http://docs.aws.amazon.com/systems-manager/latest/userguide/images/state-manager-chef-compliance-summary.png)


The **Details overview for resources** section shows information about the AWS resource that isn't in compliance. This section also includes the Chef resource type against which compliance was run, severity of issue, compliance status, and links to more information when applicable.

![\[Viewing compliance details for a Chef managed resource failure\]](http://docs.aws.amazon.com/systems-manager/latest/userguide/images/state-manager-chef-compliance-details.png)


**View output** shows the last 4,000 characters of the detailed status. Systems Manager starts with the exception as the first element, finds verbose messages, and shows them until it reaches the 4,000 character quota. This process displays the log messages that were output before the exception was thrown, which are the most relevant messages for troubleshooting.

For information about how to view compliance information, see [AWS Systems Manager Compliance](systems-manager-compliance.md).

**Important**  
If the State Manager association fails, no compliance data is reported. For example, if Systems Manager attempts to download a Chef cookbook from an S3 bucket that the node doesn't have permission to access, the association fails, and Systems Manager reports no compliance data.

# Walkthrough: Automatically update SSM Agent with the AWS CLI


The following procedure walks you through the process of creating a State Manager association using the AWS Command Line Interface. The association automatically updates the SSM Agent according to a schedule that you specify. For more information about SSM Agent, see [Working with SSM Agent](ssm-agent.md). To customize the update schedule for SSM Agent using the console, see [Automatically updating SSM Agent](ssm-agent-automatic-updates.md#ssm-agent-automatic-updates-console).

To be notified about SSM Agent updates, subscribe to the [SSM Agent Release Notes](https://github.com/aws/amazon-ssm-agent/blob/master/RELEASENOTES.md) page on GitHub.

**Before you begin**  
Before you complete the following procedure, verify that you have at least one running Amazon Elastic Compute Cloud (Amazon EC2) instance for Linux, macOS, or Windows Server that is configured for Systems Manager. For more information, see [Setting up managed nodes for AWS Systems Manager](systems-manager-setting-up-nodes.md). 

If you create an association by using either the AWS CLI or AWS Tools for Windows PowerShell, use the `--Targets` parameter to target instances, as shown in the following example. Don't use the `--InstanceID` parameter. The `--InstanceID` parameter is a legacy parameter.

**To create an association for automatically updating SSM Agent**

1. Install and configure the AWS Command Line Interface (AWS CLI), if you haven't already.

   For information, see [Installing or updating the latest version of the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).

1. Run the following command to create an association by targeting instances using Amazon Elastic Compute Cloud (Amazon EC2) tags. Replace each *example resource placeholder* with your own information. The `Schedule` parameter sets a schedule to run the association every Sunday morning at 2:00 a.m. (UTC).

   State Manager associations don't support all cron and rate expressions. For more information about creating cron and rate expressions for associations, see [Reference: Cron and rate expressions for Systems Manager](reference-cron-and-rate-expressions.md).

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
   --targets Key=tag:tag_key,Values=tag_value \
   --name AWS-UpdateSSMAgent \
   --schedule-expression "cron(0 2 ? * SUN *)"
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
   --targets Key=tag:tag_key,Values=tag_value ^
   --name AWS-UpdateSSMAgent ^
   --schedule-expression "cron(0 2 ? * SUN *)"
   ```

------

   You can target multiple instances by specifying instances IDs in a comma-separated list.

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
   --targets Key=instanceids,Values=instance_ID,instance_ID,instance_ID \
   --name AWS-UpdateSSMAgent \
   --schedule-expression "cron(0 2 ? * SUN *)"
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
   --targets Key=instanceids,Values=instance_ID,instance_ID,instance_ID ^
   --name AWS-UpdateSSMAgent ^
   --schedule-expression "cron(0 2 ? * SUN *)"
   ```

------

   You can specify the version of the SSM Agent you want to update to.

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
   --targets Key=instanceids,Values=instance_ID,instance_ID,instance_ID \
   --name AWS-UpdateSSMAgent \
   --schedule-expression "cron(0 2 ? * SUN *)" \
   --parameters version=ssm_agent_version_number
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
   --targets Key=instanceids,Values=instance_ID,instance_ID,instance_ID ^
   --name AWS-UpdateSSMAgent ^
   --schedule-expression "cron(0 2 ? * SUN *)" ^
   --parameters version=ssm_agent_version_number
   ```

------

   The system returns information like the following.

   ```
   {
       "AssociationDescription": {
           "ScheduleExpression": "cron(0 2 ? * SUN *)",
           "Name": "AWS-UpdateSSMAgent",
           "Overview": {
               "Status": "Pending",
               "DetailedStatus": "Creating"
           },
           "AssociationId": "123..............",
           "DocumentVersion": "$DEFAULT",
           "LastUpdateAssociationDate": 1504034257.98,
           "Date": 1504034257.98,
           "AssociationVersion": "1",
           "Targets": [
               {
                   "Values": [
                       "TagValue"
                   ],
                   "Key": "tag:TagKey"
               }
           ]
       }
   }
   ```

   The system attempts to create the association on the instance(s) and applies the state following creation. The association status shows `Pending`.

1. Run the following command to view an updated status of the association you created. 

   ```
   aws ssm list-associations
   ```

   If your instances *aren't* running the most recent version of the SSM Agent, the status shows `Failed`. When a new version of SSM Agent is published, the association automatically installs the new agent, and the status shows `Success`.

# Walkthrough: Automatically update PV drivers on EC2 instances for Windows Server


Amazon Windows Server Amazon Machine Images (AMIs) contain a set of drivers to permit access to virtualized hardware. These drivers are used by Amazon Elastic Compute Cloud (Amazon EC2) to map instance store and Amazon Elastic Block Store (Amazon EBS) volumes to their devices. We recommend that you install the latest drivers to improve stability and performance of your EC2 instances for Windows Server. For more information about PV drivers, see [AWS PV Drivers](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/xen-drivers-overview.html#xen-driver-awspv).

The following walkthrough shows you how to configure a State Manager association to automatically download and install new AWS PV drivers when the drivers become available. State Manager is a tool in AWS Systems Manager.

**Before you begin**  
Before you complete the following procedure, verify that you have at least one Amazon EC2 instance for Windows Server running that is configured for Systems Manager. For more information, see [Setting up managed nodes for AWS Systems Manager](systems-manager-setting-up-nodes.md). 

**To create a State Manager association that automatically updates PV drivers**

1. Open the AWS Systems Manager console at [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/).

1. In the navigation pane, choose **State Manager**.

1. Choose **Create association**.

1. In the **Name** field, enter a descriptive name for the association.

1. In the **Document** list, choose `AWS-ConfigureAWSPackage`.

1. In the **Parameters** area, do the following:
   + For **Action**, choose **Install**.
   + For **Installation type**, choose **Uninstall and reinstall**.
**Note**  
In-place upgrades are not supported for this package. It must be uninstalled and reinstalled.
   + For **Name**, enter **AWSPVDriver**.

     You don't need to enter anything for **Version** and **Additional Arguments**.

1. In the **Targets** section, choose the managed nodes on which you want to run this operation by specifying tags, selecting instances or edge devices manually, or specifying a resource group.
**Tip**  
If a managed node you expect to see isn't listed, see [Troubleshooting managed node availability](fleet-manager-troubleshooting-managed-nodes.md) for troubleshooting tips.
**Note**  
If you choose to target instances by using tags, and you specify tags that map to Linux instances, the association succeeds on the Windows Server instance but fails on the Linux instances. The overall status of the association shows **Failed**.

1. In the **Specify schedule** area, choose whether to run the association on a schedule that you configure, or just once. Updated PV drivers are released a several times a year, so you can schedule the association to run once a month, if you want.

1. In the **Advanced options** area, for **Compliance severity**, choose a severity level for the association. Compliance reporting indicates whether the association state is compliant or noncompliant, along with the severity level you indicate here. For more information, see [About State Manager association compliance](compliance-about.md#compliance-about-association).

1. For **Rate control**:
   + For **Concurrency**, specify either a number or a percentage of managed nodes on which to run the command at the same time.
**Note**  
If you selected targets by specifying tags applied to managed nodes or by specifying AWS resource groups, and you aren't certain how many managed nodes are targeted, then restrict the number of targets that can run the document at the same time by specifying a percentage.
   + For **Error threshold**, specify when to stop running the command on other managed nodes after it fails on either a number or a percentage of nodes. For example, if you specify three errors, then Systems Manager stops sending the command when the fourth error is received. Managed nodes still processing the command might also send errors.

1. (Optional) For **Output options**, to save the command output to a file, select the **Enable writing output to S3** box. Enter the bucket and prefix (folder) names in the boxes.
**Note**  
The S3 permissions that grant the ability to write the data to an S3 bucket are those of the instance profile assigned to the managed node, not those of the IAM user performing this task. For more information, see [Configure instance permissions required for Systems Manager](setup-instance-permissions.md) or [Create an IAM service role for a hybrid environment](hybrid-multicloud-service-role.md). In addition, if the specified S3 bucket is in a different AWS account, verify that the instance profile or IAM service role associated with the managed node has the necessary permissions to write to that bucket.

1. (Optional) In the **CloudWatch alarm** section, for **Alarm name**, choose a CloudWatch alarm to apply to your association for monitoring. 
**Note**  
Note the following information about this step.  
The alarms list displays a maximum of 100 alarms. If you don't see your alarm in the list, use the AWS Command Line Interface to create the association. For more information, see [Create an association (command line)](state-manager-associations-creating.md#create-state-manager-association-commandline).
To attach a CloudWatch alarm to your command, the IAM principal that creates the association must have permission for the `iam:createServiceLinkedRole` action. For more information about CloudWatch alarms, see [Using Amazon CloudWatch alarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html).
If your alarm activates, any pending command invocations or automations do not run.

1. Choose **Create association**, and then choose **Close**. The system attempts to create the association on the instances and immediately apply the state. 

   If you created the association on one or more Amazon EC2 instances for Windows Server, the status changes to **Success**. If your instances aren't configured for Systems Manager, or if you inadvertently targeted Linux instances, the status shows **Failed**.

   If the status is **Failed**, choose the association ID, choose the **Resources** tab, and then verify that the association was successfully created on your EC2 instances for Windows Server. If EC2 instances for Windows Server show a status of **Failed**, verify that the SSM Agent is running on the instance, and verify that the instance is configured with an AWS Identity and Access Management (IAM) role for Systems Manager. For more information, see [Setting up Systems Manager unified console for an organization](systems-manager-setting-up-organizations.md).