Search code examples
typescriptamazon-web-servicesaws-cdkaws-nat-gateway

Why am I seeing InvalidInstanceID.Malformed in my NAT Gateway's Route?


I am trying to create a Stack using AWS CDK (in Javascript). In my stack, I would like to create a NAT gateway in a public subnet that is referenced by Route Table in my private subnet. Pretty standard stuff.

Below is a snippet of the relevant code I have to create the infra for this

// CREATE VPC & SUBNET
const vpc = new ec2.CfnVPC(this, `${applicationName}-vpc`, {
  cidrBlock: '10.1.0.0/16',
})

const publicSubnet1 = new ec2.PublicSubnet(this, `${applicationName}-public1`, {
  availabilityZone: availabilityZone1,
  cidrBlock: '10.1.0.0/20',
  vpcId: vpc.attrVpcId,
  mapPublicIpOnLaunch: true
})

// CREATE NAT GATEWAY
const webserverNatGatewayEIP = new ec2.CfnEIP(this, `${applicationName}-webserver-natgwEIP`)

const webserverNatGateway = new ec2.CfnNatGateway(this, `${applicationName}-webserver-natgw`, {
  subnetId: publicSubnet1.subnetId,
  allocationId: webserverNatGatewayEIP.attrAllocationId,
  tags: [{
    key: 'Name',
    value: `${applicationName}-webserver-natgw`
  }]
})

This is fine. However, when I try to create my route table and a route to that NAT gateway as follows:

// CREATE PRIVATE ROUTE TABLE
const webserverRouteTable = new ec2.CfnRouteTable(this, `${applicationName}-webserver-rtb`, {
  vpcId: vpc.attrVpcId
})

// not working, need to debug
const webserverRouteTableNatGWRoute = new ec2.CfnRoute(this, 'webserver-rt-natgw-route', {
  routeTableId: webserverRouteTable.attrRouteTableId,
  destinationCidrBlock: '0.0.0.0/0',
  instanceId: webserverNatGateway.attrNatGatewayId
})

I am seeing the following error message when I try to deploy my stack.

Invalid id: "nat-0cfe60af88b3df93a" (Service: AmazonEC2; Status Code: 400; Error Code: InvalidInstanceID.Malformed; Request
ID: 4ecbe914-6ead-4d05-bf8c-d87cd0c72654; Proxy: null)

I don't understand how the .attrXYZ call for instanceId could be malformed. I am using all over the rest of my infra and it has been working just fine as similar arguments.

I manually checked via the AWS console to see if that NAT Gateway id was incorrect, and it matches perfectly. I don't see why this is failing. I guessed perhaps that maybe the NAT gateway wasn't being created in time, so I added a dependency on it via

webserverRouteTableNatGWRoute.addDependency(webserverNatGateway)

but that didn't fix the error. Any ideas?


Solution

  • To answer the question directly, it is because the instanceId prop is for an EC2 instance ID. To point it to a NAT gateway, you need to pass the gateway ID to the natGatewayId prop instead.

    Like so:

    const webserverRouteTableNatGWRoute = new ec2.CfnRoute(this, 'webserver-rt-natgw-route', {
      routeTableId: webserverRouteTable.attrRouteTableId,
      destinationCidrBlock: '0.0.0.0/0',
      natGatewayId: webserverNatGateway.attrNatGatewayId // different prop name
    })