2
votes

How do I pass parameters input data to userdata in AWS cloudformation. Example: I have a parameter EnvType where I will pass "qa" as input to this parameter while running CFT. I want this parameter value "qa" to be read and pass to userdata so that I can write it it to instance disk.

Parameters: {
    "EnvType": {
        "Description": "Environment type",
        "Type": "String",
        "AllowedValues": [
            "prod",
            "qa"
        ]
    }

I tried using this in user data as:

export STACK_TYPE='",
{
"Ref": "EnvType"
},
"'\n",
"echo \"$STACK_TYPE\" > stacktypes\n

Where I wanted to append this input of EnvType into a file named stacktypes in the instance.

2

2 Answers

1
votes

You have to use Fn::Join to actually "join" the user data strings with results from other intrinsics function of CloudFormation (such as Ref). Here's an exemple of how it's done:

...  
  "MyInstance": {
    "Type": "AWS::EC2::Instance",
    "Properties": {
      "UserData": {
        "Fn::Base64": {
          "Fn::Join": [
            "",
            [
              "#cloud-config\n\nrepo_upgrade: all\n\n\nwrite_files:\n- path: /root/init.sh\n  owner: root:root\n  permissions: '0755'\n  content: |\n    #!/bin/bash\n\n    EC2_INSTANCE_ID=`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id`\n    aws cloudformation signal-resource --stack-name ",
              {
                "Ref": "AWS::StackName"
              },
              " --status SUCCESS --logical-resource-id AutoScalingGroup --unique-id $EC2_INSTANCE_ID --region ",
              {
                "Ref": "AWS::Region"
              }
            ]
          ]
        }
      }
      ...
    }
  }
...

This can be a tedious task, we developed a tool internally to tackle the generation of UserData but I know there are open source tools that can help (ex: https://github.com/cloudtools/troposphere).

1
votes

You can pass/append the stack parameter into a file in your instance. If you have parameter like this,

Parameters: {
"EnvType": {
    ...
}

You can try to add the UserData below into your instance properties.

   "Properties": {
      ...
      "UserData": {
        "Fn::Base64": {
          "Fn::Join": [
            "",
            [
              "#!/bin/bash -xe\",
              "echo ",
              {
                "Ref": "EnvType"
              },
              " >> /path/yourfile\n"
            ]
          ]
        }
      }
    }

This will append the EnvType parameter into file /path/yourfile in your instance.