以下是一个使用AWS CloudFormation模板创建EC2实例并根据VPC选择返回子网列表的示例:
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
VpcId:
Type: AWS::EC2::VPC::Id
Description: Select the VPC to launch the EC2 instance in
SubnetId:
Type: AWS::EC2::Subnet::Id
Description: Select the subnet to launch the EC2 instance in
Resources:
EC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-xxxxxxxxx
InstanceType: t2.micro
SubnetId: !Ref SubnetId
SubnetListFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import boto3
def lambda_handler(event, context):
vpc_id = event['ResourceProperties']['VpcId']
ec2_client = boto3.client('ec2')
response = ec2_client.describe_subnets(
Filters=[
{
'Name': 'vpc-id',
'Values': [vpc_id]
}
]
)
subnet_list = []
for subnet in response['Subnets']:
subnet_list.append(subnet['SubnetId'])
return subnet_list
Handler: index.lambda_handler
Role: !GetAtt LambdaExecutionRole.Arn
Runtime: python3.8
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
- PolicyName: LambdaExecutionPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ec2:DescribeSubnets
Resource: '*'
SubnetListOutput:
Type: Custom::SubnetListOutput
Properties:
ServiceToken: !GetAtt SubnetListFunction.Arn
VpcId: !Ref VpcId
Outputs:
SubnetList:
Value: !GetAtt SubnetListOutput.SubnetList
Description: List of subnets in the selected VPC
在这个示例中,模板定义了两个参数:VpcId和SubnetId。VpcId参数用于选择VPC,SubnetId参数用于选择子网。EC2Instance资源根据SubnetId参数创建一个EC2实例。
模板还定义了一个Lambda函数(SubnetListFunction),它使用boto3库查询给定VPC的子网列表。该函数返回子网列表。
Lambda函数需要一个IAM角色(LambdaExecutionRole)来执行ec2:DescribeSubnets操作。该角色使用AssumeRolePolicyDocument指定允许Lambda服务扮演该角色的权限,并使用Policies指定允许操作的权限。
最后,模板还定义了一个Custom资源(SubnetListOutput),它使用SubnetListFunction来获取子网列表,并输出为CloudFormation输出(SubnetList)。
要使用此模板,您可以在AWS Management Console的CloudFormation服务中创建一个新堆栈,并提供所需的参数(VpcId和SubnetId)。然后,您将能够查看输出中的子网列表。