Member-only story

Modifying EC2 security groups via AWS Lambda functions

Grig Gheorghiu
2 min readJan 11, 2018

--

One task that comes up again and again is adding, removing or updating source CIDR blocks in various security groups in an EC2 infrastructure. This can be automated either fully or partially with the help of simple AWS Lambda functions.

Example 1: Checking a Dynamic DNS IP and replacing it in an EC2 security group

This scenario arises when you have a user without a static IP. They can still get a Dynamic DNS name and have it automatically point to their local dynamic IP. You can check for that name periodically, and update the appropriate rules within EC2 security group(s).

Here is an AWS Lambda function named UpdateSecurityGroupWithHomeIP and written in Python 2.7 that achieves this goal:

A few observations:

  • it’s not trivial to do DNS lookups within Lambda, so I preferred to do the DNS lookup in the caller, and pass the resulting IP address as the sole argument to the above Lambda function — which is retrieved as new_ip_address in the lambda_handler function
  • in the update_security_group function I iterate through all permission objects in the IpPermissions list associated to the given security group and I create a deep copy of…

--

--

Grig Gheorghiu
Grig Gheorghiu

Written by Grig Gheorghiu

DevOps, cloud computing, Python and Golang programming, data science, automated testing.

Responses (1)