Created
February 20, 2016 19:33
-
-
Save yfauser/90c0955827c74d83d6a2 to your computer and use it in GitHub Desktop.
This is an example Ansible Module written in Python demonstrating a couple of key concepts for a Meetup presentation
This file contains 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/python | |
import requests | |
import json | |
def get_temperature(appkey, city, module, units='metric'): | |
session = requests.Session() | |
headers = {'Content-Type': 'application/json'} | |
url = 'http://api.openweathermap.org/data/2.5/weather' | |
params = {'q': city, 'APPID': appkey, 'units': units} | |
try: | |
response = session.request('GET', url, headers=headers, params=params) | |
except requests.exceptions.RequestException as e: | |
module.fail_json(msg=e) | |
if response.status_code not in [200]: | |
module.fail_json(msg=(response.status_code, response.content)) | |
response_content = json.loads(response.content) | |
return response_content['main']['temp'] | |
def main(): | |
module = AnsibleModule( | |
argument_spec=dict( | |
appkey=dict(required=True), | |
city=dict(default='munich,de'), | |
treshold=dict(required=True, type='float') | |
), | |
) | |
city = module.params['city'] | |
treshold = module.params['treshold'] | |
appkey = module.params['appkey'] | |
temperature = get_temperature(appkey, city, module) | |
if temperature > treshold: | |
module.exit_json(changed=True, decision='Run, Yves, Run, it is {} in {}'.format(temperature, city)) | |
if temperature < treshold: | |
module.exit_json(changed=False, decision='Stop, Yves, Stop, it is {} in {}'.format(temperature, city)) | |
from ansible.module_utils.basic import * | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment