Python Forum
AWS ELB auto tagging with Lambda and boto 3
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
AWS ELB auto tagging with Lambda and boto 3
#1
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
Reply
#2
(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'
Reply
#3
Thanks for letting me know.

Would it be possible to append elbv1.append(detail['requestParameters']['loadBalancerName']) if there is no loadBalancers in detail['responseElements']
Reply
#4
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'}]
Reply
#5
Thanks a lot for your advise, I was able to modify the code and accomplish tagging for ELB V1 and V2
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Not able to use boto library with compressed content in python3 avinash2020 1 1,895 Aug-13-2020, 09:24 PM
Last Post: avinash2020
  Boto 3 and Mongo DB zatlas1 2 2,965 May-23-2019, 07:32 PM
Last Post: zatlas1
  Text Processing and NLTK (POS tagging) TwelveMoons 2 4,907 Mar-16-2017, 02:53 AM
Last Post: TwelveMoons

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020