Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 496
Tien Dung Tran Avatar asked May 25 '17 07:05

Tien Dung Tran


People also ask

How do I add a key pair to EC2 instance in CloudFormation?

The key pair can either be imported or created by Amazon EC2, as follows: To import an existing key pair, include the PublicKeyMaterial property in the template. To create a new key pair, omit the PublicKeyMaterial property.


1 Answers

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:

  • Using CloudFormer to Create AWS CloudFormation Templates from Existing AWS Resources
  • hava.io
  • visualops.io
like image 144
John Rotenstein Avatar answered Oct 02 '22 23:10

John Rotenstein