7
votes

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?

2
what is the difference between your so called "userdata file" and the template itself? - Vladimir Mukhin
Can you explain your use case some more? - stevepkr84
Userdata scripts for say cloudinit can be fairly long shell scripts. Editing them inline in the template can be a royal pain. It is nice to have them in their own file and inject it into the template when creating it. - John Eikenberry

2 Answers

19
votes

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)
1
votes

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).