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

2 minute read
0

I want to use a user data script to automatically attach a persistent secondary Amazon Elastic Block Store (Amazon EBS) volume to my new Amazon Elastic Compute Cloud (Amazon EC2) Linux Spot Instance at boot.

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 to create the Spot Instance request.

Prerequisite

Create or use an existing AWS Identity and Access Management (IAM) role that has at least attach-volume access for Amazon EC2. Attach the role to the launch template.

Resolution

Configure a launch template with an IAM role and user data script

  1. Open the Amazon EC2 console.

  2. Choose Launch templates, and then choose Create launch template.

  3. Choose the instance Amazon Machine Image (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. Choose Advanced details.

  7. Add the IAM role that has attach-volume access.
    Example IAM policy:

    
    {
        "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 the following user data script to the template. Replace region and volume-id with your values:

    #!/bin/bash
    INSTANCEID=$(TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` && curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id)
    aws ec2 attach-volume --volume-id vol-xxxxxxxxxxxx --device /dev/xvdf --instance-id $INSTANCEID --region eu-west-1

Use the launch template to create a Spot Instance request

  1. Open the Amazon EC2 console.
  2. Choose Spot Instance, and then choose Request Spot Instance.
  3. Choose Launch templates, and then select your launch template.
  4. Choose the same Availability Zone as the EBS volume.
  5. Choose Create Spot Instance request.

After the Spot Instance request completes, the persistent secondary EBS volume is automatically attached to the new Spot Instance at boot.

AWS OFFICIAL
AWS OFFICIALUpdated 10 months ago