Revoke and Grant Public IP Addresses to Amazon EC2 Instances Via AWS Command Line Interface (CLI)
If you work from place to place, such as from one coffee shop to another, and you need access to your Amazon EC2 instances, but you don’t want to allow traffics from all IP addresses. You can use the EC2 Security Groups to allow the IP addresses from those locations. But once you move on to a different location, you want to delete the IP address from the previous location. The process to do these manually and over and over again quickly becomes cumbersome. Here is a command line method that quickly removes all other locations and allows only the traffic from your current location.
The steps are:
- Revoke all existing sources to a particular port
- Grant access to the port only from the current IP address
Assume the following:
- Profile:
default
- Security group:
mygroup
- Protocol:
tcp
- Port:
22
First, revoke access to the port from all IP addresses:
|
|
The aws ec2 describe-security-groups
command before the first pipe returns JSON formatted data, filtered via JMESPath query, which is supported by AWS CLI, for example:
|
|
jq command simply converts an array of JSON to line by line strings, which xarg
takes in, loops through and deletes one IP address at a time.
After this step, all IP addresses originally allowed are all revoked. Next step is to grant access to the port from a single IP address: