Python Forum

Full Version: AWS ELB auto tagging with Lambda and boto 3
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to build a function to auto tag aws elb v1 and v2 with cloud watch events, lambda, boto3 and python 2.7

elb v1 and v2 have same cloud watch event name CreateLoadBalancer, but json response is different.

I'm able to tag elb v2 with code as shown below, but getting KeyError('loadBalancers',)for elb v1

**elif eventname == 'CreateLoadBalancer':
    rlb = detail['responseElements']['loadBalancers']
    if rlb:
        for loadbalarn in rlb:
            elbv2.append(loadbalarn['loadBalancerArn'])
        logger.info(elbv2)
    else:
        elbv1.append(detail['requestParameters']['loadBalancerName'])
        logger.info(elbv1)**
ELB V1 json response -
ELB V2 json response -
Please provide any suggestions.

Thank you.

python-2.7
(Aug-13-2018, 05:22 AM)karteekdavid Wrote: [ -> ]but getting KeyError('loadBalancers',)for elb v1
Because there is no loadBalancers in ELB V1 json.
>>> d['responseElements']['loadBalancers']
Traceback (most recent call last):
  File "<string>", line 449, in runcode
  File "<interactive input>", line 1, in <module>
KeyError: 'loadBalancers'

>>> d['responseElements']
{'dNSName': 'my-loadbalancer-1234567890.elb.amazonaws.com'}
>>> d['responseElements']['dNSName']
'my-loadbalancer-1234567890.elb.amazonaws.com'
Thanks for letting me know.

Would it be possible to append elbv1.append(detail['requestParameters']['loadBalancerName']) if there is no loadBalancers in detail['responseElements']
Can do try/except if it fail with KeyError then append something else or can also pass out error so it continue.
>>> elbv1 = []
>>> try:
...     elbv1.append(d['responseElements']['loadBalancers'])
... except KeyError:
        # pass    
...     elbv1.append(d['responseElements'])
...     
>>> elbv1
[{'dNSName': 'my-loadbalancer-1234567890.elb.amazonaws.com'}]
Thanks a lot for your advise, I was able to modify the code and accomplish tagging for ELB V1 and V2