How to create EBS only if targeted EBS does not exist only in AWS CDK?

Viewed 275

Note that there is a static method named fromVolumeAttributes in @aws-cdk/aws-ec2.Volume

I have set removal policy for my EBS to retain. I want CDK to use the same EBS in case I delete the whole stack and decided to recreate the same CloudFormation stack again for a specific EC2 instance.

Here is the code I used to create an instance

function createOdooWebInstance(
    scope: Construct,
    instanceName: string,
    ebsSize: number,
    extraOptions: Optional<InstanceProps>
): Instance {
    const volume = new Volume(scope, instanceName + ' EBS', {
        encrypted: true,
        availabilityZone: config.region + 'b',
        removalPolicy: RemovalPolicy.RETAIN,
        size: Size.gibibytes(ebsSize),
    });

    const instance = new Instance(
        scope, instanceName,
        Object.assign({}, {
            vpc: NETWORKING.VPC,
            machineImage: new GenericLinuxImage({
                // Ubuntu 18
                [config.region]: config.ubuntu18AMI,
            }),
            instanceType: config.ec2WebInstanceType,
            vpcSubnets: {
                subnets: [NETWORKING.PUBLIC_SUBNET_2B]
            },
            // See [User data note]
            userData: UserData.forLinux({
                shebang:
                // language= bash
                    `#!/bin/sh
    sudo sed -i "$line{s/#Port 22/Port 22/g}" /etc/ssh/sshd_config
    sudo service sshd restart
    `
            }),
        }, extraOptions)
    );

    volume.grantAttachVolumeByResourceTag(instance.grantPrincipal, [instance]);

    const targetDevice = '/dev/sda1';
    instance.userData.addCommands(
        //Retrieve the instance ID from the folder name in /var/lib/cloud/instances
        `InstanceID=$(ls /var/lib/cloud/instances)`,
        // Attach the volume to /dev/xvdz
        `aws --region ${Stack.of(scope).region} ec2 attach-volume --volume-id ${volume.volumeId} --instance-id $InstanceID --device ${targetDevice}`,
        // Wait until the volume has attached
        `while ! test -e ${targetDevice}; do sleep 1; done`
        // The volume will now be mounted. You may have to add additional code to format the volume if it has not been prepared.
    );

    return instance;
}
0 Answers
Related