Skip to content

Instantly share code, notes, and snippets.

@jacoelho
Last active February 15, 2016 21:41
Show Gist options
  • Select an option

  • Save jacoelho/d040d5fed9b3139305ac to your computer and use it in GitHub Desktop.

Select an option

Save jacoelho/d040d5fed9b3139305ac to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import json
import ansible.inventory
import ansible.playbook
import ansible.runner
import ansible.constants
from ansible import utils
from ansible import callbacks
def handler(event, context):
valid_parameters = ['playbook', 'inventory', 'remote_user', 'become',
'become_user', 'extra_vars', 'only_tags',
'skip_tags', 'subset']
message = event['Records'][0]['Sns']['Message']
values = json.loads(message)
parameters = {
key: value for key, value in values.iteritems()
if key in valid_parameters}
if 'inventory' in parameters:
parameters['inventory'] = ansible.inventory.Inventory(parameters[
'inventory'])
return run_playbook(**parameters)
def run_playbook(**kwargs):
stats = callbacks.AggregateStats()
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
runner_cb = callbacks.PlaybookRunnerCallbacks(
stats, verbose=utils.VERBOSITY)
ansible.constants.DEFAULT_REMOTE_TMP = '/tmp/ansible'
out = ansible.playbook.PlayBook(
callbacks=playbook_cb,
runner_callbacks=runner_cb,
stats=stats,
**kwargs
).run()
return out
def main():
test = {
"Records": [
{
"EventVersion": "1.0",
"EventSubscriptionArn": "arn:aws:sns:EXAMPLE",
"EventSource": "aws:sns",
"Sns": {
"Message": "{\"playbook\": \"test.yml\", \"inventory\": [\"localhost\"]}",
}
}
]
}
return(handler(event=test, context=None))
if __name__ == '__main__':
print(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment