Hi, in python aws I'm struggling creating subnets with ipv6_cidr_block (/64) from vpc (/56) ```vpc =...
d
Hi, in python aws I'm struggling creating subnets with ipv6_cidr_block (/64) from vpc (/56)
Copy code
vpc = aws.ec2.Vpc(assign_generated_ipv6_cidr_block=True,...)
I'm looping over AZs
Copy code
for idx, zone in enumerate(availability_zones.names):
    aws.ec2.Subnet(...,
       ipv6_cidr_block = vpc.ipv6_cidr_block.apply(lambda ipv6_block: assign_ipv6_cidr_block(idx,ipv6_block)))
using a utility function:
Copy code
def assign_ipv6_cidr_block(subnet_idx, vpc_ipv6_cidr):
    vpc_ipv6_network = ipaddress.IPv6Network(vpc_ipv6_cidr)
    subnet_ipv6_cidr = list(vpc_ipv6_network.subnets(new_prefix=64))[subnet_idx]
    return str(subnet_ipv6_cidr)
However, I get InvalidSubnet.Conflict, probably because this async stuff causes last value of idx to be used in the call to Subnet(... assign_ipv6_cidr_block(idx)). So, how to fix this code using seperate values of idx (as in a sync world) - or even better use some pulumi built-in functions that just works. Thanks for your help
d
this is a quirk in python that's caught me out before; essentially the lambda references the last assignment of idx. ``````
quick proof of concept in pure python:
Copy code
l = ["a", "b", "c"]
funcs = []
for idx, item in enumerate(l):
    funcs.append(lambda: print(idx, item))

for f in funcs:
    f()
# prints 2 c 2 c 2 c
just checking if something will work, but you might be able to do this to bring forward the idx reference into the loop:
Copy code
Output.all(idx, vpc.ipv6_cidr_block).apply(assign_ipv6_cidr_block)
actually, simpler way is to set idx using a kwarg on the lambda:
Copy code
vpc.ipv6_cidr_block.apply(lambda ipv6_block, idx=idx: assign_ipv6_cidr_block(idx,ipv6_block)))
d
damn, this was just pure python that got me. Thanks a lot Anthony! Saved my day. I ended up using Output.all as above, but had to change my helper function to:
Copy code
def assign_ipv6_cidr_block(arg):
    subnet_idx, vpc_ipv6_cidr = arg
    ...
Again, thank you so much!
d
Aye, it catches many out the first time they encounter the issue
I wonder if Ruff (python's defacto linter) has rules for it