Created
          May 18, 2016 15:12 
        
      - 
      
- 
        Save trebortech/6a468c61cb28293a539a1b89391f44b4 to your computer and use it in GitHub Desktop. 
    AWS custom grains
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | #!/usr/bin/env python | |
| # encoding: utf-8 | |
| # Standard Libs | |
| import logging | |
| # First Party Libs | |
| import requests | |
| from requests.adapters import HTTPAdapter | |
| def ec2(): | |
| """Returns custom grains from AWS EC2. | |
| """ | |
| urls = { | |
| 'id': 'http://169.254.169.254/latest/meta-data/instance-id', | |
| 'ip': 'http://169.254.169.254/latest/meta-data/local-ipv4' | |
| } | |
| grains = { | |
| 'ec2': {} | |
| } | |
| s = requests.Session() | |
| s.mount('http://169.254.169.254', HTTPAdapter(max_retries=1)) | |
| for name, url in urls.iteritems(): | |
| try: | |
| req = s.prepare_request(requests.Request('GET', url)) | |
| rsp = s.send(req, timeout=0.5) | |
| except: | |
| logging.warn('Not able to get AWS Meta Data: {0}'.format(name)) | |
| else: | |
| grains['ec2'][name] = rsp.text | |
| return grains | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment