我想为单个参数使用多个值,以通过 AWS CloudFormation 模板创建或更新堆栈。
解决方案
**注意:**如果您在运行 AWS 命令行界面 (AWS CLI) 命令时收到错误,请参阅 AWS CLI 错误故障排除。此外,请确保您使用的是最新版本的 AWS CLI。
要在 CloudFormation 模板中为单个参数使用多个值,请执行以下操作之一:
使用特定于 AWS 的参数类型
**注意:**CloudFormation 会根据账户中的现有值验证您选择的输入值。
在以下 CloudFormation 模板示例中,包含 SecurityGroups 键的参数指定了一个特定于 AWS 的参数类型,可接受多个 SecurityGroupIds 值。
JSON 模板:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Parameters": {
"SecurityGroups": {
"Type": "List<AWS::EC2::SecurityGroup::Id>",
"Description": "The list of SecurityGroupIds in your Virtual Private Cloud (VPC)"
}
},
"Resources": {
"MyEC2Instance": {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId": "ami-79fd7eee",
"KeyName": "testkey",
"SecurityGroupIds": {
"Ref": "SecurityGroups"
}
}
}
}
}
YAML 模板:
AWSTemplateFormatVersion: 2010-09-09
Parameters:
SecurityGroups:
Type: 'List<AWS::EC2::SecurityGroup::Id>'
Description: The list of SecurityGroupIds in your Virtual Private Cloud (VPC)
Resources:
MyEC2Instance:
Type: 'AWS::EC2::Instance'
Properties:
ImageId: ami-79fd7eee
KeyName: testkey
SecurityGroupIds: !Ref SecurityGroups
要部署堆栈,请运行 create-stack AWS CLI 命令:
aws cloudformation create-stack --stack-name StackName --template-body file://TemplateFileName
--parameters ParameterKey=SecurityGroups,ParameterValue="sg-0123456789\,sg-2345678901"
**注意:**请将 StackName 替换为您的堆栈名称,将 TemplateFileName 替换为您的文件名称。对于 ParameterValue,输入您的安全组 ID。
使用 CommaDelimitedList 参数类型
在以下 CloudFormation 模板示例中,包含 SecurityGroups 键的参数指定了一个 CommaDelimitedList 类型,可接受多个 SecurityGroupIds 值。
JSON 模板:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Parameters": {
"SecurityGroups": {
"Type": "CommaDelimitedList",
"Description": "The list of SecurityGroupIds in your Virtual Private Cloud (VPC)",
"Default": "sg-a123fd85, sg-b456ge94"
}
},
"Resources": {
"MyEC2Instance": {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId": "ami-79fd7eee",
"KeyName": "testkey",
"SecurityGroupIds": {
"Ref": "SecurityGroups"
}
}
}
}
}
YAML 模板:
AWSTemplateFormatVersion: 2010-09-09
Parameters:
SecurityGroups:
Type: CommaDelimitedList
Description: The list of SecurityGroupIds in your Virtual Private Cloud (VPC)
Default: sg-a123fd85, sg-b456ge94
Resources:
MyEC2Instance:
Type: 'AWS::EC2::Instance'
Properties:
ImageId: ami-79fd7eee
KeyName: testkey
SecurityGroupIds: !Ref SecurityGroups