是否可以从子网列表中选择要在CloudFormation中启动EC2实例的位置?

时间:2019-06-13 18:23:24

标签: amazon-web-services amazon-cloudformation

我对AWS和CloudFormation还是很陌生,我试图做一个CF模板来启动三个不同的环境,但是我希望能够选择在不对特定子网进行硬编码的情况下启动EC2实例的子网。模板。但是,在下面的示例中,我收到一个错误,提示SubnetId必须为字符串。我想不出任何其他方式来实现这一目标。有什么想法吗?

Parameters:
  EnvironmentType:
    Type: String
    Default: Dev  
    AllowedValues:
      - Dev  
      - Test 
      - Production
    Description: Select Environment Type (Dev, Test, Production)
  SubnetIdList:
    Type: String
    AllowedValues: 
      - Public1
      - Public2
      - Private
    Description: Select a subnet



Mappings:
  InstanceSize:
    Dev:
      "EC2" : "t3.micro"
    Test:
      "EC2" : "t3.small"
    Production:
      "EC2" : "t3.medium"
  Sub:
    Public1:
      "Subnet" : "subnet-05daa558dc3f65529" #public 1
    Public2:
      "Subnet" : "subnet-0f57bb83e0fc545f4" #public 2
    Private:
      "Subnet" : "subnet-0eb76c49954acc803" #Private




Resources:
  EC2:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-0080e4c5bc078760e
      InstanceType: !FindInMap [InstanceSize, !Ref EnvironmentType, EC2]
      KeyName: Ashkelon
      SubnetId: [Sub, !Ref SubnetIdList, Subnet]

1 个答案:

答案 0 :(得分:1)

我认为您只是在Ec2子网参数定义中缺少!FindInMap。见下文

Resources:
  EC2:
     Type: AWS::EC2::Instance
     Properties:
     ImageId: ami-0080e4c5bc078760e
     InstanceType: !FindInMap [InstanceSize, !Ref EnvironmentType, EC2]
     KeyName: Ashkelon
     SubnetId: !FindInMap [Sub, !Ref SubnetIdList, Subnet]