I want to use a user data script to automatically launch a persistent secondary Amazon Elastic Block Store (Amazon EBS) volume to my new Amazon Elastic Compute Cloud (Amazon EC2) Linux Spot Instance at boot. How do I do this?
To automatically attach a persistent secondary EBS volume to a new EC2 Linux Spot Instance at boot, add a user data script to an EC2 launch template. Use the template when configuring your Spot Instance Request.
Create or use an AWS Identity and Access Management (IAM) role that at a minimum has attach-volume access granted for Amazon EC2. This role will be attached to the launch template.
Step 1: Configure a launch template with an IAM Role and user data script
1. Open the Amazon EC2 console.
2. Select Launch Templates, and then select Create launch template.
3. Choose the instance AMI, type, and size. Or, choose an existing AMI.
4. Associate a key pair with the template.
5. Choose a subnet in the same Availability Zone as the EBS volume.
6. Select Advanced details.
7. Add the IAM role that at a minimum has attach-volume access granted, as shown in the following example:
8. Add a user data script to the template. The following is an example user data script. Replace the region and volume-id to match your environment.
aws ec2 attach-volume --volume-id vol-xxxxxxxxxxxx --device /dev/xvdf --instance-id $OUTPUT --region ap-southeast-1
Step 2: Configure a Spot Request using the launch template created in Step 1
1. Select Spot Instance, and then select Request Spot Instance.
2. Select Launch Templates, and then choose the Launch Template created in Step 1. All the information configured on the template auto-populates.
3. Choose the same Availability Zone as the EBS volume.
4. Select create Spot Request.
After the Spot request completes, the persistent secondary EBS volume is attached to the new Spot Instance automatically at boot.