1

我有一个安全组参数:

"Parameters" : {
 "SecurityGroup" : {
   "Description" : "Name of an existing EC2 Security Group ",
   "Type" : "String",
   "Default" : "default", 
   "MinLength": "1",
   "MaxLength": "64",
   "AllowedPattern" : "[-_ a-zA-Z0-9]*",
   "ConstraintDescription" : "can contain only alphanumeric characters, spaces, dashes and underscores."
  },
},

但是,如果没有指定参数,我想创建一个,而不是使用默认值。这可能吗?

4

2 回答 2

1

这些可能是在提出此问题后添加的,但对于现在遇到此问题的任何人,都可以使用 CloudFormation 中的条件来完成。

因此,如果我们从您的参数声明开始

"Parameters" : {
 "SecurityGroup" : {
   "Description" : "Name of an existing EC2 Security Group ",
   "Type" : "String",
   "Default" : "default", 
   "MinLength": "1",
   "MaxLength": "64",
   "AllowedPattern" : "[-_ a-zA-Z0-9]*",
   "ConstraintDescription" : "can contain only alphanumeric characters, spaces, dashes and underscores."
  },
},

我们可以添加一个Conditions带有条件的声明ShouldCreateSecurityGroup

"Conditions" : {
  "ShouldCreateSecurityGroup" : {"Fn::Equals" : [{"Ref" : "SecurityGroup"}, "default"]}
},

此条件现在可用于告诉 CloudFormation 是否创建安全组:

"Resources": {
  "NewSecurityGroup": {
    "Type" : "AWS::EC2::SecurityGroup",
    "Condition" : "ShouldCreateSecurityGroup" 
    "Properties" : {
       "SecurityGroupEgress" : [ Security Group Rule, ... ],
       "SecurityGroupIngress" : [ Security Group Rule, ... ],
    }
  }
}

那么当你去引用this里面的值的时候,你可以使用Fn::If Conditional函数来说明你是想使用SecurityGroup参数中的值还是NewSecurityGroupResource中的值。例如,要将值传递给SecurityGroupsEC2 实例的参数,我们可以使用{"Fn::If}如下:

"Server": {
  {
    "Type" : "AWS::EC2::Instance",
    "Properties" : {
        ...
      "SecurityGroups" : [ {"Fn::If": ["ShouldCreateSecurityGroup", {"Ref": "NewSecurityGroup"}, {"Ref": "SecurityGroup"}]} ],
    }
  }
}
于 2017-09-13T03:41:49.823 回答
0

否 - Cloud Formation 是一种声明性语言,因此很遗憾没有“if/else”。

您甚至不能通过创建自己的然后将“Ref”传递给参数来做到这一点,因为参数部分在脚本执行之前被解析和评估。

你可以用嵌套的云形成脚本做一些事情,但我还没有玩够它来确定它是否可能。所以对我来说 - 你会有一个脚本,它需要一个参数。如果提供了参数,则直接将其传递给第二个云结构,但如果未提供,则执行第一个云结构并返回新创建的安全组的名称,然后将其传递给第二个云形成。

于 2013-08-20T10:39:52.180 回答