Pretty new to CDK for Terraform. I’m using it with Python. I want to create an instance inside a particular VPC.
Code I have now:
newInstance = Instance(self, 'pythondemo',
ami="ami-0a02ee601d742e89f",
instance_type="t2.micro",
availability_zone="us-east-1a",
associate_public_ip_address=True,
tags={"Name": "Python-Demo"},
user_data = user_data
)
To be able to create the instance in a particular VPC, I would like to find the VPC id based on the VPC name. I have already imported the VPC module as follows:
from imports.terraform_aws_modules.vpc.aws import TerraformAwsModulesVpcAws
I then also need to find out the subnets within that VPC.
Any idea how to determine the VPC id and subnet ids?
You could use the vpc data source with a name filter to find it. I believe the Python type is DataAwsVpc
.
From that you could use the subnet ids data source (DataAwsSubnetIds) to look up the subnet ids.
You could use that module to create a vpc in which case you could access its outputs to get the values you need. If you are using in a different stack, you could add as an output to that stack and import via remote state.
OK thanks. Will try that.
In the meantime tried some other stuff as well. Follow up question: how then to get the attributes of a VPC that has been created with CDK?
my_vpc = TerraformAwsModulesVpcAws(self,
id='vpc',
name ="test-vpc",
cidr = "10.0.0.0/16",
azs = ["eu-central-1a", "eu-central-1b", "eu-central-1c"],
public_subnets = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
)
newInstance = Instance(self, 'demo',
ami="ami-0a02ee601d742e89f",
instance_type="t2.micro",
availability_zone="eu-central-1a",
associate_public_ip_address=True,
tags={"Name": "Demo"},
user_data = user_data,
subnet_id =my_vpc.public_subnets[0]
)
I want to launch the instance in the newly created VPC.
According to the documentation here or here the public_subnets
return a list of ID’s but instead I’m getting back the following:
Error: Error launching source instance: InvalidSubnetID.NotFound: The subnet ID ‘10.0.101.0/24’ does not exist
I believe for Python the naming would be my_vpc.public_subnets_output
. Unfortunately there is a bug where the type of any output is a string, so you’ll need to add an override to get a single subnet.