Whitelist IP addresses to AWS Security Groups using Terraform and Bash

Gika Megawan Pramudita
1 min readMay 15, 2020

--

When we need to whitelist several IP addresses to all security groups on the AWS account, it would be painful to update each of them manually. So, we have to create a simple script to update it with less effort. Before we start, I assume you know how to work with AWS CLI and Terraform.

First, we create a new security group that contained IP addresses by using Terraform.

Query all security group IDs in the AWS account by redirect output to file.

aws ec2 describe-security-groups --profile development --query 'SecurityGroups[*].{GroupId:GroupId}' --output text > sg.txt

Query the security group ID by filtering the security group name.

aws ec2 describe-security-groups --profile development --filters Name=group-name,Values=vpn-ssh --query 'SecurityGroups[*].{GroupId:GroupId}' --output text

Next, whitelist new security group that contained new IP addresses inside existing security groups, and redirect output file to blackhole.

aws ec2 authorize-security-group-ingress --profile $environment --group-id $line --protocol tcp --port 22 --source-group $vpnssh > /dev/null 2>&1

Finally, we use bash while loop to repeat the line in the file that contained security group ids.

--

--

Gika Megawan Pramudita

SRE and DevOps practitioner who enjoys writing about tech and occasionally sharing bits of my life.