

This is the new *CloudFormation Template Reference Guide*. Please update your bookmarks and links. For help getting started with CloudFormation, see the [AWS CloudFormation User Guide](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html).

# CloudFormation helper scripts reference
<a name="cfn-helper-scripts-reference"></a>

CloudFormation provides the following Python helper scripts that you can use to install software and start services on an Amazon EC2 instance that you create as part of your stack:
+  [cfn-init](cfn-init.md) – Use to retrieve and interpret resource metadata, install packages, create files, and start services.
+  [cfn-signal](cfn-signal.md) – Use to signal with a `CreationPolicy` or `WaitCondition`, so you can synchronize other resources in the stack when the prerequisite resource or application is ready.
+  [cfn-get-metadata](cfn-get-metadata.md) – Use to retrieve metadata for a resource or path to a specific key.
+  [cfn-hup](cfn-hup.md) – Use to check for updates to metadata and execute custom hooks when changes are detected.

You call the scripts directly from your template. The scripts work in conjunction with resource metadata that's defined in the same template. The scripts run on the Amazon EC2 instance during the stack creation process.

**Note**  
The scripts aren't executed by default. You must include calls in your template to execute specific helper scripts.

**Topics**
+ [Amazon Linux AMI images](#cfn-helper-scripts-reference-amazon-amis)
+ [Downloading packages for other platforms](#cfn-helper-scripts-reference-downloads)
+ [Permissions for helper scripts](#cfn-helper-scripts-reference-permissions)
+ [Using the latest version](#cfn-helper-scripts-reference-latest-version)
+ [cfn-init](cfn-init.md)
+ [cfn-signal](cfn-signal.md)
+ [cfn-get-metadata](cfn-get-metadata.md)
+ [cfn-hup](cfn-hup.md)

## Amazon Linux AMI images
<a name="cfn-helper-scripts-reference-amazon-amis"></a>

The CloudFormation helper scripts are preinstalled on Amazon Linux AMI images that have bootstrap scripts installed.
+ On the latest Amazon Linux AMI version, the scripts are installed in `/opt/aws/bin`.
+ On previous Amazon Linux AMI versions, the `aws-cfn-bootstrap` package that contains the scripts is located in the Yum repository.

**Note**  
The helper scripts are pre-installed on the latest versions of the Amazon Linux AMI and not on Optimized AMIs, such as ECS Optimized Image that uses Amazon Linux as base.

## Downloading packages for other platforms
<a name="cfn-helper-scripts-reference-downloads"></a>

<a name="cfn-helper-scripts-reference-downloads"></a>For Linux/Unix distributions other than Amazon Linux AMI images and for Microsoft Windows (2008 or later), you can download the `aws-cfn-bootstrap` package.

**Note**  
Version 2.0–1 and above of the helper scripts support Python 3.4 and above. If you need helper scripts that support an earlier version of Python, see [Release History for CloudFormation Helper Scripts 1.4](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/releasehistory-aws-cfn-bootstrap.html#releasehistory-aws-cfn-bootstrap-v1).


| File format | Download URL | 
| --- | --- | 
|  TAR.GZ  |  [ https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz](https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz) Use Python's pip to install `tar.gz`. To complete the installation for Ubuntu, you must create a symlink: `ln -s /<path-to-extracted-tar>/aws-cfn-bootstrap-2.0/init/ubuntu/cfn-hup /etc/init.d/cfn-hup`  | 
|  ZIP  |  [ https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.zip](https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.zip)  | 
|  EXE  |  32-bit Windows: [ https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.exe](https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.exe)  64-bit Windows: [ https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-win64-latest.exe](https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-win64-latest.exe)  | 

## Permissions for helper scripts
<a name="cfn-helper-scripts-reference-permissions"></a>

By default, helper scripts don't require credentials, so you don't need to use the `--access-key`, `--secret-key`, `--role`, or `--credential-file` options. However, if no credentials are specified, CloudFormation checks for stack membership and limits the scope of the call to the stack that the instance belongs to.

If you choose to specify an option, we recommend that you specify only one of the following:
+ `--role`
+ `--credential-file`
+ `--access-key` together with `--secret-key`

If you do specify an option, keep in mind which permissions the various helper scripts require:
+ `cfn-signal` requires `cloudformation:SignalResource`
+ All other helper scripts require `cloudformation:DescribeStackResource`

For more information on using CloudFormation-specific actions and condition context keys in IAM policies, see [Control CloudFormation access with AWS Identity and Access Management](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/control-access-with-iam.html) in the *AWS CloudFormation User Guide*.

## Using the latest version
<a name="cfn-helper-scripts-reference-latest-version"></a>

The helper scripts are updated periodically. If you use the helper scripts, ensure that your launched instances are using the latest version of the scripts:
+ Include the following command in the `UserData` property of your template before you call the scripts. This command ensures that you get the latest version:

  `yum install -y aws-cfn-bootstrap`
+ If you don't include the `yum install` command and you use the `cfn-init`, `cfn-signal`, or `cfn-get-metadata` scripts, then you'll need to manually update the scripts in each Amazon EC2 Linux instance using this command:

  `sudo yum install -y aws-cfn-bootstrap`
**Note**  
Running `sudo yum install -y aws-cfn-bootstrap` installs the helper scripts from the `yum` repository.
+ If you don't include the `yum install` command and you use the `cfn-hup` script, then you'll need to manually update the script in each Amazon EC2 Linux instance using these commands:

  `sudo yum install -y aws-cfn-bootstrap`

  `sudo /sbin/service cfn-hup restart`
**Note**  
Running `sudo yum install -y aws-cfn-bootstrap` installs the helper scripts from the `yum` repository.
+ If you use the source code for the scripts to work with another version of Linux or a different platform, and you have created your own certificate trust store, you'll also need to keep the trust store updated.

For the version history of the `aws-cfn-bootstrap` package, see [Release history for CloudFormation helper scripts](releasehistory-aws-cfn-bootstrap.md).

# cfn-init
<a name="cfn-init"></a>

In a CloudFormation template, you can use `AWS::CloudFormation::Init` within the `Metadata` section of an Amazon EC2 resource to define initialization tasks. For more information, see [`AWS::CloudFormation::Init`](aws-resource-init.md).

The `cfn-init` helper script reads template metadata from the `AWS::CloudFormation::Init` key and acts accordingly to:
+ Fetch and parse metadata from CloudFormation
+ Install packages
+ Write files to disk
+ Enable/disable and start/stop services

The `cfn-init` helper script is typically run from an Amazon EC2 instance's or launch template's user data.

If you're new to using helper scripts, we recommend you first complete the [Deploying applications on Amazon EC2](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/deploying.applications.html) tutorial in the *AWS CloudFormation User Guide*.

**Topics**
+ [Syntax](#cfn-init-Syntax)
+ [Options](#cfn-init-options)
+ [Examples](#cfn-init-examples)
+ [Related resources](#cfn-init-related-resources)

**Note**  
If you use `cfn-init` to update an existing file, it creates a backup copy of the original file in the same directory with a .bak extension. For example, if you update `/path/to/file_name`, the action produces two files: `/path/to/file_name.bak` contains the original file's contents and `/path/to/file_name` contains the updated contents.

## Syntax
<a name="cfn-init-Syntax"></a>

```
cfn-init --stack|-s stack.name.or.id \
         --resource|-r logical.resource.id \
         --region region \
         --access-key access.key \
         --secret-key secret.key \
         --role rolename \
         --credential-file|-f credential.file \
         --configsets|-c config.sets \
         --url|-u service.url \
         --http-proxy HTTP.proxy \
         --https-proxy HTTPS.proxy \
         --verbose|-v
```

**Note**  
`cfn-init` doesn't require credentials, so you don't need to use the `--access-key`, `--secret-key`, `--role`, or `--credential-file` options. However, if no credentials are specified, CloudFormation checks for stack membership and limits the scope of the call to the stack that the instance belongs to. For more information, see [Permissions for helper scripts](cfn-helper-scripts-reference.md#cfn-helper-scripts-reference-permissions).

## Options
<a name="cfn-init-options"></a>


| Name | Description | Required | 
| --- | --- | --- | 
|   `-s, --stack`   |  Stack name or stack ID. *Type*: String *Default*: None *Example*: `--stack { "Ref" : "AWS::StackName" },`  |  Yes  | 
|   `-r, --resource `   |  The logical resource ID of the resource that contains the metadata. *Type*: String *Example*: `--resource WebServerHost`  |  Yes  | 
|   `--region`   |  The CloudFormation regional endpoint to use. *Type*: String *Default*: `us-east-1` *Example*:`--region ", { "Ref" : "AWS::Region" },`  |  No  | 
|   `--access-key`   |  AWS access key for an account with permission to call `DescribeStackResource` on CloudFormation. The credential file parameter supersedes this parameter. *Type*: String  |  No  | 
|   `--secret-key`   |  AWS secret access key that corresponds to the specified AWS access key. *Type*: String  |  No  | 
|   `--role`   |  The name of an IAM role that's associated with the instance. *Type*: String Condition: The credential file parameter supersedes this parameter.  |  No  | 
|   `-f, --credential-file`   |  A file that contains both a secret access key and an access key. The credential file parameter supersedes the --role, --access-key, and --secret-key parameters. *Type*: String  |  No  | 
|   `-c, --configsets`   |  A comma-separated list of configsets to run (in order). *Type*: String *Default*: `default`  |  No  | 
|   `-u, --url`   |  The CloudFormation endpoint to use. *Type*: String  |  No  | 
|  `--http-proxy`  |  An HTTP proxy (non-SSL). Use the following format: `http://user:password@host:port` *Type*: String  |  No  | 
|  `--https-proxy`  |  An HTTPS proxy. Use the following format: `https://user:password@host:port` *Type*: String  |  No  | 
|  `-v, --verbose`  |  Verbose output. This is useful for debugging cases where `cfn-init` is failing to initialize.  To debug initialization events, you should turn `DisableRollback` on. You can then SSH into the console and read the logs at `/var/log/cfn-init.log`. For more information, see [Choose how to handle failures when provisioning resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stack-failure-options.html) in the *AWS CloudFormation User Guide*.   |  No  | 
| `-h, --help` | Shows the help message and exits. |  No | 

## Examples
<a name="cfn-init-examples"></a>

### Amazon Linux examples
<a name="w2aac32c27c21b3"></a>

The following examples show the `UserData` property of an EC2 instance, which runs the `InstallAndRun` configset that's associated with the `WebServerInstance` resource.

To include the latest version, add `yum install -y aws-cfn-bootstrap` to the `UserData`.

#### JSON
<a name="cfn-init-example.json"></a>

`UserData` property using the `Fn::Join` intrinsic function.

```
{
    "UserData": {
        "Fn::Base64": {
            "Fn::Join": [
                "",
                [
                    "#!/bin/bash -xe\n",
                    "",
                    "yum install -y aws-cfn-bootstrap",
                    "/opt/aws/bin/cfn-init -v ",
                    "         --stack ",
                    {
                        "Ref": "AWS::StackName"
                    },
                    "         --resource WebServerInstance ",
                    "         --configsets InstallAndRun ",
                    "         --region ",
                    {
                        "Ref": "AWS::Region"
                    },
                    "\n"
                ]
            ]
        }
    }
}
```

#### YAML
<a name="cfn-init-example.yaml"></a>

`UserData` property using the `Fn::Sub` intrinsic function.

```
UserData:
  Fn::Base64: !Sub |
    #!/bin/bash -xe
    yum update -y aws-cfn-bootstrap
    # Install the files and packages from the metadata
    /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource WebServerInstance --configsets InstallAndRun --region ${AWS::Region}
```

## Related resources
<a name="cfn-init-related-resources"></a>

For a tutorial with a sample template, see [Deploying applications on Amazon EC2](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/deploying.applications.html) in the *AWS CloudFormation User Guide*.

For a Windows example, see [Bootstrapping Windows-based CloudFormation stacks](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-windows-stacks-bootstrapping.html) in the *AWS CloudFormation User Guide*.

You can also visit our GitHub repository to download [sample templates](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html#sample-templates) that use `cfn-init`, including the following templates.
+  [InstanceWithCfnInit.yaml](https://github.com/aws-cloudformation/aws-cloudformation-templates/blob/main/EC2/InstanceWithCfnInit.yaml) 
+  [AutoScalingRollingUpdates.yaml](https://github.com/aws-cloudformation/aws-cloudformation-templates/blob/main/AutoScaling/AutoScalingRollingUpdates.yaml) 

For example LAMP stack templates that use `cfn-init`, see [ec2-lamp-server](https://github.com/aws-samples/ec2-lamp-server) on the GitHub website.

# cfn-signal
<a name="cfn-signal"></a>

The `cfn-signal` helper script signals CloudFormation to indicate whether Amazon EC2 instances have been successfully created or updated. If you install and configure software applications on instances, you can signal CloudFormation when those software applications are ready.

You use the `cfn-signal` script in conjunction with a [`CreationPolicy` attribute](aws-attribute-creationpolicy.md) or an [`UpdatePolicy` attribute](aws-attribute-updatepolicy.md) with `WaitOnResourceSignals` for Amazon EC2 Auto Scaling groups. When CloudFormation creates or updates resources with those policies, it suspends work on the stack until the resource receives the required number of signals or until the timeout period is exceeded. For each valid signal that CloudFormation receives, it publishes the signals to the stack events so that you track each signal.

**Topics**
+ [Syntax for resource signaling (recommended)](#w2aac32c29b9)
+ [Syntax for use with wait condition handle](#cfn-signal-Syntaxwaitcondition)
+ [Options](#cfn-signal-options)
+ [Examples](#cfn-signal-examples)
+ [Related resources](#cfn-signal-related-resources)

## Syntax for resource signaling (recommended)
<a name="w2aac32c29b9"></a>

If you want to signal CloudFormation resources, use the following syntax.

```
cfn-signal --success|-s signal.to.send \
        --access-key access.key \
        --credential-file|-f credential.file \
        --exit-code|-e exit.code \
        --http-proxy HTTP.proxy \
        --https-proxy HTTPS.proxy \
        --id|-i unique.id \
        --region AWS.region \
        --resource resource.logical.ID \
        --role IAM.role.name \
        --secret-key secret.key \
        --stack stack.name.or.stack.ID \
        --url CloudFormation.endpoint
```

**Note**  
`cfn-signal` doesn't require credentials, so you don't need to use the `--access-key`, `--secret-key`, `--role`, or `--credential-file` options. However, if no credentials are specified, CloudFormation checks for stack membership and limits the scope of the call to the stack that the instance belongs to. For more information, see [Permissions for helper scripts](cfn-helper-scripts-reference.md#cfn-helper-scripts-reference-permissions).

## Syntax for use with wait condition handle
<a name="cfn-signal-Syntaxwaitcondition"></a>

If you want to signal a wait condition handle, use the following syntax.

```
cfn-signal --success|-s signal.to.send \
        --reason|-r resource.status.reason \
        --data|-d data \
        --id|-i unique.id \
        --exit-code|-e exit.code \
        waitconditionhandle.url
```

## Options
<a name="cfn-signal-options"></a>

The options that you can use depend on whether you're signaling a creation policy or a wait condition handle. Some options that apply to a creation policy might not apply to a wait condition handle.


| Name | Description | Required | 
| --- | --- | --- | 
|  `--access-key` (resource signaling only)  |  AWS access key for an account with permission to call the CloudFormation `SignalResource `API. The credential file parameter supersedes this parameter. *Type*: String  |  No  | 
|  `-d, --data` (wait condition handle only)  |  Data to send back with the `waitConditionHandle`. Defaults to blank. *Type*: String *Default*: blank  |  No  | 
|  `-e, --exit-code`   |  The error code from a process that can be used to determine success or failure. If specified, the `--success` option is ignored. *Type*: String *Examples*: `-e $?` (for Linux), `-e %ERRORLEVEL%` (for Windows cmd.exe), and `-e $lastexitcode` (for Windows PowerShell).  |  No  | 
|  `-f, --credential-file` (resource signaling only)  |  A file that contains both a secret access key and an access key. The credential file parameter supersedes the --role, --access-key, and --secret-key parameters. *Type*: String  |  No  | 
|  `--http-proxy`  |  An HTTP proxy (non-SSL). Use the following format: `http://user:password@host:port` *Type*: String  |  No  | 
|  `--https-proxy`  |  An HTTPS proxy. Use the following format: `https://user:password@host:port` *Type*: String  |  No  | 
|  `-i, --id`  |  The unique ID to send. *Type*: String *Default*: The ID of the Amazon EC2 instance. If the ID can't be resolved, the machine's Fully Qualified Domain Name (FQDN) is returned.  |  No  | 
|  `-r, --reason ` (wait condition handle only)  |  A status reason for the resource event (currently only used on failure) - defaults to 'Configuration failed' if success is false. *Type*: String  |  No  | 
| --region (resource signaling only) |  The CloudFormation regional endpoint to use. *Type*: String *Default*: `us-east-1`  |  No  | 
| --resource (resource signaling only) |  The logical ID of the resource that contains the creations policy you want to signal. *Type*: String  |  Yes  | 
|  `--role` (resource signaling only)  |  The name of an IAM role that's associated with the instance. *Type*: String Condition: The credential file parameter supersedes this parameter.  |  No  | 
|  `-s, --success`   |  If true, signal `SUCCESS`, else `FAILURE`. *Type*: Boolean *Default*: `true`  |  No  | 
|  `--secret-key` (resource signaling only)  |  AWS secret access key that corresponds to the specified AWS access key. *Type*: String  |  No  | 
|  `--stack` (resource signaling only)  |  The stack name or stack ID that contains the resource you want to signal. *Type*: String  |  Yes  | 
| -u, --url (resource signaling only) |  The CloudFormation endpoint to use. *Type*: String  |  No  | 
|  `waitconditionhandle.url` (wait condition handle only)  |  A presigned URL that you can use to signal success or failure to an associated `WaitCondition` *Type*: String  |  Yes  | 

## Examples
<a name="cfn-signal-examples"></a>

### Amazon Linux example
<a name="w2aac32c29c15b3"></a>

A common usage pattern is to use `cfn-init` and `cfn-signal` together. The `cfn-signal` call uses the return status of the call to `cfn-init` (using the \$1? shell construct). If the application fails to install, the instance will fail to create and the stack will rollback.

#### JSON
<a name="cfn-signal-example.json"></a>

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Simple EC2 instance",
    "Resources": {
        "MyInstance": {
            "Type": "AWS::EC2::Instance",
            "Metadata": {
                "AWS::CloudFormation::Init": {
                    "config": {
                        "files": {
                            "/tmp/test.txt": {
                                "content": "Hello world!",
                                "mode": "000755",
                                "owner": "root",
                                "group": "root"
                            }
                        }
                    }
                }
            },
            "Properties": {
                "ImageId": "{{resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2}}",
                "InstanceType": "t2.micro",
                "UserData": {
                    "Fn::Base64": {
                        "Fn::Join": [
                            "",
                            [
                                "#!/bin/bash -x\n",
                                "# Install the files and packages from the metadata\n",
                                "yum install -y aws-cfn-bootstrap",
                                "\n",
                                "/opt/aws/bin/cfn-init -v ",
                                "         --stack ",
                                {
                                    "Ref": "AWS::StackName"
                                },
                                "         --resource MyInstance ",
                                "         --region ",
                                {
                                    "Ref": "AWS::Region"
                                },
                                "\n",
                                "# Signal the status from cfn-init\n",
                                "/opt/aws/bin/cfn-signal -e $? ",
                                "         --stack ",
                                {
                                    "Ref": "AWS::StackName"
                                },
                                "         --resource MyInstance ",
                                "         --region ",
                                {
                                    "Ref": "AWS::Region"
                                },
                                "\n"
                            ]
                        ]
                    }
                }
            },
            "CreationPolicy": {
                "ResourceSignal": {
                    "Timeout": "PT5M"
                }
            }
        }
    }
}
```

#### YAML
<a name="cfn-signal-example.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Description: Simple EC2 instance
Resources:
  MyInstance:
    Type: AWS::EC2::Instance
    Metadata:
      'AWS::CloudFormation::Init':
        config:
          files:
            /tmp/test.txt:
              content: Hello world!
              mode: '000755'
              owner: root
              group: root
    Properties:
      ImageId: '{{resolve:ssm:/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2}}'
      InstanceType: t2.micro
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash -x
          # Install the files and packages from the metadata
          yum install -y aws-cfn-bootstrap
          /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource MyInstance --region ${AWS::Region}
          # Signal the status from cfn-init
          /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource MyInstance --region ${AWS::Region}
    CreationPolicy:
      ResourceSignal:
        Timeout: PT5M
```

## Related resources
<a name="cfn-signal-related-resources"></a>

You can also visit our GitHub repository to download [sample templates](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html#sample-templates) that use `cfn-signal`, including the following templates.
+  [InstanceWithCfnInit.yaml](https://github.com/aws-cloudformation/aws-cloudformation-templates/blob/main/EC2/InstanceWithCfnInit.yaml) 
+  [AutoScalingRollingUpdates.yaml](https://github.com/aws-cloudformation/aws-cloudformation-templates/blob/main/AutoScaling/AutoScalingRollingUpdates.yaml) 

# cfn-get-metadata
<a name="cfn-get-metadata"></a>

You can use the `cfn-get-metadata` helper script to fetch a metadata block from CloudFormation and print it to standard output. You can also print a sub-tree of the metadata block if you specify a key. However, only top-level keys are supported.

**Topics**
+ [Syntax](#cfn-get-metadata-Syntax)
+ [Options](#cfn-get-metadata-options)

## Syntax
<a name="cfn-get-metadata-Syntax"></a>

```
cfn-get-metadata --access-key access.key \
                 --secret-key secret.key \
                 --credential-file|f credential.file \
                 --key|k key \
                 --stack|-s stack.name.or.id \
                 --resource|-r logical.resource.id \
                 --role IAM.role.name \
                 --url|-u service.url \
                 --region region
```

**Note**  
`cfn-get-metadata` doesn't require credentials, so you don't need to use the `--access-key`, `--secret-key`, `--role`, or `--credential-file` options. However, if no credentials are specified, CloudFormation checks for stack membership and limits the scope of the call to the stack that the instance belongs to. For more information, see [Permissions for helper scripts](cfn-helper-scripts-reference.md#cfn-helper-scripts-reference-permissions).

## Options
<a name="cfn-get-metadata-options"></a>


| Name | Description | Required | 
| --- | --- | --- | 
|   `-k, --key`   |  For a key-value pair, returns the name of the key for the value that you specified. *Type*: String *Example*: For `{ "Key1": "SampleKey1", "Key2": "SampleKey2" }`, `cfn-get-metadata -k Key2` returns `SampleKey2`.  |  No  | 
|   `-s, --stack`   |  Name of the Stack. *Type*: String *Default*: None *Example*: `-s { "Ref" : "AWS::StackName" },`  |  Yes  | 
|   `-r, --resource`   |  The logical resource ID of the resource that contains the metadata. *Type*: String *Example*: `-r WebServerHost`  |  Yes  | 
|  `--role` (resource signaling only)  |  The name of an IAM role that's associated with the instance. *Type*: String Condition: The credential file parameter supersedes this parameter.  |  No  | 
|   `--region`   |  The region to derive the CloudFormation URL from. *Type*: String *Default*: None *Example*: `--region ", { "Ref" : "AWS::Region" },`  |  No  | 
|   `--access-key`   |  AWS Access Key for an account with permission to call DescribeStackResource on CloudFormation. *Type*: String Condition: The credential file parameter supersedes this parameter.  |  Conditional  | 
|   `--secret-key`   |  AWS Secret Key that corresponds to the specified AWS Access Key. *Type*: String Condition: The credential file parameter supersedes this parameter.  |  Conditional  | 
|   `-f, --credential-file`   |  A file that contains both a secret key and an access key. *Type*: String Condition: The credential file parameter supersedes the --access-key and --secret-key parameters.  |  Conditional  | 

# cfn-hup
<a name="cfn-hup"></a>

The `cfn-hup` helper is a daemon that detects changes in resource metadata and runs user-specified actions when a change is detected. This allows you to make configuration updates on your running Amazon EC2 instances through the `UpdateStack` API action.

For more information, see the [ Updating a CloudFormation stack](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/updating.stacks.walkthrough.html) tutorial in the *AWS CloudFormation User Guide*.

**Topics**
+ [Syntax](#cfn-hup-Syntax)
+ [Options](#cfn-hup-options)
+ [cfn-hup.conf configuration file](#cfn-hup-config-file)
+ [`hooks.conf` configuration file](#cfn-hup-hook-file)
+ [`hooks.d` directory](#cfn-hup-hooks-dir)
+ [Examples](#cfn-hup-examples)
+ [Related resources](#cfn-hup-related-resources)

## Syntax
<a name="cfn-hup-Syntax"></a>

```
cfn-hup --config|-c config.dir \
        --no-daemon \
        --verbose|-v
```

## Options
<a name="cfn-hup-options"></a>


| Name | Description | Required | 
| --- | --- | --- | 
|   `--config\|-c config.dir`   |  Specifies the path that the `cfn-hup` script looks for the `cfn-hup.conf` and the `hooks.d` directories. On Windows, the default path is `system_drive\cfn`. On Linux, the default path is `/etc/cfn`.  |  No  | 
|   `--no-daemon`   |  Specify this option to run the `cfn-hup` script once and exit.  |  No  | 
|   `-v, --verbose `   |  Specify this option to use verbose mode.  |  No  | 

## cfn-hup.conf configuration file
<a name="cfn-hup-config-file"></a>

The `cfn-hup.conf` file stores the name of the stack and the AWS credentials that the `cfn-hup` daemon targets.

The `cfn-hup.conf` file uses the following format:

```
[main]
stack=<stack-name-or-id>
```


| Name | Description | Required | 
| --- | --- | --- | 
|   `stack`   |  A stack name or ID. *Type*: String  |  Yes  | 
|   `credential-file`   |  An owner-only credential file, in the same format used for the command line tools. *Type*: String *Condition*: The `role` parameter supersedes this parameter.  |  No  | 
|   `role`   |  The name of an IAM role that's associated with the instance. *Type*: String  |  No  | 
|   `region`   |  The name of the AWS Region containing the stack. *Example*: us-east-2  |  No  | 
|   `umask`   |  The `umask` used by the `cfn-hup` daemon. This value can be specified with or without a leading 0. In both cases, it's interpreted as an octal number (similar to the Linux `umask` command). This parameter has no effect on Windows. *Type*: Octal integer between `0` and `0777` *Default*: `022`, version 1.4–22 and higher. The default value of `022` masks group and world write permissions, so files created by the `cfn-hup` daemon aren't group or world writable by default. The default value for versions 1.4 –21 and earlier is `0`, which masks nothing.  |  No  | 
|   `interval`   |  The interval used to check for changes to the resource metadata in minutes. *Type*: Integer *Default*: `15`  |  No  | 
|   `verbose`   |  Specifies whether to use verbose logging. *Type*: Boolean *Default*: `false`  |  No  | 

## `hooks.conf` configuration file
<a name="cfn-hup-hook-file"></a>

The user actions that the `cfn-hup` daemon calls periodically are defined in the `hooks.conf` configuration file. The `hooks.conf` file uses the following *format*:

```
[hookname]
triggers=post.add or post.update or post.remove
path=Resources.<logicalResourceId> (.Metadata or .PhysicalResourceId)(.<optionalMetadatapath>)
action=<arbitrary shell command>
runas=<runas user>
```

When the operation is run, it is run in a copy of the current environment (that `cfn-hup` is in), with `CFN_OLD_METADATA` set to the previous metadata value specified by path, and `CFN_NEW_METADATA` set to the current value.

The hooks configuration file is loaded at `cfn-hup` daemon start up only, so new hooks will require the daemon to be restarted. A cache of previous metadata values is stored at `/var/lib/cfn-hup/data/metadata_db`— you can delete this cache to force `cfn-hup` to run all `post.add` actions again.


| Name | Description | Required | 
| --- | --- | --- | 
|   `hookname`   |  A unique name for this hook. *Type*: String  |  Yes  | 
|   `triggers`   |  A comma-delimited list of conditions to detect. *Valid values*: `post.add`, `post.update`, or `post.remove` *Example*: `post.add, post.update`  |  Yes  | 
|   `path`   |  The path to the metadata object. Supports an arbitrarily deep path within the Metadata block.  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/cfn-hup.html)  |  Yes  | 
|   `action`   |  An arbitrary shell command that is run as given.  |  Yes  | 
|   `runas`   |  A user to run the commands as. `cfn-hup` uses the su command to switch to the user.  |  Yes  | 

## `hooks.d` directory
<a name="cfn-hup-hooks-dir"></a>

To support composition of several applications deploying change notification hooks, `cfn-hup` supports a directory named `hooks.d` that is located in the hooks configuration directory. You can place one or more additional hooks configuration files in the `hooks.d` directory. The additional hooks files must use the same layout as the `hooks.conf` file.

The `cfn-hup` daemon parses and loads each file in this directory. If any hooks in the `hooks.d` directory have the same name as a hook in `hooks.conf`, the hooks will be merged (meaning `hooks.d` will overwrite `hooks.conf` for any values that both files specify).

## Examples
<a name="cfn-hup-examples"></a>

In the following examples, CloudFormation triggers the `cfn-auto-reloader.conf` hooks file when you change the `AWS::CloudFormation::Init` resource that is associated with the `LaunchConfig` resource.

### JSON
<a name="cfn-hup-example.json"></a>

```
...
    "LaunchConfig": {
      "Type" : "AWS::AutoScaling::LaunchConfiguration",
      "Metadata" : {
        "AWS::CloudFormation::Init" : {
...
              "/etc/cfn/hooks.d/cfn-auto-reloader.conf": {
                "content": { "Fn::Join": [ "", [
                  "[cfn-auto-reloader-hook]\n",
                  "triggers=post.update\n",
                  "path=Resources.LaunchConfig.Metadata.AWS::CloudFormation::Init\n",
                  "action=/opt/aws/bin/cfn-init -v ",
                          "         --stack ", { "Ref" : "AWS::StackName" },
                          "         --resource LaunchConfig ",
                          "         --configsets wordpress_install ",
                          "         --region ", { "Ref" : "AWS::Region" }, "\n",
                  "runas=root\n"
                ]]},          
                "mode"  : "000400",
                "owner" : "root",
                "group" : "root"
              }
...
```

### YAML
<a name="cfn-hup-example.yaml"></a>

```
...
  LaunchConfig:
    Type: AWS::AutoScaling::LaunchConfiguration
    Metadata:
      AWS::CloudFormation::Init:
...
            /etc/cfn/hooks.d/cfn-auto-reloader.conf:
              content: !Sub |
                [cfn-auto-reloader-hook]
                triggers=post.update
                path=Resources.LaunchConfig.Metadata.AWS::CloudFormation::Init
                action=/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource LaunchConfig --configsets wordpress_install --region ${AWS::Region}
                runas=root
              mode: "000400"
              owner: "root"
              group: "root"
...
```

## Related resources
<a name="cfn-hup-related-resources"></a>

You can also visit our GitHub repository to download [sample templates](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html#sample-templates) that use `cfn-hup`, including the following templates.
+  [InstanceWithCfnInit.yaml](https://github.com/aws-cloudformation/aws-cloudformation-templates/blob/main/EC2/InstanceWithCfnInit.yaml) 
+  [AutoScalingRollingUpdates.yaml](https://github.com/aws-cloudformation/aws-cloudformation-templates/blob/main/AutoScaling/AutoScalingRollingUpdates.yaml) 