Summary of CloudFormation Helper Scripts Training
- Problems with User Data:
- Inflexibility with large instance configurations.
- Difficulty in evolving EC2 instance state without termination.
- Readability issues with user data scripts.
- Uncertainty about the success of user data scripts.
- Solution: CloudFormation Helper Scripts:
- Python scripts included with Amazon Linux AMIs or installable via
yum or dnf.
- Important scripts include
cfn-init, cfn-signal, cfn-get-metadata, and cfn-hup.
- Focus on
cfn-init:
- Retrieves and interprets resource metadata.
- Installs packages, creates files, and starts services on EC2 instances.
- Makes complex EC2 configurations readable.
- Logs are stored in
/var/log/cfn-init.log.
- CloudFormation Init Block:
- Part of the metadata block within a resource.
- Components include packages, groups, users, sources, files, commands, and services.
- Example of
cfn-init Usage:
- EC2 instance queries CloudFormation service for init data.
- User data script updates and runs
cfn-init with StackId, resource name, and region.
- Metadata block contains CloudFormation init block with configuration details.
- Instance creation and configuration are more readable and manageable.
- Debugging and Logs:
- Check
/var/log/cloud-init.log for basic run information.
- Detailed command output and errors are logged in
/var/log/cfn-init.log and cfn-init-cmd.log.
- Cleanup:
- Remember to delete the stack after the training.
Example Configuration in Markdown
Resources:
MyInstance:
Type: AWS::EC2::Instance
Metadata:
AWS::CloudFormation::Init:
configSets:
setup:
- install_server
install_server:
packages:
yum:
httpd: []
files:
"/var/www/html/index.html":
content: |
Hello world!
mode: 000644
owner: root
group: root
services:
sysvinit:
httpd:
enabled: true
ensureRunning: true
Properties:
# ... other properties ...
UserData:
Fn::Base64: !Sub |
#!/bin/bash -xe
yum update -y aws-cfn-bootstrap
/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource MyInstance --configsets setup --region ${AWS::Region}
/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource MyInstance --region ${AWS::Region}