Reputation: 13402
My CloudFormation template has gotten pretty long. One reason is because my AWS::CloudFormation::Init
section has gotten pretty huge. This is a very small sample of what I have:
"ConfigDisk": {
"commands": {
"01formatFS": {
"command": "/sbin/mkfs.ext4 /dev/xvdf"
},
"02mountFS": {
"command": "/bin/mount /dev/xvdf /var/lib/jenkins"
},
"03changePerms": {
"command": "/bin/chown jenkins:jenkins /var/lib/jenkins"
},
"04updateFStab": {
"command": "/bin/echo /dev/xvdf /var/lib/jenkins ext4 defaults 1 1 >> /etc/fstab"
}
}
},
Wouldn't it be better to just put this into the userdata section as a bunch of commands?
/sbin/mkfs.ext4 /dev/xvdf
/bin/mount /dev/xvdf /var/lib/jenkins
/bin/chown jenkins:jenkins /var/lib/jenkins
/bin/echo /dev/xvdf /var/lib/jenkins ext4 defaults 1 1 >> /etc/fstab
What are the benefits of leaving this in the Init over userdata?
Upvotes: 23
Views: 11347
Reputation: 47971
A major benefit of AWS::CloudFormation::Init
over UserData
is that the former is updatable -- if you modify the AWS::CloudFormation::Init
section, CloudFormation will update your EC2 instance in place, whereas if you modify the UserData
property of an EC2 resource in your template and update your stack, CloudFormation will replace that EC2 instance.
This is handy, for example, if you want to update the packages you have installed on your EC2 instance without recreating it.
Upvotes: 33
Reputation: 419
Thinking of CFN-INIT as a bespoke version of user-data is 100% wrong - CFN-INIT has power MUCH beyond userdata.
userdata is procedural based , Run command
A
B
C
D
CFN-INIT is desired state based.
Make A like this
Make B like this.
CFN-INIT can be run again - e.g during stack updated, to update config, or specifically bring a state to a desired 'state' - userdata because of its procedural background cant - it isnt guarenteed to be able to run a second time and move an instance to a certain state.
You can run commands in CFN-INIT - i.e it can also be procedural - but it can also be state based.. i.e /tmp/something.txt has THIS content. Or service X is started. 'Apache Installed' which knows the diff between no apache, most recent apache, a version of apache - and it acts accordingly.
Upvotes: 13
Reputation: 10566
The biggest advantage is that you're not polluting the user data if you are also using that for some other purpose. So this lives in the CloudFormation Stack vs living in each of the Instance user data.
cfn-init basically pulls this data from CloudFormation and just runs the command.
Depending how this complicated is you might consider baking this into the AMI and just calling it in one command vs a series of commands.
Another difference is that cfn-init has to be baked into the AMI you're using to launch the machine. That's the case for pretty much any AMI nowadays so not really a cause of major concern.
Upvotes: 8