https://pulumi.com logo
Title
d

dry-beach-58138

04/28/2023, 5:43 AM
Hello Does Pulumi have any best practice for resource reference by instance name in different program script, and using depends_on in Resource options I just know I can using stack reference for get output, but no ideas to get resource instance for depends_on example codes as below:
# program_vpc.py
import pulumi
from pulumi_aws import ec2

# Create multiple VPCs
vpc1 = ec2.Vpc("vpc1", cidr_block="10.0.0.0/16")
vpc2 = ec2.Vpc("vpc2", cidr_block="10.1.0.0/16")

# Export VPC IDs
pulumi.export("vpc1_id", vpc1.id)
pulumi.export("vpc2_id", vpc2.id)
# program_subnet.py
import pulumi
from pulumi import ResourceOptions
from pulumi_aws import ec2
from pulumi import StackReference

# Get VPC instance
vpc1 = ???
vpc2 = ???

# Get VPC IDs
stack_ref = StackReference(f"{org}/my-first-app/{stack}")
vpc1_id = stack_ref.get_output("vpc1_id")
vpc2_id = stack_ref.get_output("vpc2_id")

# Create subnets
subnet1_vpc1 = ec2.Subnet(
    "subnet1_vpc1",
    cidr_block="10.0.1.0/24",
    vpc_id=vpc1_id,
    # vpc_id=vpc1.id
    opts=ResourceOptions(depends_on=[vpc1]))
subnet2_vpc1 = ec2.Subnet(
    "subnet2_vpc1",
    cidr_block="10.0.2.0/24",
    vpc_id=vpc1_id,
    # vpc_id=vpc1.id
    opts=ResourceOptions(depends_on=[vpc1]))
subnet1_vpc2 = ec2.Subnet(
    "subnet1_vpc2",
    cidr_block="10.1.1.0/24",
    vpc_id=vpc2_id,
    # vpc_id=vpc2.id
    opts=ResourceOptions(depends_on=[vpc2]))
subnet2_vpc2 = ec2.Subnet(
    "subnet2_vpc2",
    cidr_block="10.1.2.0/24",
    vpc_id=vpc2_id,
    # vpc_id=vpc2.id
    opts=ResourceOptions(depends_on=[vpc2]))

# Export subnet IDs
pulumi.export("subnet1_vpc1_id", subnet1_vpc1.id)
pulumi.export("subnet2_vpc1_id", subnet2_vpc1.id)
pulumi.export("subnet1_vpc2_id", subnet1_vpc2.id)
pulumi.export("subnet2_vpc2_id", subnet2_vpc2.id)
c

creamy-monkey-35142

05/03/2023, 8:06 AM
I not sure how Pulumi handle this case, I did my trick by convert
program_subnet.py
into Class and create a function like `vpc_subnet(vpc_id,cidr)`then at program_vpc.py just import this class and call function after vpc create
other way is using
pulumi.export("vpc1_id", vpc1.id)
pulumi.export("vpc2_id", vpc2.id)
as array export, so in next python file you can refer value without write so many export line