Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 669
see sharper Avatar asked Oct 12 '25 11:10

see sharper


1 Answers

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

    });
like image 95
Chun Avatar answered Oct 14 '25 20:10

Chun