Murphy
Murphy

Reputation: 556

How to get the resource for a given security group using python boto?

Given a security group I am able to find the associated EC2 instance to which the security group is attached using:

sgs   = conn.get_all_security_groups( filters = {'group-name':grouplist})

for sg in sgs:
    for instance in sg.instances():
        print sg.name,instance.id,i.ip_address

How can I get the same information for say an RDS or ELB to which the security group is attached.

Note that the security groups are the general VPC SG's which are seen in EC2 console window but in my case have also been used on RDS and ELB's

Upvotes: 1

Views: 1748

Answers (1)

phoenix
phoenix

Reputation: 3159

The below may not be the best solution but this will work. I have given boto3 examples.

For ELB, you can get all the load balancers in your account using describe_load_balancers and by without specifying any loadbalancer in the argument for that method. This also gives the security group(s) associated with each ELB. You can loop on the ELB list. Create a map of security Group name and ELB list i.e, something like :

{ 'sg1' : [elb1, elb2], 
  'sg2' : [elb3, elb5]
}

This can be done by looping through the security groups in an ELB.

i.e, something like below (Not a perfect working code but you can get an idea):

sgDict = {}
for elb in Elbs:
    Sgs = elb['SecurityGroups']
    for sg in Sgs:
        elbName = elb['LoadBalancerName']
        if sg in sgDict:
            elbList = sgDict[sg];
            elbList.append(elbName);
            sgDict[sg] = elbList;
        else:
            sgDict[sg] = [elbName]

        

For RDS, you can do similar thing with describe_db_instances

Upvotes: 1

Related Questions