To replace a broken server on its own, AWS needs to know how to build one. A launch template is that recipe: image, type, security groups, instance profile and user data, under one name.
User data is base64
run-instances --user-data encodes the script for you. A template takes it already in base64, and refuses plain text with InvalidUserData.Malformed. base64 -w0 encodes a file on one line:
UD=$(base64 -w0 app.sh)aws ec2 create-launch-template --launch-template-name web-lt --launch-template-data "ImageId=$AMI,InstanceType=t3.micro,SecurityGroupIds=$WEB_SG,UserData=$UD"$AMI and $WEB_SG are as in Chapter 3. IamInstanceProfile={Name=web-profile} in the same list gives the instances a role. To see the script again, decode it: aws ec2 describe-launch-template-versions --launch-template-name web-lt --versions 1 --query "LaunchTemplateVersions[0].LaunchTemplateData.UserData" --output text | base64 -d.
Versions
A version never changes. A new script is a new version, starting from an old one with only what differs:
aws ec2 create-launch-template-version --launch-template-name web-lt --source-version 1 --launch-template-data "UserData=$UD"aws ec2 describe-launch-template-versions --launch-template-name web-lt --query "LaunchTemplateVersions[].[VersionNumber,DefaultVersion]" --output tableWhich version a group launches
| It names | It launches | After you create version 3 |
|---|---|---|
| $Latest | the newest | version 3 |
| $Default | the default version | the old default, until you change it |
| 2 | version 2 | version 2, forever |
aws ec2 modify-launch-template --launch-template-name web-lt --default-version 2Running instances never change when the template does: a version only matters at the next launch.