These were likely added after this question was asked, but for anyone that comes across this now, this can be done with Conditions in CloudFormation.
So if we start with your Parameters declaration
"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."
},
},
We could add a Conditions
declaration, with a condition ShouldCreateSecurityGroup
"Conditions" : {
"ShouldCreateSecurityGroup" : {"Fn::Equals" : [{"Ref" : "SecurityGroup"}, "default"]}
},
This condition can now be used to tell CloudFormation whether to create a security group:
"Resources": {
"NewSecurityGroup": {
"Type" : "AWS::EC2::SecurityGroup",
"Condition" : "ShouldCreateSecurityGroup"
"Properties" : {
"SecurityGroupEgress" : [ Security Group Rule, ... ],
"SecurityGroupIngress" : [ Security Group Rule, ... ],
}
}
}
Then when you go to reference the value in this, you can use the Fn::If Conditional function to say whether you want to use the value from the SecurityGroup
parameter or the NewSecurityGroup
Resource. For example, for passing the value into the SecurityGroups
parameter of an EC2 instance, we could use {"Fn::If}
like:
"Server": {
{
"Type" : "AWS::EC2::Instance",
"Properties" : {
...
"SecurityGroups" : [ {"Fn::If": ["ShouldCreateSecurityGroup", {"Ref": "NewSecurityGroup"}, {"Ref": "SecurityGroup"}]} ],
}
}
}