10

I have a shell script(userdata file) and wondering is there a CLI command parameter that allows user to launch Cloudformation stack with userdata file?

tset
  • 433
  • 3
  • 12
  • 23

2 Answers2

21

Inside your template, use a CloudFormation parameter for the instance userdata:

{
  "Parameters": {
    "UserData": {
      "Type": "String"
    }
  },
  "Resources": {
    "Instance": {
      "Type" : "AWS::EC2::Instance",
      "Properties" : {
        "UserData" : { "Ref" : "UserData" },
        ...
      }
    },
    ...
  }
}

Assuming you're using a Unix-like command line environment, create your stack like this:

aws cloudformation create-stack --stack-name myStack \
    --template-body file://myStack.json \
    --parameters ParameterKey=UserData,ParameterValue=$(base64 -w0 userdata.sh)
ataylor
  • 64,891
  • 24
  • 161
  • 189
  • Hi Ataylor, this is exactly what I was looking for. What is the command for Windows? – tset Jul 05 '16 at 22:59
  • 1
    You can use the same command in Windows with cygwin or git bash. If you use cmd.exe, you'll need to find a utility program to base64 encode the script, I think. PowerShell should be able to do this as well, but I'm not certain about the details. – ataylor Jul 08 '16 at 16:55
  • How could I add the --template-body in case we create the stack from the AWS console instead of from a command? – FVod Oct 05 '17 at 10:34
  • 1
    @ataylor, what if I have variables in userdata.sh, defined in the "Parameters" section of the template, that I want to be substituted by CloudFormation? For instance, I have a following variable in the script: ${AWS::StackName} – antonbormotov Jun 13 '19 at 11:29
1

Your user-data must exist in the CloudFormation template when you create the stack. You can write a script to read in your user-data from the file and insert it into the CloudFormation stack prior to creating the stack. Note that you may need to make formatting changes to the userdata (see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-userdata).

jzonthemtn
  • 3,344
  • 1
  • 21
  • 30