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?
Asked
Active
Viewed 1.1k times
10
-
what is the difference between your so called "userdata file" and the template itself? – Vladimir Mukhin Jul 05 '16 at 08:34
-
Can you explain your use case some more? – stevepkr84 Jul 05 '16 at 09:20
-
1Userdata 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 May 16 '17 at 22:04
2 Answers
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
-
1You 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