如何根据专用IP地址获取与ec2-instance关联的安全组ID 因此,希望自动化修改安全组入口的过程。
例如:从10.0.0.11开始在10.0.0.10上打开端口22
我希望将sg-xxxxxx关联到10.0.0.10并添加ingress FromPort:22 ToPort:22 Cidr:10.0.0.11/32
答案 0 :(得分:2)
您可以从此命令获取安全组(将X.X.X.X
替换为私有IP地址):
aws ec2 describe-instances --filters "Name=private-ip-address,Values=X.X.X.X" \
--query "Reservations[*].Instances[*].SecurityGroups[*]" --output text
之后,应该是aws ec2 authorize-security-group-ingress
打开端口的简单调用。
这可以轻松地包装在Bash脚本中,如果实例是多个成员,您只需要某种方法来确定要修改的安全组。
答案 1 :(得分:0)
#!/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")