Skip to main content
Home
badllama.com
  • Search
  • Log In

How to create copies of a resource using troposphere

cpeters's picture

Thu, 04/21/2016 - 17:49 by cpeters

One of the surprises that Python contains is that it appears to only pass variables by reference, which I'm sure will get me in hot water with Python gurus but walking and quacking like a duck will get you called a duck. In any case, something very useful that one might want to do in troposphere is to make value-based copies of AWS resources. While technically this is impossible, one can accomplish the net same affect with a simple for-each loop:

import troposphere.ec2 as ec2
from troposphere import Template, Ref, Output, Join, GetAtt, Parameter

template = Template()

psub = ec2.Subnet("PrimarySubnet")
psub.CidrBlock = "172.31.16.0/20"
psub.VpcId = "DefaultVPC"

template.add_resource(psub)

instanceList = []
ha01 = ec2.Instance("SpatialInoteHA01")
ha02 = ec2.Instance("SpatialInoteHA02")

instanceList.append(ha01)
instanceList.append(ha02)

for instance in instanceList:
    instance.ImageId = "ami-cdf71ad"
    instance.InstanceType = "t2.medium"
    instance.KeyName = "spatial-inote-key-pair"
    instance.SecurityGroupIds = ["sg-bf0afdd8"]
    instance.SubnetId = Ref(psub)
    template.add_resource(instance)

print(template.to_json())

One can get creative from there.

Tags: 
Python value reference troposphere AWS
Powered by Backdrop CMS