7
votes

Currently, our AWS infrastructure has many instances which are attached to security groups, which I created in the console.

We are re-structuring our security groups with CloudFormation, thus we can have a comment and description in each rule.

My question is:

  • When I create a new Security Group with CloudFormation, how can I add it to an existing EC2 instance, without removing the instance
  • I saw some stack templates in AWS, but they only have a template to create a new Instance with a security group, so I have no idea how to create a stack for only security groups. And if I update the stack, does it apply to all instance immediately?
  • How can I export current security groups to JSON, so I don't have to re-create all the security groups in CloudFormation?
2

2 Answers

7
votes

You can't.

Amazon CloudFormation templates can create resources, and those resources can refer to other resources within the same template. For example, you could create a Security Group and an Instance, and configure the Instance to use the Security Group. When making such references within the template, resources can be referenced by name (eg SecurityGroup1, Web Server).

If you wish resources within a CloudFormation to be associated with resources that already exist, you will need to refer to the external resource via its unique ID.

For example, it is possible to create an Amazon EC2 instance within a CloudFormation template, and refer to an existing security group.

However, your need is the reverse! You wish to modify an existing resource to point to a new resource. For example, modify an existing Instance to point to a new Security Group. This is not possible within a CloudFormation template, because it can only create resources and configure those resources -- it cannot modify resources outside of the template.

Logically, security groups need to exist before creating an Amazon EC2 instance since the instance links to the security groups.

Exporting to JSON

If you wish to export an existing resource to a CloudFormation template (eg export current Security Group definitions), you could use:

-2
votes

Adding security group(s) won't recreate your instance just modifies that.

You can test it:

  • add a security group, execute the changeset
  • add that security group to your instance (in same template) and make a changeset again
YourSecurityGroup:
  < enter code here >

YourInstance:
  Properties:
   SecurityGroupIds:
     - !Ref YourSecurityGroup