see sharper
see sharper

Reputation: 12055

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

I'd like to attach an EC2 volume to an EC2 instance I'm creating, but I 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?

Upvotes: 4

Views: 6620

Answers (3)

NK Rao
NK Rao

Reputation: 53

You can use AWS SDK for this.

For ex:

import ec2 from 'aws-sdk/clients/ec2';
const ec2Clinet = new ec2();
    ec2Clinet.attachVolume({
      VolumeId: vol.volumeId,
      InstanceId: instance.instanceId,
      Device: '/dev/sdh',
    }, (err, _data) => {
      if (err) {
        console.log(err);
      }
      else {
        console.log("Volume attached successfully!");
      }
    })

Upvotes: 0

Nobe's
Nobe's

Reputation: 166

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

Upvotes: 3

Chun
Chun

Reputation: 519

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)
        }
      ]

    });

Upvotes: 3

Related Questions