How to attach an EC2 volume to an EC2 instance using AWS CDK

Viewed 2686

I'd like to attach an EC2 volume to an EC2 instance I'm creating, but can't figure out how to do it:

const vol = new ec2.Volume(this, 'vol', {
  availabilityZone: 'ap-southeast-2a',
  size: Size.gibibytes(100),
});

const instance = new ec2.Instance(this, 'my-instance', {
  instanceName: 'my-instance',
  vpc: vpc,
  // how to attach 'vol' as a block device here?
  blockDevices: [{ deviceName: '/dev/sdf', volume: { ebsDevice: { deleteOnTermination: false, volumeSize: 1 } } }],
  //... more props
});

This code works, though vol is not attached as a block device. How can I achieve this?

2 Answers

Using blockDevices I don't see a convenient way of mounting, formatting, and then editing '/etc/fstab' file.

I think your best bet would be to create a userData script using the following method, the script would follow these steps

host.userData.addExecuteFileCommand({})

these are just the rough steps I need to put some logic into this script, for your windows machine use PowerShell.

### Initial steps to mount the volume  ###

mkfs -t xfs /dev/xvdf
yum install xfsprogs -y
mkdir /wddProjects
mount /dev/xvdf /wddProjects

### On Server reboot re-attach volume 
sudo cp /etc/fstab /etc/fstab.orig
blkid | egrep "/dev/xvdf: UUID="
echo "UUID=xxx  /wddProjects  xfs  defaults,nofail  0  2" >> /etc/fstab

Do you have to define the volume outside the instance? or does following is what you looking for?

const windows = ec2.MachineImage.latestWindows(ec2.WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_FULL_BASE);

    const host = new ec2.Instance(this, "server", {
      instanceType : ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3_AMD, ec2.InstanceSize.LARGE),
      availabilityZone : "ap-southeast-2a",
      machineImage : windows,
      vpc : vpc,
      vpcSubnets : {
        subnetType: ec2.SubnetType.PRIVATE
      },
      keyName : config.keyPairName,
      blockDevices: [
        {
          deviceName : "/dev/sda1",
          volume : ec2.BlockDeviceVolume.ebs(80)
        },
        {
          deviceName : "/dev/sdm",
          volume : ec2.BlockDeviceVolume.ebs(100)
        }
      ]

    });
Related