本文整理汇总了Python中troposphere.Template.add_version方法的典型用法代码示例。如果您正苦于以下问题:Python Template.add_version方法的具体用法?Python Template.add_version怎么用?Python Template.add_version使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类troposphere.Template
的用法示例。
在下文中一共展示了Template.add_version方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _template_init
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
def _template_init(self):
t = Template()
t.add_version("2010-09-09")
#t.add_parameter(Parameter("StackName",
# Description="Name of this stack",
# Type="String",))
return t
示例2: _generate_template
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
def _generate_template(tms=1, within_vpc=False):
t = Template()
t.add_description(FLINK_TEMPLATE_DESCRIPTION)
t.add_version(FLINK_TEMPLATE_VERSION)
t.add_metadata({'LastUpdated': datetime.datetime.now().strftime('%c')})
# mappings
mappings.add_mappings(t)
# parameters
parameters.add_parameters(t)
vpc = None
subnet_pri = None
subnet_pub = None
if within_vpc:
# networking resources
vpc, subnet_pri, subnet_pub = _define_vpc(t)
# security groups
sg_ssh = t.add_resource(securitygroups.ssh(
parameters.ssh_location, vpc))
sg_jobmanager = t.add_resource(securitygroups.jobmanager(
parameters.http_location, vpc))
sg_taskmanager = t.add_resource(securitygroups.taskmanager(None, vpc))
jobmanager = t.add_resource(instances.jobmanager(
0,
[Ref(sg_ssh), Ref(sg_jobmanager)],
within_vpc,
subnet_pub
))
prefix = "JobManager00"
t.add_output(outputs.ssh_to(jobmanager, prefix))
t.add_output(Output(
"FlinkWebGui",
Description="Flink web interface",
Value=Join("", [
'http://', GetAtt(jobmanager, "PublicDnsName"), ':8081'
])
))
for index in range(0, tms):
i = t.add_resource(instances.taskmanager(
index,
jobmanager,
[Ref(sg_ssh), Ref(sg_taskmanager)],
within_vpc,
subnet_pri
))
prefix = "TaskManager%2.2d" % index
t.add_output(outputs.ssh_to(i, prefix, bastion=jobmanager))
return t.to_json()
示例3: generate_env_template
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
def generate_env_template(app_env, env_dict):
sg_name = env_dict['sg_name']
vpc_id = 'vpc-a1d187c4' # query for this!
logger.debug('generating template for %s' % vpc_id)
t = Template()
t.add_version('2010-09-09')
t.add_description('env template for %s' % app_env)
app_sg = SecurityGroup('TestAppSecurityGroup')
app_sg.VpcId = vpc_id
app_sg.GroupDescription = 'testing'
app_sg.Tags = name_tag(sg_name)
t.add_resource(app_sg)
return t.to_json()
示例4: generate_application_template
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
def generate_application_template(app_dict):
app_name = app_dict['app_name']
t = Template()
t.add_version()
t.add_description('app template for %s' % app_name)
app = Application(app_name, Description=app_name)
t.add_resource(app)
bucket_name = 'ehi-pcf-%s' % app_name
bucket = Bucket('AppBucket', BucketName=bucket_name, AccessControl=Private)
t.add_resource(bucket)
return t.to_json()
示例5: lambda_handler
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
def lambda_handler(event, context):
#print("Received event: " + json.dumps(event, indent=2))
# Get the object from the event and show its content type
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
print ("buket:" + bucket)
print ("key:" + key)
obj = s3.Object(bucket,key)
response= obj.get()
body = response['Body'].read()
body_list= body.splitlines()
# VPC関係
VPC_CidrBlockList = body_list[0].split(',')
VPC_EnableDnsSupportList = body_list[1].split(',')
VPC_TagsValueList = body_list[2].split(',')
t = Template()
t.add_version("2010-09-09")
t.add_description("ROOP&ROOP")
if len(VPC_CidrBlockList) > 1:
for (address,dns,value) in zip(VPC_CidrBlockList[1:],VPC_EnableDnsSupportList[1:],VPC_TagsValueList[1:]):
t.add_resource(VPC(
value,
EnableDnsSupport="true",
CidrBlock=address,
EnableDnsHostnames=dns,
Tags=Tags(Name=value)
))
json_template = t.to_json()
bucket = s3.Bucket('cf-templates-hokan')
obj = bucket.Object('json-template-' + basename + ' .txt')
response = obj.put(
Body=json_template.encode('utf-8'),
ContentEncoding='utf-8',
ContentType='text/plane'
)
print(json_template)
示例6: add_resources
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
def add_resources(self, resources, config):
"""
Creates JSON-formatted string representation of stack resourcs
suitable for use with AWS Cloudformation
:param resources: Internal data structure of resources
:type resources: dict.
:param config: Config key/value pairs
:type config: dict.
:returns: string
:raises: :class:`pmcf.exceptions.ProvisionerException`
"""
LOG.info('Start building template')
data = Template()
desc = "%s %s stack" % (config['name'], config['environment'])
data.add_description(desc)
data.add_version()
self._add_streams(data, resources.get('stream', []), config)
self._add_queues(data, resources.get('queue', []), config)
self._add_nets(data, resources.get('network', []), config)
sgs = self._add_secgroups(data, resources['secgroup'], config)
self._add_caches(data, resources.get('cache', []), config, sgs)
lbs = self._add_lbs(data,
resources['load_balancer'],
config,
sgs,
resources['instance'])
self._add_instances(data,
resources['instance'],
config,
sgs,
lbs)
LOG.info('Finished building template')
return data.to_json(indent=None)
示例7: main
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
def main(argv):
FILE = None
try:
opts, args = getopt.getopt(argv,"hf:",["FILE="])
except getopt.GetoptError:
print sys.argv[0], ' -f <metric-csv-file>'
sys.exit(2)
# An array to contain any parameters for the template.
parameters = []
# An array to contain any conditions for the template.
conditions = {}
# An array to contain any key value maps for the template.
maps = []
# An array to contain any resource objects for the template.
resources = []
# An array to contain any output objects for the template.
outputs = []
with open(FILE, 'rbU') as f:
reader = csv.reader(f)
try:
for row in islice(reader, 1, None):
resources.append(Alarm(
"QueueDepthAlarm",
AlarmDescription="Alarm if queue depth grows beyond 10 messages",
Namespace="AWS/SQS",
MetricName="ApproximateNumberOfMessagesVisible",
Dimensions=[
MetricDimension(
Name="QueueName",
Value=GetAtt(myqueue, "QueueName")
),
],
Statistic="Sum",
Period="300",
EvaluationPeriods="1",
Threshold="10",
ComparisonOperator="GreaterThanThreshold",
AlarmActions=[Ref(alarmtopic), ],
InsufficientDataActions=[Ref(alarmtopic), ],
))
except csv.Error as e:
sys.exit('file %s, line %d: %s' % (VPC_ID, reader.line_num, e))
t = Template()
t.add_version('2010-09-09')
t.add_description(
"This is an AWS CloudFormation template that provisions metric filters "
"based on a spreadsheet of applicable metric filters. ***WARNING*** This "
"template creates many Amazon CloudWatch alarms based on a Amazon "
"CloudWatch Logs Log Group. You will be billed for the AWS resources used "
"if you create a stack from this template."
)
for p in parameters:
t.add_parameter(p)
for k in conditions:
t.add_condition(k, conditions[k])
for r in resources:
t.add_resource(r)
for o in outputs:
t.add_output(o)
# Print the template to JSON
print(t.to_json())
示例8: create_template
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
def create_template(num_masters, num_agents, num_publicAgents):
#outfilename = "test.json"
outfilename = "cf_" + str(num_masters) + "." + str(num_agents) + "." + str(num_publicAgents) + ".json"
# Create the Template
t = Template()
t.add_version('2010-09-09')
t.add_description('Creates a set of Servers for DC/OS using CentOS 7.3 AMI. Creates a boot server to host the DC/OS installer and a NAT Instance for outbound connections from private agents. Creates ' + str(num_masters) + ' Master(s), ' \
+ str(num_agents) + ' Private Agent(s), and ' + str(num_publicAgents) + ' Public Agent(s). After creating the Stack; Log into the boot server and run the DCOS Bash Script installer for AWS')
# Amazon Linux AMI 2016.09.1.20170119 x86_64 VPC NAT HVM EBS
# amzn-ami-vpc-nat-hvm-2016.09.1.20170119-x86_64-ebs -
# ami-dd3dd7cb us-east-1 (N. Virginia)
# ami-564b6e33 us-east-2 (Ohio)
# ami-7d54061d us-west-1 (N. Cal)
# ami-3b6fd05b us-west-2 (Oregon)
t.add_mapping('NATAmi', {
'us-east-1': {'default': 'ami-dd3dd7cb'},
'us-east-2': {'default': 'ami-564b6e33'},
'us-west-1': {'default': 'ami-7d54061d'},
'us-west-2': {'default': 'ami-3b6fd05b'},
})
# The c73 AMI pre created and deployed on each region
t.add_mapping('c73Ami', {
'us-east-1': {'default': 'ami-46c1b650'},
'us-east-2': {'default': 'ami-18f8df7d'},
'us-west-1': {'default': 'ami-f5d7f195'},
'us-west-2': {'default': 'ami-f4533694'},
})
# CloudFormation Parameters
# Sometimes when I deployed stack on us-east-1; it would fail on av zone us-east-1c with error messages instance type not support on this AZ. I added this parameter to fix all of the components in on AZ for now
avzone_param = t.add_parameter(Parameter(
"AVZoneName",
ConstraintDescription='Must be the name of an an Availability Zone',
Description='Name of an Availability Zone',
Type='AWS::EC2::AvailabilityZone::Name',
))
# Every agent will get a data drive of this size
dataDriveSizeGB_param = t.add_parameter(Parameter(
"dataDriveSizeGB",
Default="100",
MinValue=20,
MaxValue=1000,
Description='Size of data drive to add to private agents from 20 to 1000GB',
Type='Number'
))
# The key will be added to the centos user so you can login to centos using the key
keyname_param = t.add_parameter(Parameter(
"KeyName",
ConstraintDescription='Must be the name of an existing EC2 KeyPair.',
Description='Name of an existing EC2 KeyPair to enable SSH access to the instance',
Type='AWS::EC2::KeyPair::KeyName',
))
# While you can allow everyone it's more secure to just allow a single machine or subnet of machines; web port will also be opened to this CIDR
sshlocation_param = t.add_parameter(Parameter(
"sshlocation",
Type="String",
Description="Subnet allowed to ssh to these servers. 0.0.0.0/0 to allow all."
))
# Instance type for Master
instanceTypeMaster_param = t.add_parameter(Parameter(
'InstanceTypeMaster',
Type='String',
Description='EC2 instance type for ' + str(num_masters) + ' Masters(s)',
Default='m4.xlarge',
AllowedValues=[
't2.xlarge', 't2.2xlarge',
'm4.xlarge', 'm4.2xlarge',
'm4.4xlarge', 'm4.10xlarge',
'c4.xlarge', 'c4.2xlarge',
'c4.4xlarge', 'c4.8xlarge',
],
ConstraintDescription='Must be a valid EC2 instance type.',
))
# Instance type for Agents
instanceTypeAgent_param = t.add_parameter(Parameter(
'InstanceTypeAgent',
Type='String',
Description='EC2 instance type for ' + str(num_agents) + ' Private Agent(s)',
Default='m4.2xlarge',
AllowedValues=[
't2.xlarge', 't2.2xlarge',
'm4.xlarge', 'm4.2xlarge',
'm4.4xlarge', 'm4.10xlarge',
'c4.xlarge', 'c4.2xlarge',
'c4.4xlarge', 'c4.8xlarge',
],
#.........这里部分代码省略.........
示例9: main
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
def main():
template = Template()
template.add_version("2010-09-09")
template.add_description(
"AWS CloudFormation Sample Template: ELB with 2 EC2 instances")
AddAMI(template)
# Add the Parameters
keyname_param = template.add_parameter(Parameter(
"KeyName",
Type="String",
Default="mark",
Description="Name of an existing EC2 KeyPair to "
"enable SSH access to the instance",
))
template.add_parameter(Parameter(
"InstanceType",
Type="String",
Description="WebServer EC2 instance type",
Default="m1.small",
AllowedValues=[
"t1.micro", "m1.small", "m1.medium", "m1.large", "m1.xlarge",
"m2.xlarge", "m2.2xlarge", "m2.4xlarge", "c1.medium", "c1.xlarge",
"cc1.4xlarge", "cc2.8xlarge", "cg1.4xlarge"
],
ConstraintDescription="must be a valid EC2 instance type.",
))
webport_param = template.add_parameter(Parameter(
"WebServerPort",
Type="String",
Default="8888",
Description="TCP/IP port of the web server",
))
apiport_param = template.add_parameter(Parameter(
"ApiServerPort",
Type="String",
Default="8889",
Description="TCP/IP port of the api server",
))
subnetA = template.add_parameter(Parameter(
"subnetA",
Type="String",
Default="subnet-096fd06d"
))
subnetB = template.add_parameter(Parameter(
"subnetB",
Type="String",
Default="subnet-1313ef4b"
))
VpcId = template.add_parameter(Parameter(
"VpcId",
Type="String",
Default="vpc-82c514e6"
))
# Define the instance security group
instance_sg = template.add_resource(
ec2.SecurityGroup(
"InstanceSecurityGroup",
GroupDescription="Enable SSH and HTTP access on the inbound port",
SecurityGroupIngress=[
ec2.SecurityGroupRule(
IpProtocol="tcp",
FromPort="22",
ToPort="22",
CidrIp="0.0.0.0/0",
),
ec2.SecurityGroupRule(
IpProtocol="tcp",
FromPort=Ref(webport_param),
ToPort=Ref(webport_param),
CidrIp="0.0.0.0/0",
),
ec2.SecurityGroupRule(
IpProtocol="tcp",
FromPort=Ref(apiport_param),
ToPort=Ref(apiport_param),
CidrIp="0.0.0.0/0",
),
]
)
)
# Add the web server instance
WebInstance = template.add_resource(ec2.Instance(
"WebInstance",
SecurityGroups=[Ref(instance_sg)],
KeyName=Ref(keyname_param),
InstanceType=Ref("InstanceType"),
ImageId=FindInMap("RegionMap", Ref("AWS::Region"), "AMI"),
UserData=Base64(Ref(webport_param)),
))
#.........这里部分代码省略.........
示例10: open
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
env = arguments["ENV"].lower()
with open('conf/aws_config.json') as aws_config_file:
aws_config = json.load(aws_config_file)
with open(arguments["-f"]) as config_file:
config = json.load(config_file)
vpc = {
"VpcId": aws_config["VpcId"]
}
zones = config.get("Zones", aws_config["Zones"])
template = Template()
template.add_version("2010-09-09")
min_size = Parameter(
"MinSize",
Default="1",
AllowedValues=config["MinMaxNumberOfInstancesPerZone"],
Type="Number",
Description="Set MinSize and MaxSize to 0 to stop instances. Set it to 1 to start instances",
)
template.add_parameter(min_size)
max_size = Parameter(
"MaxSize",
Default="1",
AllowedValues=config["MinMaxNumberOfInstancesPerZone"],
Type="Number",
示例11: make_bigfix_awscf_template
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
def make_bigfix_awscf_template():
template = Template()
# http://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists-in-python
# http://www.tutorialspoint.com/python/string_endswith.htm
# Only run the function to include the Meraki MSI installation if Windows Server + MERAKI_MSI_URL defined properly
# MERAKI_MSI_URL should be defined in the bf_cf_config.py file
if "Windows" == BES_ROOT_SERVER_TYPE and 'MERAKI_MSI_URL' in globals() and MERAKI_MSI_URL.endswith('/MerakiPCCAgent.msi'):
meraki_msi_url = MERAKI_MSI_URL
else:
meraki_msi_url = ""
template.add_description("""\
BigFix Eval AWS CloudFormation Template within the resource limits of the AWS free tier. \
**WARNING** This template creates Amazon EC2 & RDS instances. You may be billed \
for the AWS resources used if you create a stack from this template.""")
template.add_version('2010-09-09')
# define subnet
# define DB Subnet Group
# define RDS instance
# https://github.com/cloudtools/troposphere/blob/master/troposphere/rds.py#L13
# define EBS volume (to be attached to the EC2 instance)
# define Metadata for EC2 instance
# http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-init.html#aws-resource-init-files
# http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/deploying.applications.html
# https://github.com/cloudtools/troposphere/issues/3
metadata = {
"AWS::CloudFormation::Init": {
"config": {
"packages": {
"msi" : {
#"awscli" : "https://s3.amazonaws.com/aws-cli/AWSCLI64.msi",
"meraki" : meraki_msi_url
},
},
}
}
}
# define EC2 instance with Metadata
ec2_instance = ec2.Instance("BigFixEval", Metadata=metadata)
ec2_instance.ImageId = "ami-6502e021"
ec2_instance.InstanceType = "t2.micro"
# https://github.com/cloudtools/troposphere/blob/master/troposphere/ec2.py#L134
#ec2_instance.SubnetId = "" # Ref(SubnetID)
# http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-volumes
# https://github.com/cloudtools/troposphere/blob/master/troposphere/ec2.py#L138
#ec2_instance.Volumes = "" # Ref(Volume)
template.add_resource(ec2_instance)
template.add_output([
Output(
"AZ",
Description="Availability Zone of the newly created EC2 instance",
Value=GetAtt(ec2_instance, "AvailabilityZone"),
),
Output(
"PublicDNS",
Description="Public DNSName of the newly created EC2 instance",
Value=GetAtt(ec2_instance, "PublicDnsName"),
),
])
template.add_parameter(
Parameter(
'RootServerDomain',
Description=' The domain name the BigFix root server will use ',
Type='String',
Default='bigfixeval.organization.tld'
))
return template.to_json()
示例12: Template
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
EMAIL_PATTERN = '^[\w!#$%&\'*+/=?`{|}~^-]+(?:\.[\w!#$%&\'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}$'
# pylint: enable=anomalous-backslash-in-string
ANSIBLE_PULL_URL = os.getenv('ANSIBLE_PULL_URL',
'https://github.com/trustedanalytics/ansible-playbooks.git')
ANSIBLE_PULL_CHECKOUT = os.getenv('ANSIBLE_PULL_CHECKOUT', 'master')
ANSIBLE_GROUP_VARS = [
'ntp_server=[\'0.amazon.pool.ntp.org\', \'1.amazon.pool.ntp.org\']\n',
'provider=aws\n',
]
TEMPLATE = Template()
TEMPLATE.add_version('2010-09-09')
TEMPLATE.add_description('Trusted Analytics Platform (TAP) is open source software, optimized for '
'performance and security, that accelerates the creation of Cloud-native '
'applications driven by Big Data Analytics. TAP makes it easier for '
'developers and data scientists, at enterprises, CSPs and SIs, to '
'collaborate by providing a shared, flexible environment for advanced '
'analytics in public and private Clouds. Data scientists get extensible '
'tools, scalable algorithms and powerful engines to train and deploy '
'predictive models. Developers get consistent APIs, services and runtimes'
' to quickly integrate these models into applications. System Operators '
'get an integrated stack that they can easily provision in a Cloud '
'infrastructure.')
TEMPLATE.add_mapping('Region2AMI', {
EU_WEST_1: {'Ubuntu': 'ami-cd0fd6be', 'RHEL': 'ami-78d29c0f'},
示例13: CloudFormationBuilder
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
class CloudFormationBuilder(object):
def __init__(self):
self._random_id = str(uuid.uuid4()).replace('-', '')[:12].upper()
self._template = Template()
self._template.add_version("2010-09-09")
self.add_resource = self._template.add_resource
self.add_parameter = self._template.add_parameter
self.PushVPC = self.add_parameter(Parameter(
"ExistingVPC",
Type="AWS::EC2::VPC::Id",
Description=(
"The VPC Id so launch the Autopush server into"
),
))
self.PushCryptoKey = self.add_parameter(Parameter(
"AutopushCryptoKey",
Type="String",
Default=Fernet.generate_key(),
Description="Autopush crypto-key",
))
self.KeyPair = self.add_parameter(Parameter(
"AutopushSSHKeyPair",
Type="AWS::EC2::KeyPair::KeyName",
Description="Name of an EC2 KeyPair to enable SSH access."
))
self.PushTablePrefix = self.add_parameter(Parameter(
"PushTablePrefix",
Type="String",
Default="autopush_" + self._random_id,
Description="Autopush DynamoDB Table Prefixes",
))
self._add_autopush_security_group()
self._add_autopush_iam_roles()
self._add_autopush_servers()
def _add_autopush_security_group(self):
self.InternalRouterSG = self.add_resource(SecurityGroup(
"AutopushInternalRouter",
GroupDescription="Internal Routing SG"
))
self.EndpointSG = self.add_resource(SecurityGroup(
"AutopushEndpointNode",
SecurityGroupIngress=[
allow_tcp(8082),
allow_tcp(22),
],
GroupDescription="Allow HTTP traffic to autoendpoint node",
))
self.ConnectionSG = self.add_resource(SecurityGroup(
"AutopushConnectionNode",
SecurityGroupIngress=[
allow_tcp(8080),
allow_tcp(22),
SecurityGroupRule(
IpProtocol="tcp",
FromPort=8081,
ToPort=8081,
SourceSecurityGroupName=Ref(self.InternalRouterSG)
)
],
GroupDescription=(
"Allow Websocket traffic to autopush node"
)
))
def _add_autopush_iam_roles(self):
self.PushServerRole = self.add_resource(Role(
"AutopushServerRole",
AssumeRolePolicyDocument=Policy(
Version="2012-10-17",
Statement=[
Statement(
Effect=Allow,
Action=[AssumeRole],
Principal=Principal("Service", "ec2.amazonaws.com")
)
]
),
Path="/",
))
self.add_resource(PolicyType(
"AutopushServerRolePolicy",
PolicyName="AutopushServerRole",
PolicyDocument=Policy(
Version="2012-10-17",
Statement=[
Statement(
Effect=Allow,
Action=[
ddb.BatchGetItem,
ddb.BatchWriteItem,
ddb.GetItem,
ddb.PutItem,
ddb.DeleteItem,
ddb.UpdateItem,
ddb.Query,
ddb.Scan,
],
#.........这里部分代码省略.........
示例14: lambda_handler
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
# lambda_handlerに渡されたイベントからs3バケットとキーを取り出してs3オブジェクトをgetする。
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
print ("buket:" + bucket)
print ("key:" + key)
obj = s3.Object(bucket,key)
response= obj.get()
data = response['Body'].read()
# パラメータシートの読み込み。
# 作成したパラメータシートの先頭に書いてある文字列が変数名として使用されます。
patrameter_list= data.splitlines()
for i in range(len(parameter_list)):
parameter = parameter_list[i].split(',')
a = str(parameter[0])
ns = locals()
ns[a] = parameter
# テンプレートの作成
t = Template()
t.add_version("2010-09-09")
t.add_description("ROOP&ROOP")
# VPCの作成
if len(VPC_CidrBlockList) > 1:
for (address,dns,value) in zip(VPC_CidrBlockList[1:],VPC_EnableDnsHostnamesList[1:],VPC_TagsValueList[1:]):
t.add_resource(VPC(
value.translate(string.maketrans("", ""), "-_"),
EnableDnsSupport="true",
CidrBlock=address,
EnableDnsHostnames=dns,
Tags=Tags(
Name=value
)
))
# u'サブネットの作成'
if len(Subnet_CidrBlockList) > 1:
for (address,az,pip,value,vpcid) in zip(Subnet_CidrBlockList[1:],Subnet_AzList[1:],Subnet_MapPublicIpOnLaunchList[1:],\
Subnet_TagsValueList[1:],Subnet_VpcIdList[1:]):
t.add_resource(Subnet(
value.translate(string.maketrans("", ""), "-_"),
CidrBlock=address,
AvailabilityZone=az,
MapPublicIpOnLaunch=pip,
VpcId=Ref(vpcid.translate(string.maketrans("", ""), "-_")),
Tags=Tags(
Name=value
)
))
# u'各種GateWayの作成
if len(InternetGateway_TagsValueList) > 1:
for (value) in (InternetGateway_TagsValueList[1:]):
t.add_resource(InternetGateway(
value.translate(string.maketrans("", ""), "-_"),
Tags=Tags(
Name=value
)
))
if len(CustomerGateway_TagsValueList) > 1:
for (value,ipaddress,bgpasn) in zip(CustomerGateway_TagsValueList[1:],CustomerGateway_IpAddressList[1:],CustomerGateway_BgpAsnList[1:]):
t.add_resource(CustomerGateway(
value.translate(string.maketrans("", ""), "-_"),
Type="ipsec.1",
IpAddress=ipaddress,
BgpAsn=bgpasn,
Tags=Tags(
Name=value
)
))
if len(VPNGateway_TagsValueList) > 1:
for (value) in (VPNGateway_TagsValueList[1:]):
t.add_resource(VPNGateway(
value.translate(string.maketrans("", ""), "-_"),
Type="ipsec.1",
Tags=Tags(
Name=value
)
))
# u'各種GatewayのVPCへのアタッチ'
if len(VPCGatewayAttachment_InternetGatewayIdList) > 1:
for i,(gatewayid,vpcid) in enumerate(zip(VPCGatewayAttachment_InternetGatewayIdList[1:],VPCGatewayAttachment_VpcId_IGList[1:])):
t.add_resource(VPCGatewayAttachment(
"VPCGatewayAttachmentInternetGateway"+str(i),
InternetGatewayId=Ref(gatewayid.translate(string.maketrans("", ""), "-_")),
VpcId=Ref(vpcid.translate(string.maketrans("", ""), "-_"))
))
if len(VPCGatewayAttachment_VpnGatewayIdList) > 1:
for i,(gatewayid,vpcid) in enumerate(zip(VPCGatewayAttachment_VpnGatewayIdList[1:],VPCGatewayAttachment_VpcId_VPNList[1:])):
t.add_resource(VPCGatewayAttachment(
"VPCGatewayAttachmentVPNGateway"+str(i),
VpnGatewayId=Ref(gatewayid.translate(string.maketrans("", ""), "-_")),
VpcId=Ref(vpcid.translate(string.maketrans("", ""), "-_"))
))
# u'DHCPオプションの作成'
if len(DHCPOptions_DomainNameList) > 1:
for (domainname,domainnameservers,value,) in zip(DHCPOptions_DomainNameList[1:],DHCPOptions_DomainNameServersList[1:],DHCPOptions_ValueList[1:]):
t.add_resource(DHCPOptions(
value.translate(string.maketrans("", ""), "-_"),
DomainName=domainname,
#.........这里部分代码省略.........
示例15: Template
# 需要导入模块: from troposphere import Template [as 别名]
# 或者: from troposphere.Template import add_version [as 别名]
from troposphere import Template
from troposphere.codedeploy import AutoRollbackConfiguration, \
DeploymentStyle, DeploymentGroup, ElbInfoList, LoadBalancerInfo
template = Template()
template.add_version('2010-09-09')
auto_rollback_configuration = AutoRollbackConfiguration(
Enabled=True,
Events=['DEPLOYMENT_FAILURE']
)
deployment_style = DeploymentStyle(
DeploymentOption='WITH_TRAFFIC_CONTROL'
)
elb_info_list = ElbInfoList(
Name='DemoLoadBalancer'
)
load_balancer_info = LoadBalancerInfo(
ElbInfoList=[elb_info_list]
)
deployment_group = DeploymentGroup(
"DemoDeploymentGroup",
ApplicationName='DemoApplication',
AutoRollbackConfiguration=auto_rollback_configuration,
DeploymentStyle=deployment_style,