https://pulumi.com logo
#general
Title
# general
w

witty-spring-28765

05/09/2020, 8:13 PM
Hello. I am new to Pulumi Python. I have a small query. How do I search for existing subnets from a VPC and then choose a particular Subnet to the EC2 in the pulumi code? Currently I have to login to the console and then get the Subnet ID from there.
b

billowy-army-68599

05/09/2020, 8:54 PM
Hey! Welcome! You can use
ec2.get_subnet_ids
for this, here's a hastily thrown together example
Copy code
import pulumi
from pulumi_aws import ec2

# get the default vpc
vpc = ec2.get_vpc(default=True)

# get subnets associated with the default vpc
subnets = ec2.get_subnet_ids(vpc_id=vpc.id)

export the subnet ids associated
pulumi.export("subnets", subnets.ids)
w

witty-spring-28765

05/10/2020, 10:31 AM
Thanks Jaxxstrom. I want to run through all the VPCs so I will try without the default. But if the subnet exists can we quit the pulumi build or is that not best practice. I am struggling to find how to implement IaC based on certain criteria or do they have to be immutable(as best practice). The reason being, I will be deploying my service over a shared infra supported by another team.
Tried this:
Copy code
import pulumi
from pulumi_aws import ec2
# get the default vpc
vpc = ec2.get_vpc(default=False)
for i in vpc:
    subnets = ec2.get_subnet_ids(vpc_id=i.id)
    pulumi.export("subnets", subnets.ids)
Error:
Exception: invocation of awsec2/getVpcgetVpc returned an error: invoking awsec2/getVpcgetVpc: multiple VPCs matched; use additional constraints to reduce matches to a single VPC
b

billowy-army-68599

05/10/2020, 7:10 PM
sorry for the delay! ideally in this situation, if your VPC doesn't exist, you should create it. In this case, you probably want to filter the VPCs based on something like the tags assigned to it.
w

witty-spring-28765

05/11/2020, 9:18 AM
no worries on the delay Jaxxstorm.Many thanks for the help. So does the ec2.getvpc return only a single VPC? I wanted to run through all the VPC..I understand that I will have to get a tag assigned to my project.
b

billowy-army-68599

05/11/2020, 3:18 PM
You can use
get_vpcs
to get all the VPCs in an account and loop through them https://www.pulumi.com/docs/reference/pkg/python/pulumi_aws/ec2/#pulumi_aws.ec2.get_vpcs
6 Views