https://pulumi.com logo
#golang
Title
# golang
s

salmon-account-74572

06/24/2020, 1:26 AM
Another question from a newcomer to Go: I'm trying to create a VPC in AWS with subnets in each AZ for that region. I have code that looks up the number of AZs in the region, and then I'm using a
for
loop to create a subnet in each AZ. The problem I'm having is this: how do I capture the subnet IDs as they are created? Code included in a thread below.
Here's the code that iterates through the AZs and creates a subnet in each AZ:
Copy code
// Create public subnets in the VPC
		pubSubnetIds := make([]string, numOfAZs)
		for idx := 0; idx < numOfAZs; idx++ {
			subnetAddr := (idx)*16
			subnetCidrBlock := fmt.Sprintf("%s.%d.0/23", vpcNetPrefix, subnetAddr)
			subnetArgs := &ec2.SubnetArgs {
				VpcId: vpc.ID(),
				AvailabilityZone: pulumi.String(azNames[idx]),
				CidrBlock: pulumi.String(subnetCidrBlock),
				MapPublicIpOnLaunch: pulumi.Bool(true),
			}

			subnet, err := ec2.NewSubnet(ctx, fmt.Sprintf("%s-pub-subnet-%d", baseName, idx), subnetArgs)
			if err != nil {
				log.Printf("error creating subnet: %s", err.Error())
			}
			pubSubnetIds = append(pubSubnetIds, subnet.Id)
		}
The issue is that the
subnet
variable doesn't have any field named
Id
,
id
, or any variation I've tried so far. The
.ID()
method that is used for VPCs doesn't seem to work for subnets. So how does one capture the ID for a subnet that you've created?
g

gentle-diamond-70147

06/24/2020, 1:42 AM
.ID()
should work. Are you getting an error when trying it?
s

salmon-account-74572

06/24/2020, 2:03 AM
I'll need to test again to verify, but I think it's just an error trying to use it with the
append
statement (due to a type mismatch, as far as I can tell). Using
pulumi.String
doesn't help.
g

gentle-diamond-70147

06/24/2020, 3:57 AM
Oh... yea, I believe you need
pubSubnetIds := make([]pulumi.IDOutput, numOfAZs)
s

salmon-account-74572

06/24/2020, 11:31 AM
That will fix it for now, but may introduce type issues later when I need to re-use those IDs (for placing EC2 instances, for example). I guess I'll cross that bridge when I get there. 🙂
Thanks!
4 Views