user60679
user60679

Reputation: 729

AWS get security group ids from private IP

How to get the security group ids associated to the ec2-instance based on Private IP Address So, want to automate process of modifying security group ingress.

eg: open port 22 on 10.0.0.10 from 10.0.0.11

I want to get the sg-xxxxxx associate to 10.0.0.10 and add ingress FromPort:22 ToPort:22 Cidr:10.0.0.11/32

Upvotes: 2

Views: 210

Answers (2)

user60679
user60679

Reputation: 729

#!/usr/bin/python

import subprocess
from sys import argv
import sys, getopt

ipaddress=" "
protocol = " "
FromPort = " "
ToPort = " "
CidrIP = " "

opts, args = getopt.getopt(argv[1:],"hi:h:p:f:t:c:",["help","ip=","protocol=","FromPort=","ToPort=","CidrIp="])
for opt, arg in opts:
   if opt in ("-h", "--help"):
      print "Usage: -i x.x.x.x -p icmp -f 22 -t 22 -c x.x.x.x/x"
      sys.exit()
   elif opt in ("-i", "--ipaddress"):
      ipaddress = arg
   elif opt in ("-p", "--protocol"):
      protocol = arg
   elif opt in ("-f", "--fromport"):
      FromPort = arg
   elif opt in ("-t", "--toport"):
      ToPort = arg
   elif opt in ("-c", "--cidrip"):
       CidrIP = arg
   else:
       print 'Invalid argument'

subprocess.call("aws ec2 describe-instances --filters \"Name=private-ip-address,Values="+ipaddress+"\" --query \"Reservations[*].Instances[*].SecurityGroups[*]\" --output text > /tmp/sg.txt", shell=True)
sg_id = []
with open('/tmp/sg.txt', 'r') as f:
    for line in f:
        sg_id.append(line.split(None, 1)[0])

subprocess.call("aws ec2 authorize-security-group-ingress --group-id"+ " "+sg_id[0] + " "+"--ip-permissions '[{\"IpProtocol\":"+ " "+"\""+protocol+"\""+"," " "+ "\"FromPort\":"+ " "+FromPort+"," " "+ "\"ToPort\":"+ " "+ToPort+"," " "+ "\"IpRanges\":"+ " "+"[{\"CidrIP\":"+ " "+"\""+CidrIP+"\""+"}]}]'", shell=True)

print("successful")

Upvotes: 0

Mark B
Mark B

Reputation: 201088

You can get the the security group(s) from this command (replace X.X.X.X with the private IP address):

aws ec2 describe-instances --filters "Name=private-ip-address,Values=X.X.X.X" \
    --query "Reservations[*].Instances[*].SecurityGroups[*]" --output text

After that, it should be a simple call to aws ec2 authorize-security-group-ingress to open the port.

This could easily be wrapped in a Bash script, you would just need some way of determining which security group to modify if an instance is a member of more than one.

Upvotes: 2

Related Questions