-->

Update AWS Security Groups with PowerShell

awssecurity powershell, ec2

Here’s the scenario:

  • You use AWS
  • You don’t have a static IP
  • You connect to your EC2 instances via SSH and/or RDP only from your IP
  • You are too lazy to update the security groups manually when your IP changes!

You’ve come to the right place: I’ve got the solution.

Let’s have a look how it’s built step-by-step:

Step 1: Create an IAM account to access security groups

As a general rule of thumb always grant the minimum privileges possible to the accounts you use. Create a new user and go to the user’s details. Select Attach User Policy and then Policy Generator. Select AWS EC2 from the services list. For our script to run we need 3 privileges: List security groups (DescribeSecurityGroups), delete old IP permissions (RevokeSecurityGroupIngress) and add new IP permissions (AuthorizeSecurityGroupIngress).

Alternatively you can just attach the following policy to your user:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1418339796000",
      "Effect": "Allow",
      "Action": [
        "ec2:AuthorizeSecurityGroupIngress",
        "ec2:DescribeSecurityGroups",
        "ec2:RevokeSecurityGroupIngress"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}

IAM has a very nice simulation feature. Before you proceed I recommend you run it and verify only 3 actions are allowed.

Step 2: Modify the PowerShell script

The script I created is on Gist as seen below. Before you can use it you have to update it with the access and secret keys of the user created above.

Also since fiddling with security groups can become messy very quickly I’d strongly recommend you perform a dry run first. By default $dryRun is set to true. Unless you set it to $false it will only display what it is going to do but will not take any action. So make sure you know what you’re doing before you give it a go. I don’t think this script will be a ready-made script for anyone. Probably would need some tweaking here and there to tailor to your needs. But this version works for me so here it is:

First it gets a list of security groups that have SSH and RDP permissions in them. Then loops through these permissions and compares the IP address with the current one. I used my own external IP checker service that I’ve recently developed as I blogged here. You can use other services as well. Just make sure you change the URL in the script. My service returns a JSON object so if the method you use returns a different format you need to modify the parsing code as well.

If the IP addresses are different, it revokes the old permission and creates a new one with your current IP. Protocol and ports remain intact.

This is the output of the script:

If the IP addresses for port 22 an 3389 are up-to-date it just displays “Security group is up-to-date” so it can be run consecutively. So you can schedule it to run as often as you want.

Resources