How can I create an EC2 instance in Pulumi with a non-default VPC?

541 views Asked by At

I am trying to create AWS infrastructure (VPC, Security Groups, EC2 instance) in Pulumi, but I've hit a road block. Namely:

I am using Pulumi to create a VPC, which automatically creates subnets, gateways and routing tables by default, which is fine for my purposes. After this, I create Security groups. All is well up to this point and there are no issues. However, when I try to create an EC2 instance, I want to create it on the VPC I just created and since it's dynamic, I won't know the VPC and subnet ids until they are created.

When creating the EC2 instance, you need to tell it which subnet to create the instance on. This is where I start having trouble. The VPC I create provides a Promise<Output[]> of subnet IDs, however I can't access the subnet IDs to even get one - nothing is returned.

It's obvious I'm overlooking something important, but I can't seem to find ANY examples of this flow in any documentation or examples. Here's the 2 functions I am using to construct the VPC and attempt to get the subnets.

Create VPC:

createVPC() {
        const CIDRBLOCK = "10.0.0.0/16"
        const NUM_AVAILABILITY_ZONES = 2
    
        const vpc = new awsx.ec2.Vpc(this.basename + "_vpc", {
            cidrBlock: CIDRBLOCK,
            numberOfAvailabilityZones: NUM_AVAILABILITY_ZONES,
            subnets: [{type : "public"}, {type : "private"}],
        });
        return vpc;
    }

Subnet lookup:

private async waitForPromise(prom : Promise<Output<string>[]>) {
        await prom;
        console.log((await prom).toString());
        return prom;
    }

    private getSubnet(vpc : awsx.ec2.Vpc) {
        if (this.subnetID === "") {
            let subnetids = this.waitForPromise(vpc.privateSubnetIds)
            subnetids.then((ids) => { ids[0].apply((id) => this.subnetID = id) });
        }
        return this.subnetID;
    }

Any thoughts? For context, I'm relatively new to Typescript as well, so I may just not understand some concept. Feedback there is also welcome.

1

There are 1 answers

0
Mitch G On BEST ANSWER

Using the pulumi.output method worked for me:

      const fleetvpc = new awsx.ec2.Vpc(vpcName, {
        cidrBlock : vpcCidr,
        subnets: [ 
            {type: "public"},
        ],
        numberOfNatGateways: 0, 
        tags: { "Name": vpcName}
    });

    const az1_pub_subnet = pulumi.output(fleetvpc.publicSubnetIds.then(ids => ids[0])) 
    const az2_pub_subnet = pulumi.output(fleetvpc.publicSubnetIds.then(ids => ids[1]))