Using Cloud Formation provisioned security group with specific subnet

amazon ec2amazon-cloudformation

Summary

I'm attempting to create an AWS CloudFormation template which contains an instance for which I want to select a particular subnet. If I specify the subnet ID then I get the following error The parameter groupName cannot be used with the parameter subnet. From reading this thread it appears I need to provide security group IDs – not names. How can I create a security group in CloudFormation and then get its ID after the fact?

Details

The relevant part of the instance config is as follows

"WebServerHost": {
  "Type" : "AWS::EC2::Instance",
 <..skipping metadata...>
 "Properties": {
    "ImageId" : { "ami-1234" },
    "InstanceType" : { "Ref" : "WebServerInstanceType" },
    "SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],
    "SubnetId"       : "subnet-abcdef123",

and the security group looks as follows

"WebServerSecurityGroup" : {
  "Type" : "AWS::EC2::SecurityGroup",
  "Properties" : {
    "GroupDescription" : "Enable HTTP and SSH",
    "SecurityGroupIngress" : [
      {"IpProtocol" : "tcp", "FromPort" : "80", "ToPort" : "80", "CidrIp" : "0.0.0.0/0"},
      {"IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" : "0.0.0.0/0"}
    ]
  }
},

How can I create and then get that security group's ID?

Best Answer

You just need to change this line:

"SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],

to this:

"SecurityGroupIds" : [ {"Ref" : "WebServerSecurityGroup"} ],

Per the Cloudformation documentation on the topic, the SecurityGroups attribute is only valid for EC2 security groups. You're using VPC, so you need to use SecurityGroupIds.