How to add a security group to an existing EC2 instance with CloudFormation

Viewed 8455

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 Answers

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
Related