简体   繁体   中英

Boto to Boto3 function implementation

1) How can i implement this from boto into boto3 code:

conn = boto.connect_ec2()  # boto way
sgs = conn.get_all_security_groups()  # boto way
for sg in sgs:
    if len(sg.instances()) == 0:
        print(sg.name, sg.id, len(sg.instances()))

The above code basically prints all Security Groups with no instances attached.


2) And this individual command which uses duct.sh() module :

command = 'aws ec2 describe-instances --filters "Name=instance.group-id,Values=' + sg.id + '\" --query \'Reservations[*].Instances[*].[InstanceId,Tags[?Key==`Name`]  | [0].Value]\' --output json'

boto: get_all_security_groups()

boto3: security_group_iterator = ec2.security_groups.all()

However, boto has the .instances() method on boto.ec2.securitygroup.SecurityGroup , whereas boto3 does not have an equivalent method on ec2.SecurityGroup .

Therefore, it looks like you would have to call describe_instances() , passing the security group as a Filter :

response = client.describe_instances(
  Filters=[{'Name':'instance.group-id','Values':['sg-abcd1234']}])

This will return a list of instances that use the given security group.

You could then count len(response['Reservations']) to find unused security groups. (Note: This is an easy way to find zero-length responses, but to count the actual instances would require adding up all Reservations.Instances .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM