Introduction
Managing secure access to AWS resources like bastion servers can be challenging when you’re dealing with dynamic IPs or CGNAT. I am in the same boat where I have a bastion server that needs to be accessible from my current IP address, which changes frequently since its CGNAT-based.
So here’s the solution that I came up with: A simple Bash script that automatically updates the AWS security group rules to include my current public IP address. This ensures that you can always securely access your bastion server without manually updating the security group every time my IP changes.
This is similar to the Dynamic DNS service via Cloudflare which I talked about in past but instead of updating IP in Cloudflare, we are now updating it for AWS security group.
Prerequisites
-
AWS CLI: Ensure you have AWS CLI ↗️ installed and configured with appropriate permissions to update the security group. If you are using homebrew then the command would be:
brew install awscli
Run
aws configure
to set up your AWS access key, secret key, and region and then you should be good to go. -
jq: This script uses
jq
for JSON parsing, so ensure it’s installed on your system. You can install it using your package manager (e.g.,brew install jq
via homebrew).
The Script
Here’s how it works:
-
Fetches Your Current IP
we use curl to retrieve your public IP from
checkip.amazonaws.com
. -
Checks Existing Security Group Rules:
Next we use the AWS CLI to inspect the current rule of the specified security group and security group rule.
đź’ˇPre-requisite
Make sure that you have initially added a new security group rule for your IP address one time and then take a note of the security group rule id from it.
-
Compares and Updates
If the IP has changed, the script updates the security group rule with your new IP.
Update the permissions for running the script:
And run it like this:
Run it Periodically
Running it once is fine, but what we really want is a way to periodically run this script so that our current IP address is in sync with the one added in the AWS security group. To achieve this, we can use SystemD timers or Cron Jobs.
For something like this, a cron job is more than enough so let’s set it up.
Open the crontab editor first using this command:
And add the contents at the last line:
Replace /path/to
with the actual path where you have stored the script.
The above mentioned config will run this script every day at 11:00AM. Feel free to update the frequency as per your need.
Conclusion
By automating IP updates in AWS security groups, you save time and ensure seamless access to your AWS resources. With this simple script, you can focus on what really matters without worrying about IP changes. Try it out and make your AWS environment smarter!
If you have any questions or comments, feel free to reach out to me on Twitter ↗️ / Reddit ↗️ or drop a comment below.