Created
February 26, 2015 20:19
-
-
Save perzizzle/532e8a5359bc76886724 to your computer and use it in GitHub Desktop.
Ansible module to run tower-cli
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/python | |
| DOCUMENTATION = ''' | |
| --- | |
| module: tower-cli | |
| short_description: Trigger ansible tower jobs from ansible tower | |
| description: | |
| - Use tower-cli to trigger jobs | |
| options: | |
| job_number: | |
| description: | |
| - The ansible tower unique job id | |
| required: true | |
| host_limit: | |
| description: | |
| - The host_limit for the job | |
| ''' | |
| EXAMPLES = ''' | |
| - tower-cli: job_number={{ job_number }} host_limit={{ host_limit }} | |
| ''' | |
| import sys | |
| import requests | |
| import subprocess | |
| import json | |
| def main(): | |
| module = AnsibleModule( | |
| argument_spec = dict( | |
| job_number = dict(required=True), | |
| host_limit = dict(required=True), | |
| ), | |
| supports_check_mode=False | |
| ) | |
| changed = 'False' | |
| params = module.params | |
| job_number = params['job_number'] | |
| host_limit = params['host_limit'] | |
| try: | |
| # Get job_template info | |
| command = "tower-cli job_template get {0} -f json".format(job_number) | |
| proc = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True) | |
| (out, err) = proc.communicate() | |
| except: | |
| module.fail_json(msg='Unable to get job' + job_number + err) | |
| exit(1) | |
| if not err: | |
| data = json.loads(out) | |
| # Seems odd I have to load twice | |
| extra_vars = json.loads(data['extra_vars']) | |
| extra_vars['host_limit'] = host_limit | |
| # Write extra_vars to file to allow them to be provided at command line | |
| try: | |
| f = open('/tmp/extra_vars.json', 'w') | |
| f.write(json.dumps(extra_vars)) | |
| f.close() | |
| except: | |
| module.fail_json(msg='Unable to write to file') | |
| exit(1) | |
| try: | |
| # Run job | |
| command = "tower-cli job launch --job-template {0} --extra-vars=/tmp/extra_vars.json --monitor".format(job_number) | |
| proc = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True) | |
| (out, err) = proc.communicate() | |
| change = True | |
| except: | |
| module.fail_json(msg='Unable to start job' + job_number + err) | |
| exit(1) | |
| else: | |
| module.fail_json(msg='err') | |
| exit(1) | |
| module.exit_json(job_number=job_number, host_limit=host_limit, changed=changed) | |
| exit(0) | |
| 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