Is it possible to update an existing EC2 security group from CloudFormation?

I have a manually created security group to access Redis, and I am creating a LAMP stack with AWS CloudFormation. I need to update the Amazon EC2 security group from Redis to allow access from this LAMP stack, but I want it to be updated through CloudFormation - is this possible?


Solution 1:

Existing SecurityGroups can be updated using SecurityGroupIngress

For example:

"SecurityGroupRedisIngress": {
    "Type": "AWS::EC2::SecurityGroupIngress",
    "Properties" : {   
        "GroupId": "sg-123456789",
        "IpProtocol": "tcp",
        "FromPort": "6379",
        "ToPort": "6379",
        "CidrIp": "1.2.3.4/0"
    }
}

Solution 2:

Yes you can update it. Make necessary changes to your cloud formation template and execute the below command with necessary template and parameter file or list of parameters.

Its always good practice to validate the template after making changes to your template using below command. Once the validation is good you can execute the update stack command.

aws cloudformation validate-template --template-body "file://mention_your_template_name (example.json)"

aws cloudformation update-stack --stack-name "Mention you stack name" --template-body "file://mention_your_template_name (example.json)" --parameters "file://mention_your_parameter_file or list_of_parameters (example_parameters.json)"

Once you have updated the template, open the aws cloudformation console and click on you stack and under it click on the resources console and watch out for the resources that you have updated.

you can modify any AWS resources in the template, but you need to be cautioned when you deal with the RDS or so...check for aws documentation as while updating the resources it will recreate those. Its recommended to take a snapshot for databases. But for security group its fine.