Home Bash Script to Add ISP IP to Security Group
Post
Cancel

Bash Script to Add ISP IP to Security Group

Suppose, you have an EC2 instance and you need to access it when you are travelling or changing your network provider. Accessing IP restricted AWS Services is a headache as you need to add your ISP IP address to security group everytime your ISP IP address changes (unless you are using a VPN!).

Here is a simple bash script that adds your current ISP IP address to security group for SSH access:

Prerequisites

We are going to update an exisiting rule from the security group and the ID of security group and rule are passed as variables.

image2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash

region="us-west-2"
sg_id="sg-0ea2b5969193e6cbe"
rule_id="sgr-0769caf4f93569b25"
protocol="TCP"
port=22

# Get the ISP IP address
isp_ip=$(wget -qO- ifconfig.me | awk '{print $1}'| sed 's/$/\/32/')

# Print the ISP IP 
echo "Your ISP IP is $isp_ip"
aws ec2 --region $region modify-security-group-rules \
	    --group-id $sg_id \
	        --security-group-rules SecurityGroupRuleId=$rule_id,SecurityGroupRule='{IpProtocol="TCP",FromPort="'"$port"'",ToPort="'"$port"'",CidrIpv4="'"$isp_ip"'",Description="ISP IP"}'

You can copy the script and give execute permission to this. Once you execute the script, it will add your ISP IP address to the SSH inbound rule of the security group.

This post is licensed under CC BY 4.0 by the author.