如何将多个值用于 AWS CloudFormation 模板中的单个参数?

2 分钟阅读
0

我想为单个参数使用多个值从 AWS CloudFormation 模板创建或更新堆栈。

简短描述

您可以通过以下方式之一将多个值用于 AWS CloudFormation 模板中的单个参数

解决方法

使用 AWS 特定的参数类型,从 AWS 账户的现有 AWS 值预填充列表中选择值

**重要提示:**AWS CloudFormation 会根据您账户中现有的值来验证您选择的输入值。

在这些示例 AWS CloudFormation 模板中,含有 SecurityGroups 键的参数指定了一个可接受将多个值用于 SecurityGroupIds 的 AWS 特定的参数类型。

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

要使用 AWS CLI 部署堆栈,请使用以下命令:

**注意:**将 StackName 替换为您的堆栈名称。将 TemplateFileName 替换为您的文件名。对于 ParameterValue,请输入您的安全组 ID。

aws cloudformation create-stack --stack-name StackName --template-body file://TemplateFileName
--parameters ParameterKey=SecurityGroups,ParameterValue="sg-0123456789\,sg-2345678901"

使用 CommaDelimitedList 参数类型键入输入值

在以下 AWS CloudFormation 模板示例中,含有 SecurityGroups 键的参数指定了一个可接受将多个值用于 SecurityGroupIdsCommaDelimitedList 参数类型。

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

AWS 官方
AWS 官方已更新 1 年前