我想在AWS market-place上托管解决方案(CloudFormation模板)。当用户想要使用我的解决方案启动实例时,他应该选择仅 AWS区域。我希望模板找出该区域的默认VPC以及其中一个AZ的默认子网;目前,AZ的选择无关紧要。此question要求在创建模板时将值输入到模板。但是,我的要求是让这些值自动神奇地计算出来。
我知道我可以自动从Python SDK中查找默认值,如下所示。我也可以将此脚本的输出提供给troposphere以获取我的最终模板。即使我完成了这项工作,我该如何主持这个“动态”的活动。市场上的模板?请注意,CloudFormation模板很重要,因此,我不会看到基于Chef或Puppet的解决方案。
"""
Documentation
"""
#
import json
import boto3
#
def get_default_vpc_id():
"""
Get default VPC of a region. The region parameter is read from the AWS configuration file.
The `boto3` SDK will look for the configuration file here - `$HOME/.aws/config`.
"""
ec2_client = boto3.client('ec2')
default_vpc = ec2_client.describe_vpcs(Filters=[{'Name' : 'isDefault', 'Values' : ['true']}])
default_vpc_id = default_vpc['Vpcs'][0]['VpcId']
return default_vpc_id
#
def get_vpc_subnets(vpc_id):
"""
Get subnet and its details for the provided VPC identifier. The region parameter is read
from the AWS configuration file. The `boto3` SDK will look for the configuration file here -
`$HOME/.aws/config`.
Since the VPC identifier, provided in this code, is the default VPC of a region, its
subnets will be public. Therefore, there is no check for Internet Gateway.
TODO: Include check of Internet Gateway and NAT Gateway.
"""
ec2_resource = boto3.resource('ec2')
default_vpc_id = ec2_resource.Vpc(vpc_id)
vpc_subnets = default_vpc_id.subnets.all()
#
subnet_array = []
for ec2_subnet in vpc_subnets:
subnet = {}
subnet['subnet_id'] = ec2_subnet.subnet_id
subnet['subnet_az'] = ec2_subnet.availability_zone
subnet['default_for_az'] = ec2_subnet.default_for_az
subnet_array.append(subnet)
#
subnets = json.dumps(subnet_array)
return subnets
#
def default_vpc_subnets():
"""
Get subnets of the default VPC of a AWS region
"""
default_vpc_id = get_default_vpc_id()
subnets = get_vpc_subnets(default_vpc_id)
subnets_of_default_vpc = json.dumps({'default_vpc_id' : default_vpc_id, 'subnets' : subnets})
#
print subnets_of_default_vpc
#
default_vpc_subnets()