John
John

Reputation: 11921

How do I tag an EBS volume using AWS CDK?

I am creating an instance with an EBS volume using AWS CDK:

BlockDevice durableStorage = BlockDevice.builder()
                                        .deviceName("/dev/sdf")
                                        .volume(BlockDeviceVolume.ebs(
                                                    DURABLE_STORAGE_GB,
                                                    EbsDeviceOptions.builder()
                                                                    .deleteOnTermination(true)
                                                                    .encrypted(true)
                                                                    .volumeType(EbsDeviceVolumeType.GP2)
                                                                    .build()))
                                                .build();

Instance instance = new Instance(
                this,
                "MyInstance",
                InstanceProps.builder()
                             /* other config here */
                             .blockDevices(List.of(durableStorage))
                             .build());

How do I tag the EBS volume? The Tag static method requires a Construct, which I can't find on the BlockDevice, e.g. I want to do something like this:

Tag.add(durableStorage, "cdk", "true");

Upvotes: 4

Views: 2724

Answers (2)

Wingjam
Wingjam

Reputation: 802

The only working solution I found so far is using EC2 User Data to tag the attached EBS volume:

import * as ec2 from '@aws-cdk/aws-ec2'

// ...

const userData = ec2.UserData.forLinux()
userData.addCommands(
  // Tag volume
  'AWS_INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id)',
  `ROOT_DISK_ID=$(aws ec2 describe-volumes --region ${props.region} --filter "Name=attachment.instance-id, Values=\${AWS_INSTANCE_ID}" --query "Volumes[].VolumeId" --out text)`,
  `aws ec2 create-tags --region ${props.region} --resources \${ROOT_DISK_ID} --tags Key=${tagKey},Value=${tagValue}`,
)

const ec2Instance = new ec2.Instance(this, 'ec2-instance', {
  // ...
  userData: userData,
})

Upvotes: 1

Milan Gatyás
Milan Gatyás

Reputation: 2797

It looks like it is not possible to tag volume directly with CDK constructs. Maybe tag will be propagated to the volume when instance is tagged.

Tagging the volumes directly looks to be however achievable by using CloudFormation resources - https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.CfnInstance.html

Upvotes: 0

Related Questions