My particular use case was that In my own AWS Account where I do most of the R&D I had one security group which was only for me doing SSH into EC2 instances. Way back in 2020 during pandemic season, had to go freelance for sometime while in notice period with one company and in negotiation with another one. Well this time I was mostly connected from mobile hotspot switching from JIO on Galaxy M14 to Airtel on Galaxy A54 and BSNL on second sim of M14 and this was causing my security group update a real pain.
Basically being lazy and having devops and automation since long back. Started working on an idea an the outcome was an AWS Serverless clone of what is my ip service which is named echo my ip. Check it out on github. The nodejs code and aws sam template to deploy is given over there.
Next using the standard Ubuntu terminal text editor added the following to the .bash_aliases file.
sgupdate()
{
currentip=$(curl --silent https://{api gateway url}/Prod/ip/)
/usr/local/bin/aws ec2 describe-security-groups --group-id $AWS_SECURITY_GROUP > /dev/shm/permissions.json
grep CidrIp /dev/shm/permissions.json | grep -v '/0' | awk -F'"' '{print $4}' | while read cidr;
do
/usr/local/bin/aws ec2 revoke-security-group-ingress --group-id $AWS_SECURITY_GROUP --ip-permissions "FromPort=-1,IpProtocol=-1,IpRanges=[{CidrIp=$cidr}]"
done
/usr/local/bin/aws ec2 authorize-security-group-ingress --group-id $AWS_SECURITY_GROUP --protocol "-1" --cidr "$currentip/32"
}
alias aws-permit-me='sgupdate'
I already have a .env file for every project I am handling and a cd command will check for existance of .env and source it in case it exists.
cwd(){
cd $1
if [ -f .env ] ; then
. .env
fi
}
alias cd='cwd'
The env file is of structure as follows with coresponding values after the ‘=’ ofcourse.
export AWS_DEFAULT_REGION=
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export AWS_SECURITY_GROUP=
export AWS_SSH_ID=
export AWS_ACCOUNT=
It’s a common problem for people working from home with dynamic IPs to manage firewall rules. Automating the process with a serverless function and a shell alias is a great way to simplify things. Sharing on github is to help others and provide back to the community.
This method provides some advantages
- Automation: Eliminates the tedious manual process of updating security group rules.
- Serverless: Cost-effective, as you only pay for the compute time used.
- Shell Alias: Provides a convenient and easy-to-remember way to trigger the update.
- GitHub Sharing: Makes the solution accessible to others.
- Secure: Security Group Modification uses aws cli and credentials in terminal environment