How can I automatically attach a persistent secondary EBS volume to a new EC2 Linux Spot Instance at boot?

Last updated: 2021-10-18

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?

Short description

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.

Prerequisite

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.

Resolution

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:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ec2:AttachVolume",
                "ec2:DetachVolume"
            ],
            "Resource": [
                "arn:aws:ec2:*:*:instance/*",
                "arn:aws:ec2:*:*:volume/vol-xxxxxxxxxxxx"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "ec2:DescribeVolumes",
            "Resource": "arn:aws:ec2:*:*:volume/vol-xxxxxxxxxxxx"
        }
    ]

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.

#!/bin/bash
      OUTPUT=$(curl http://169.254.169.254/latest/meta-data/instance-id)
      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.


Did this article help?


Do you need billing or technical support?