EC2 User Data
Feature in Amazon Web Services (AWS) that allows you to automate the initialization of an EC2 instance when it is launched. It enables you to provide custom scripts or commands that run automatically on the first boot of the instance.
When using the AWS CLI or SDK, user data is typically base64 encoded automatically. However, when entering user data directly in the console, it is assumed to be plain text.
The user data only runs once when the instance is first started. To run the same script on every reboot, you would need to modify the script to re-run itself or configure a cron job (Linux) or task scheduler (Windows).
For Windows EC2 instances, user data can be a PowerShell script.
Using aws cli:
aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 --instance-type t2.micro --user-data file://my-user-data-script.sh
EC2 Metadata
IMDSv2 (Instance Metadata Service Version 2) is an enhanced version of the Instance Metadata Service (IMDS) used by Amazon EC2 instances to retrieve instance metadata, such as instance IDs, IAM role credentials, and network details.
Get Token:
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
Access endpoint:
curl http://169.254.169.254/latest/meta-data/instance-id -H "X-aws-ec2-metadata-token: $TOKEN"