froinds
froinds

Reputation: 225

AWS::CloudFormation::Init not executing commands in metadata

This is my template with a test command in the metadata. I can't figure out why the command doesn't get executed. It's supposed to save a string to a file in /tmp. The machine is Ubuntu 16.04 with cloud-init installed. In UserData I install the helper scripts and execute cfn-init.

Thanks for your help.

{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Metadata": {
    "AWS::CloudFormation::Designer": {
      "2af5b799-f6bf-7f20-a6eb-943274f18373": {
        "size": {
          "width": 60,
          "height": 60
        },
        "position": {
          "x": 326,
          "y": 118
        },
        "z": 0,
        "embeds": []
      }
    }
  },
  "Resources": {
    "EC2I3WADD": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "ImageId": "ami-c60b90d1",
        "KeyName": "CF-KEY",
        "InstanceType": "t2.micro",
        "UserData": {
          "Fn::Base64": {
            "Fn::Join": [
              "",
              [
                "#!/bin/bash -xe\n",
                "apt-get -y install python-setuptools\n",
                "mkdir aws-cfn-bootstrap-latest\n",
                "curl https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz | tar xz -C aws-cfn-bootstrap-latest --strip-components 1\n",
                "easy_install aws-cfn-bootstrap-latest\n",
                "/usr/local/bin/cfn-init --stack ",
                {
                  "Ref": "AWS::StackName"
                },
                " --resource WebServer",
                " --region ",
                {
                  "Ref": "AWS::Region"
                },
                "\n"
              ]
            ]
          }
        }
      },
      "Metadata": {
        "AWS::CloudFormation::Designer": {
          "id": "2af5b799-f6bf-7f20-a6eb-943274f18373"
        },
        "AWS::CloudFormation::Init": {
          "config": {
            "commands": {
              "test": {
                "command": "echo \"$MAGIC\" > /tmp/test.txt",
                "env": {
                  "MAGIC": "I come from the environment!"
                }
              }
            }
          }
        }
      }
    }
  }
}

Upvotes: 1

Views: 3299

Answers (1)

Jason
Jason

Reputation: 2105

The issue is likely being cause by an incorrect --resource argument being passed to the cfn-init command within your UserData. This argument should match the logical resource name of the resource containing the MetaData, in your case EC2I3WADD.

"/usr/local/bin/cfn-init --stack ", { "Ref": "AWS::StackName" }, " --resource EC2I3WADD", " --region ", { "Ref": "AWS::Region" }

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-init.html

Upvotes: 2

Related Questions