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

Sample Troposphere Template

cpeters's picture

Fri, 04/22/2016 - 15:27 by cpeters

This is a simple Python script one can use to bring a single server stack online with a new Elastic IP. Note that sometimes you'll have properties nested within properties, such as the rules nested within the security group below. The only way to define these that I've found is by defining them within the property -- that is, one cannot define them outside the "Properties" tag of the current resource. Network interfaces are also an example of this.

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

####Define existing AWS Environment####
AccessCIDR="" #CIDR range that you want to have access through the security group
VPC_ID= ""       #ID of the existing VPC you want to use
SubnetID = ""   #ID of the existing subnet you want to use
ImageID = ""    #ID of the AMI to use for your instance
####Define existing AWS Environment####

template = Template() 

####Create Security Group####
sg01 = ec2.SecurityGroup("SecurityGroup")
sg01.VpcId=VPC_ID
sg01.GroupDescription="This is my description"
sg01.SecurityGroupIngress = [
    ec2.SecurityGroupRule(
        IpProtocol = "tcp",
        FromPort = "22",
        ToPort = "22",
        CidrIp=AccessCIDR,),
    ec2.SecurityGroupRule(
        IpProtocol = "tcp",
        FromPort = "443",
        ToPort = "443",
        CidrIp=AccessCIDR,)
]
template.add_resource(sg01)
####Create Security Group####

####Specify keypair####
keyLID  = "KeyPair"
key01 = template.add_parameter(Parameter("{}".format(keyLID,str),
                                         Type="String",
                                         Description="This is my description",))
####Specify keypair####


####Create Instance####
i01 = ec2.Instance("Instance")
i01.Tags = [{"Key" : "Name", "Value" : "Instance-Name"}]
i01.ImageId = ImageID
i01.InstanceType = "t2.medium"
i01.SubnetId = SubnetID
i01.KeyName = Ref(key01)
i01.SecurityGroupIds = [Ref(sg01)]
template.add_resource(pm01)
####Create Instance####


####Create Elastic IP####
EIP01 = ec2.EIP("ElasticIP")
EIP01.InstanceId = Ref(i01)
EIP01.Domain = "vpc"
template.add_resource(EIP01)
####Create Elastic IP####

print(template.to_json())

os.remove('/path/to/file.template')
fhandle = open('/path/to/file.template','w')
fhandle.write(template.to_json())
fhandle.close()
Tags: 
AWS Troposphere Python CloudFormation
Powered by Backdrop CMS