What You'll Learn
You'll learn how to use the Fn::Base64 intrinsic function to encode user data scripts that automatically configure EC2 instances when they launch.
Why Base64 Encoding for UserData?
When you launch an EC2 instance, you often want it to run initialization scripts—installing software, configuring services, or downloading files. AWS expects this UserData to be Base64-encoded before it's passed to the instance.
Think of Base64 encoding like sealing a letter in an envelope before mailing it. The content inside stays the same, but it's packaged in a format that travels safely through AWS's systems without corruption.
How Fn::Base64 Works
The Fn::Base64 function takes a string (your script) and encodes it into Base64 format automatically. You don't need to encode it manually—CloudFormation handles this for you.
Basic Pattern
In your EC2 resource's UserData property, wrap your script with Fn::Base64:
Resources:
MyEC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-0abcdef1234567890
InstanceType: t2.micro
UserData:
Fn::Base64: |
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
The | symbol lets you write multi-line scripts cleanly in YAML. CloudFormation encodes this entire bash script before sending it to the EC2 instance.
Combining with Other Functions
You can nest Fn::Base64 with Fn::Sub to inject parameters or pseudo parameters into your scripts:
UserData:
Fn::Base64:
Fn::Sub: |
#!/bin/bash
echo "Stack Name: ${AWS::StackName}" > /var/www/html/index.html
Key Takeaway: Fn::Base64 encodes your UserData scripts into the Base64 format required by EC2, enabling automatic instance initialization through CloudFormation templates.