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?
cfn-init can be used to retrieve and interpret resource metadata, install packages, create files, and start services. cfn-init helper script reads template metadata from the AWS::CloudFormation::Init key and acts accordingly to: Fetch and parse metadata from CloudFormation.
The cfn-hup helper is a daemon that detects changes in resource metadata and runs user-specified actions when a change is detected. This allows you to make configuration updates on your running Amazon EC2 instances through the UpdateStack API action.
Cfn-init is a set of helper scripts that interface with the CloudFormation stack and does two things. First, it reads how the instance should be initialized from the CloudFormation stack and executes it.
Configsets are a part of a CloudFormation template, so they can be written as YAML or JSON. The cfn-init script is pre-installed on the AmazonLinux2 distro. AWS packaged it up to make it easier to customize EC2 instances without having to take the additional step of installing a configuration management tool.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With