Initial commit
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
class ModuleDocFragment(object):
|
||||
|
||||
# Ansible Tower documentation fragment
|
||||
DOCUMENTATION = r'''
|
||||
options:
|
||||
tower_host:
|
||||
description:
|
||||
- URL to your Tower or AWX instance.
|
||||
- If value not set, will try environment variable C(TOWER_HOST) and then config files
|
||||
- If value not specified by any means, the value of C(127.0.0.1) will be used
|
||||
type: str
|
||||
tower_username:
|
||||
description:
|
||||
- Username for your Tower or AWX instance.
|
||||
- If value not set, will try environment variable C(TOWER_USERNAME) and then config files
|
||||
type: str
|
||||
tower_password:
|
||||
description:
|
||||
- Password for your Tower or AWX instance.
|
||||
- If value not set, will try environment variable C(TOWER_PASSWORD) and then config files
|
||||
type: str
|
||||
tower_oauthtoken:
|
||||
description:
|
||||
- The Tower OAuth token to use.
|
||||
- This value can be in one of two formats.
|
||||
- A string which is the token itself. (i.e. bqV5txm97wqJqtkxlMkhQz0pKhRMMX)
|
||||
- A dictionary structure as returned by the tower_token module.
|
||||
- If value not set, will try environment variable C(TOWER_OAUTH_TOKEN) and then config files
|
||||
type: raw
|
||||
version_added: "3.7"
|
||||
validate_certs:
|
||||
description:
|
||||
- Whether to allow insecure connections to Tower or AWX.
|
||||
- If C(no), SSL certificates will not be validated.
|
||||
- This should only be used on personally controlled sites using self-signed certificates.
|
||||
- If value not set, will try environment variable C(TOWER_VERIFY_SSL) and then config files
|
||||
type: bool
|
||||
aliases: [ tower_verify_ssl ]
|
||||
tower_config_file:
|
||||
description:
|
||||
- Path to the Tower or AWX config file.
|
||||
- If provided, the other locations for config files will not be considered.
|
||||
type: path
|
||||
|
||||
notes:
|
||||
- If no I(config_file) is provided we will attempt to use the tower-cli library
|
||||
defaults to find your Tower host information.
|
||||
- I(config_file) should contain Tower configuration in the following format
|
||||
host=hostname
|
||||
username=username
|
||||
password=password
|
||||
'''
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
class ModuleDocFragment(object):
|
||||
|
||||
# Ansible Tower documentation fragment
|
||||
DOCUMENTATION = r'''
|
||||
options:
|
||||
tower_host:
|
||||
description:
|
||||
- URL to your Tower or AWX instance.
|
||||
- If value not set, will try environment variable C(TOWER_HOST) and then config files
|
||||
- If value not specified by any means, the value of C(127.0.0.1) will be used
|
||||
type: str
|
||||
tower_username:
|
||||
description:
|
||||
- Username for your Tower or AWX instance.
|
||||
- If value not set, will try environment variable C(TOWER_USERNAME) and then config files
|
||||
type: str
|
||||
tower_password:
|
||||
description:
|
||||
- Password for your Tower or AWX instance.
|
||||
- If value not set, will try environment variable C(TOWER_PASSWORD) and then config files
|
||||
type: str
|
||||
validate_certs:
|
||||
description:
|
||||
- Whether to allow insecure connections to Tower or AWX.
|
||||
- If C(no), SSL certificates will not be validated.
|
||||
- This should only be used on personally controlled sites using self-signed certificates.
|
||||
- If value not set, will try environment variable C(TOWER_VERIFY_SSL) and then config files
|
||||
type: bool
|
||||
aliases: [ tower_verify_ssl ]
|
||||
tower_config_file:
|
||||
description:
|
||||
- Path to the Tower or AWX config file.
|
||||
- If provided, the other locations for config files will not be considered.
|
||||
type: path
|
||||
|
||||
notes:
|
||||
- If no I(config_file) is provided we will attempt to use the tower-cli library
|
||||
defaults to find your Tower host information.
|
||||
- I(config_file) should contain Tower configuration in the following format
|
||||
host=hostname
|
||||
username=username
|
||||
password=password
|
||||
'''
|
||||
@@ -0,0 +1,48 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2020, Ansible by Red Hat, Inc
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
class ModuleDocFragment(object):
|
||||
|
||||
# Ansible Tower documentation fragment
|
||||
DOCUMENTATION = r'''
|
||||
options:
|
||||
host:
|
||||
description: The network address of your Ansible Tower host.
|
||||
env:
|
||||
- name: TOWER_HOST
|
||||
username:
|
||||
description: The user that you plan to use to access inventories on Ansible Tower.
|
||||
env:
|
||||
- name: TOWER_USERNAME
|
||||
password:
|
||||
description: The password for your Ansible Tower user.
|
||||
env:
|
||||
- name: TOWER_PASSWORD
|
||||
oauth_token:
|
||||
description:
|
||||
- The Tower OAuth token to use.
|
||||
env:
|
||||
- name: TOWER_OAUTH_TOKEN
|
||||
verify_ssl:
|
||||
description:
|
||||
- Specify whether Ansible should verify the SSL certificate of Ansible Tower host.
|
||||
- Defaults to True, but this is handled by the shared module_utils code
|
||||
type: bool
|
||||
env:
|
||||
- name: TOWER_VERIFY_SSL
|
||||
aliases: [ validate_certs ]
|
||||
|
||||
notes:
|
||||
- If no I(config_file) is provided we will attempt to use the tower-cli library
|
||||
defaults to find your Tower host information.
|
||||
- I(config_file) should contain Tower configuration in the following format
|
||||
host=hostname
|
||||
username=username
|
||||
password=password
|
||||
'''
|
||||
@@ -0,0 +1,176 @@
|
||||
# Copyright (c) 2018 Ansible Project
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
|
||||
__metaclass__ = type
|
||||
|
||||
DOCUMENTATION = '''
|
||||
name: tower
|
||||
plugin_type: inventory
|
||||
author:
|
||||
- Matthew Jones (@matburt)
|
||||
- Yunfan Zhang (@YunfanZhang42)
|
||||
short_description: Ansible dynamic inventory plugin for Ansible Tower.
|
||||
description:
|
||||
- Reads inventories from Ansible Tower.
|
||||
- Supports reading configuration from both YAML config file and environment variables.
|
||||
- If reading from the YAML file, the file name must end with tower.(yml|yaml) or tower_inventory.(yml|yaml),
|
||||
the path in the command would be /path/to/tower_inventory.(yml|yaml). If some arguments in the config file
|
||||
are missing, this plugin will try to fill in missing arguments by reading from environment variables.
|
||||
- If reading configurations from environment variables, the path in the command must be @tower_inventory.
|
||||
extends_documentation_fragment: awx.awx.auth_plugin
|
||||
options:
|
||||
inventory_id:
|
||||
description:
|
||||
- The ID of the Ansible Tower inventory that you wish to import.
|
||||
- This is allowed to be either the inventory primary key or its named URL slug.
|
||||
- Primary key values will be accepted as strings or integers, and URL slugs must be strings.
|
||||
- Named URL slugs follow the syntax of "inventory_name++organization_name".
|
||||
type: raw
|
||||
env:
|
||||
- name: TOWER_INVENTORY
|
||||
required: True
|
||||
include_metadata:
|
||||
description: Make extra requests to provide all group vars with metadata about the source Ansible Tower host.
|
||||
type: bool
|
||||
default: False
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
# Before you execute the following commands, you should make sure this file is in your plugin path,
|
||||
# and you enabled this plugin.
|
||||
|
||||
# Example for using tower_inventory.yml file
|
||||
|
||||
plugin: awx.awx.tower
|
||||
host: your_ansible_tower_server_network_address
|
||||
username: your_ansible_tower_username
|
||||
password: your_ansible_tower_password
|
||||
inventory_id: the_ID_of_targeted_ansible_tower_inventory
|
||||
# Then you can run the following command.
|
||||
# If some of the arguments are missing, Ansible will attempt to read them from environment variables.
|
||||
# ansible-inventory -i /path/to/tower_inventory.yml --list
|
||||
|
||||
# Example for reading from environment variables:
|
||||
|
||||
# Set environment variables:
|
||||
# export TOWER_HOST=YOUR_TOWER_HOST_ADDRESS
|
||||
# export TOWER_USERNAME=YOUR_TOWER_USERNAME
|
||||
# export TOWER_PASSWORD=YOUR_TOWER_PASSWORD
|
||||
# export TOWER_INVENTORY=THE_ID_OF_TARGETED_INVENTORY
|
||||
# Read the inventory specified in TOWER_INVENTORY from Ansible Tower, and list them.
|
||||
# The inventory path must always be @tower_inventory if you are reading all settings from environment variables.
|
||||
# ansible-inventory -i @tower_inventory --list
|
||||
'''
|
||||
|
||||
import os
|
||||
|
||||
from ansible.module_utils import six
|
||||
from ansible.module_utils._text import to_text, to_native
|
||||
from ansible.errors import AnsibleParserError, AnsibleOptionsError
|
||||
from ansible.plugins.inventory import BaseInventoryPlugin
|
||||
from ansible.config.manager import ensure_type
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def handle_error(**kwargs):
|
||||
raise AnsibleParserError(to_native(kwargs.get('msg')))
|
||||
|
||||
|
||||
class InventoryModule(BaseInventoryPlugin):
|
||||
NAME = 'awx.awx.tower' # REPLACE
|
||||
# Stays backward compatible with tower inventory script.
|
||||
# If the user supplies '@tower_inventory' as path, the plugin will read from environment variables.
|
||||
no_config_file_supplied = False
|
||||
|
||||
def verify_file(self, path):
|
||||
if path.endswith('@tower_inventory'):
|
||||
self.no_config_file_supplied = True
|
||||
return True
|
||||
elif super(InventoryModule, self).verify_file(path):
|
||||
return path.endswith(('tower_inventory.yml', 'tower_inventory.yaml', 'tower.yml', 'tower.yaml'))
|
||||
else:
|
||||
return False
|
||||
|
||||
def warn_callback(self, warning):
|
||||
self.display.warning(warning)
|
||||
|
||||
def parse(self, inventory, loader, path, cache=True):
|
||||
super(InventoryModule, self).parse(inventory, loader, path)
|
||||
if not self.no_config_file_supplied and os.path.isfile(path):
|
||||
self._read_config_data(path)
|
||||
|
||||
# Defer processing of params to logic shared with the modules
|
||||
module_params = {}
|
||||
for plugin_param, module_param in TowerAPIModule.short_params.items():
|
||||
opt_val = self.get_option(plugin_param)
|
||||
if opt_val is not None:
|
||||
module_params[module_param] = opt_val
|
||||
|
||||
module = TowerAPIModule(
|
||||
argument_spec={}, direct_params=module_params,
|
||||
error_callback=handle_error, warn_callback=self.warn_callback
|
||||
)
|
||||
|
||||
# validate type of inventory_id because we allow two types as special case
|
||||
inventory_id = self.get_option('inventory_id')
|
||||
if isinstance(inventory_id, int):
|
||||
inventory_id = to_text(inventory_id, nonstring='simplerepr')
|
||||
else:
|
||||
try:
|
||||
inventory_id = ensure_type(inventory_id, 'str')
|
||||
except ValueError as e:
|
||||
raise AnsibleOptionsError(
|
||||
'Invalid type for configuration option inventory_id, '
|
||||
'not integer, and cannot convert to string: {err}'.format(err=to_native(e))
|
||||
)
|
||||
inventory_id = inventory_id.replace('/', '')
|
||||
inventory_url = '/api/v2/inventories/{inv_id}/script/'.format(inv_id=inventory_id)
|
||||
|
||||
inventory = module.get_endpoint(
|
||||
inventory_url, data={'hostvars': '1', 'towervars': '1', 'all': '1'}
|
||||
)['json']
|
||||
|
||||
# To start with, create all the groups.
|
||||
for group_name in inventory:
|
||||
if group_name != '_meta':
|
||||
self.inventory.add_group(group_name)
|
||||
|
||||
# Then, create all hosts and add the host vars.
|
||||
all_hosts = inventory['_meta']['hostvars']
|
||||
for host_name, host_vars in six.iteritems(all_hosts):
|
||||
self.inventory.add_host(host_name)
|
||||
for var_name, var_value in six.iteritems(host_vars):
|
||||
self.inventory.set_variable(host_name, var_name, var_value)
|
||||
|
||||
# Lastly, create to group-host and group-group relationships, and set group vars.
|
||||
for group_name, group_content in six.iteritems(inventory):
|
||||
if group_name != 'all' and group_name != '_meta':
|
||||
# First add hosts to groups
|
||||
for host_name in group_content.get('hosts', []):
|
||||
self.inventory.add_host(host_name, group_name)
|
||||
# Then add the parent-children group relationships.
|
||||
for child_group_name in group_content.get('children', []):
|
||||
# add the child group to groups, if its already there it will just throw a warning
|
||||
self.inventory.add_group(child_group_name)
|
||||
self.inventory.add_child(group_name, child_group_name)
|
||||
# Set the group vars. Note we should set group var for 'all', but not '_meta'.
|
||||
if group_name != '_meta':
|
||||
for var_name, var_value in six.iteritems(group_content.get('vars', {})):
|
||||
self.inventory.set_variable(group_name, var_name, var_value)
|
||||
|
||||
# Fetch extra variables if told to do so
|
||||
if self.get_option('include_metadata'):
|
||||
|
||||
config_data = module.get_endpoint('/api/v2/config/')['json']
|
||||
|
||||
server_data = {}
|
||||
server_data['license_type'] = config_data.get('license_info', {}).get('license_type', 'unknown')
|
||||
for key in ('version', 'ansible_version'):
|
||||
server_data[key] = config_data.get(key, 'unknown')
|
||||
self.inventory.set_variable('all', 'tower_metadata', server_data)
|
||||
|
||||
# Clean up the inventory.
|
||||
self.inventory.reconcile_inventory()
|
||||
@@ -0,0 +1,200 @@
|
||||
# (c) 2020 Ansible Project
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
DOCUMENTATION = """
|
||||
lookup: tower_api
|
||||
author: John Westcott IV (@john-westcott-iv)
|
||||
short_description: Search the API for objects
|
||||
requirements:
|
||||
- None
|
||||
description:
|
||||
- Returns GET requests from the Ansible Tower API. See
|
||||
U(https://docs.ansible.com/ansible-tower/latest/html/towerapi/index.html) for API usage.
|
||||
- For use that is cross-compatible between the awx.awx and ansible.tower collection
|
||||
see the tower_meta module
|
||||
extends_documentation_fragment: awx.awx.auth_plugin
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- The endpoint to query, i.e. teams, users, tokens, job_templates, etc.
|
||||
required: True
|
||||
query_params:
|
||||
description:
|
||||
- The query parameters to search for in the form of key/value pairs.
|
||||
type: dict
|
||||
required: False
|
||||
aliases: [query, data, filter, params]
|
||||
expect_objects:
|
||||
description:
|
||||
- Error if the response does not contain either a detail view or a list view.
|
||||
type: boolean
|
||||
default: False
|
||||
aliases: [expect_object]
|
||||
expect_one:
|
||||
description:
|
||||
- Error if the response contains more than one object.
|
||||
type: boolean
|
||||
default: False
|
||||
return_objects:
|
||||
description:
|
||||
- If a list view is returned, promote the list of results to the top-level of list returned.
|
||||
- Allows using this lookup plugin to loop over objects without additional work.
|
||||
type: boolean
|
||||
default: True
|
||||
return_all:
|
||||
description:
|
||||
- If the response is paginated, return all pages.
|
||||
type: boolean
|
||||
default: False
|
||||
return_ids:
|
||||
description:
|
||||
- If response contains objects, promote the id key to the top-level entries in the list.
|
||||
- Allows looking up a related object and passing it as a parameter to another module.
|
||||
- This will convert the return to a string or list of strings depending on the number of selected items.
|
||||
type: boolean
|
||||
aliases: [return_id]
|
||||
default: False
|
||||
max_objects:
|
||||
description:
|
||||
- if C(return_all) is true, this is the maximum of number of objects to return from the list.
|
||||
- If a list view returns more an max_objects an exception will be raised
|
||||
type: integer
|
||||
default: 1000
|
||||
|
||||
notes:
|
||||
- If the query is not filtered properly this can cause a performance impact.
|
||||
"""
|
||||
|
||||
EXAMPLES = """
|
||||
- name: Load the UI settings
|
||||
set_fact:
|
||||
tower_settings: "{{ lookup('awx.awx.tower_api', 'settings/ui') }}"
|
||||
|
||||
- name: Load the UI settings specifying the connection info
|
||||
set_fact:
|
||||
tower_settings: "{{ lookup('awx.awx.tower_api', 'settings/ui' host='tower.example.com', username='admin', password=my_pass_var, verify_ssl=False) }}"
|
||||
|
||||
- name: Report the usernames of all users with admin privs
|
||||
debug:
|
||||
msg: "Admin users: {{ query('awx.awx.tower_api', 'users', query_params={ 'is_superuser': true }) | map(attribute='username') | join(', ') }}"
|
||||
|
||||
- name: debug all organizations in a loop # use query to return a list
|
||||
debug:
|
||||
msg: "Organization description={{ item['description'] }} id={{ item['id'] }}"
|
||||
loop: "{{ query('awx.awx.tower_api', 'organizations') }}"
|
||||
loop_control:
|
||||
label: "{{ item['name'] }}"
|
||||
|
||||
- name: Make sure user 'john' is an org admin of the default org if the user exists
|
||||
tower_role:
|
||||
organization: Default
|
||||
role: admin
|
||||
user: john
|
||||
when: "lookup('awx.awx.tower_api', 'users', query_params={ 'username': 'john' }) | length == 1"
|
||||
|
||||
- name: Create an inventory group with all 'foo' hosts
|
||||
tower_group:
|
||||
name: "Foo Group"
|
||||
inventory: "Demo Inventory"
|
||||
hosts: >-
|
||||
{{ query(
|
||||
'awx.awx.tower_api',
|
||||
'hosts',
|
||||
query_params={ 'name__startswith' : 'foo', },
|
||||
) | map(attribute='name') | list }}
|
||||
register: group_creation
|
||||
"""
|
||||
|
||||
RETURN = """
|
||||
_raw:
|
||||
description:
|
||||
- Response from the API
|
||||
type: dict
|
||||
returned: on successful request
|
||||
"""
|
||||
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.errors import AnsibleError
|
||||
from ansible.module_utils._text import to_native
|
||||
from ansible.utils.display import Display
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
display = Display()
|
||||
|
||||
def handle_error(self, **kwargs):
|
||||
raise AnsibleError(to_native(kwargs.get('msg')))
|
||||
|
||||
def warn_callback(self, warning):
|
||||
self.display.warning(warning)
|
||||
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
if len(terms) != 1:
|
||||
raise AnsibleError('You must pass exactly one endpoint to query')
|
||||
|
||||
self.set_options(direct=kwargs)
|
||||
|
||||
# Defer processing of params to logic shared with the modules
|
||||
module_params = {}
|
||||
for plugin_param, module_param in TowerAPIModule.short_params.items():
|
||||
opt_val = self.get_option(plugin_param)
|
||||
if opt_val is not None:
|
||||
module_params[module_param] = opt_val
|
||||
|
||||
# Create our module
|
||||
module = TowerAPIModule(
|
||||
argument_spec={}, direct_params=module_params,
|
||||
error_callback=self.handle_error, warn_callback=self.warn_callback
|
||||
)
|
||||
|
||||
response = module.get_endpoint(terms[0], data=self.get_option('query_params', {}))
|
||||
|
||||
if 'status_code' not in response:
|
||||
raise AnsibleError("Unclear response from API: {0}".format(response))
|
||||
|
||||
if response['status_code'] != 200:
|
||||
raise AnsibleError("Failed to query the API: {0}".format(response['json'].get('detail', response['json'])))
|
||||
|
||||
return_data = response['json']
|
||||
|
||||
if self.get_option('expect_objects') or self.get_option('expect_one'):
|
||||
if ('id' not in return_data) and ('results' not in return_data):
|
||||
raise AnsibleError(
|
||||
'Did not obtain a list or detail view at {0}, and '
|
||||
'expect_objects or expect_one is set to True'.format(terms[0])
|
||||
)
|
||||
|
||||
if self.get_option('expect_one'):
|
||||
if 'results' in return_data and len(return_data['results']) != 1:
|
||||
raise AnsibleError(
|
||||
'Expected one object from endpoint {0}, '
|
||||
'but obtained {1} from API'.format(terms[0], len(return_data['results']))
|
||||
)
|
||||
|
||||
if self.get_option('return_all') and 'results' in return_data:
|
||||
if return_data['count'] > self.get_option('max_objects'):
|
||||
raise AnsibleError(
|
||||
'List view at {0} returned {1} objects, which is more than the maximum allowed '
|
||||
'by max_objects, {2}'.format(terms[0], return_data['count'], self.get_option('max_objects'))
|
||||
)
|
||||
|
||||
next_page = return_data['next']
|
||||
while next_page is not None:
|
||||
next_response = module.get_endpoint(next_page)
|
||||
return_data['results'] += next_response['json']['results']
|
||||
next_page = next_response['json']['next']
|
||||
return_data['next'] = None
|
||||
|
||||
if self.get_option('return_ids'):
|
||||
if 'results' in return_data:
|
||||
return_data['results'] = [str(item['id']) for item in return_data['results']]
|
||||
elif 'id' in return_data:
|
||||
return_data = str(return_data['id'])
|
||||
|
||||
if self.get_option('return_objects') and 'results' in return_data:
|
||||
return return_data['results']
|
||||
else:
|
||||
return [return_data]
|
||||
@@ -0,0 +1,248 @@
|
||||
# (c) 2020 Ansible Project
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
DOCUMENTATION = """
|
||||
lookup: tower_schedule_rrule
|
||||
author: John Westcott IV (@john-westcott-iv)
|
||||
short_description: Generate an rrule string which can be used for Tower Schedules
|
||||
requirements:
|
||||
- pytz
|
||||
- python.dateutil >= 2.7.0
|
||||
description:
|
||||
- Returns a string based on criteria which represents an rrule
|
||||
options:
|
||||
_terms:
|
||||
description:
|
||||
- The frequency of the schedule
|
||||
- none - Run this schedule once
|
||||
- minute - Run this schedule every x minutes
|
||||
- hour - Run this schedule every x hours
|
||||
- day - Run this schedule every x days
|
||||
- week - Run this schedule weekly
|
||||
- month - Run this schedule monthly
|
||||
required: True
|
||||
choices: ['none', 'minute', 'hour', 'day', 'week', 'month']
|
||||
start_date:
|
||||
description:
|
||||
- The date to start the rule
|
||||
- Used for all frequencies
|
||||
- Format should be YYYY-MM-DD [HH:MM:SS]
|
||||
type: str
|
||||
timezone:
|
||||
description:
|
||||
- The timezone to use for this rule
|
||||
- Used for all frequencies
|
||||
- Format should be as US/Eastern
|
||||
- Defaults to America/New_York
|
||||
type: str
|
||||
every:
|
||||
description:
|
||||
- The repetition in months, weeks, days hours or minutes
|
||||
- Used for all types except none
|
||||
type: int
|
||||
end_on:
|
||||
description:
|
||||
- How to end this schedule
|
||||
- If this is not defined, this schedule will never end
|
||||
- If this is a positive integer, this schedule will end after this number of occurences
|
||||
- If this is a date in the format YYYY-MM-DD [HH:MM:SS], this schedule ends after this date
|
||||
- Used for all types except none
|
||||
type: str
|
||||
on_days:
|
||||
description:
|
||||
- The days to run this schedule on
|
||||
- A comma-separated list which can contain values sunday, monday, tuesday, wednesday, thursday, friday
|
||||
- Used for week type schedules
|
||||
month_day_number:
|
||||
description:
|
||||
- The day of the month this schedule will run on (0-31)
|
||||
- Used for month type schedules
|
||||
- Cannot be used with on_the parameter
|
||||
type: int
|
||||
on_the:
|
||||
description:
|
||||
- A description on when this schedule will run
|
||||
- Two strings separated by a space
|
||||
- First string is one of first, second, third, fourth, last
|
||||
- Second string is one of sunday, monday, tuesday, wednesday, thursday, friday
|
||||
- Used for month type schedules
|
||||
- Cannot be used with month_day_number parameters
|
||||
"""
|
||||
|
||||
EXAMPLES = """
|
||||
- name: Create a string for a schedule
|
||||
debug:
|
||||
msg: "{{ query('awx.awx.tower_schedule_rrule', 'none', start_date='1979-09-13 03:45:07') }}"
|
||||
"""
|
||||
|
||||
RETURN = """
|
||||
_raw:
|
||||
description:
|
||||
- String in the rrule format
|
||||
type: string
|
||||
"""
|
||||
|
||||
from ansible.plugins.lookup import LookupBase
|
||||
from ansible.errors import AnsibleError
|
||||
from datetime import datetime
|
||||
import re
|
||||
from distutils.version import LooseVersion
|
||||
|
||||
missing_modules = []
|
||||
try:
|
||||
import pytz
|
||||
except ImportError:
|
||||
missing_modules.append('pytz')
|
||||
|
||||
try:
|
||||
from dateutil import rrule
|
||||
except ImportError:
|
||||
missing_modules.append('python.dateutil')
|
||||
|
||||
# Validate the version of python.dateutil
|
||||
try:
|
||||
import dateutil
|
||||
if LooseVersion(dateutil.__version__) < LooseVersion("2.7.0"):
|
||||
raise Exception
|
||||
except Exception:
|
||||
missing_modules.append('python.dateutil>=2.7.0')
|
||||
|
||||
if len(missing_modules) > 0:
|
||||
raise AnsibleError('You are missing the modules {0}'.format(', '.join(missing_modules)))
|
||||
|
||||
|
||||
class LookupModule(LookupBase):
|
||||
frequencies = {
|
||||
'none': rrule.DAILY,
|
||||
'minute': rrule.MINUTELY,
|
||||
'hour': rrule.HOURLY,
|
||||
'day': rrule.DAILY,
|
||||
'week': rrule.WEEKLY,
|
||||
'month': rrule.MONTHLY,
|
||||
}
|
||||
|
||||
weekdays = {
|
||||
'monday': rrule.MO,
|
||||
'tuesday': rrule.TU,
|
||||
'wednesday': rrule.WE,
|
||||
'thursday': rrule.TH,
|
||||
'friday': rrule.FR,
|
||||
'saturday': rrule.SA,
|
||||
'sunday': rrule.SU,
|
||||
}
|
||||
|
||||
set_positions = {
|
||||
'first': 1,
|
||||
'second': 2,
|
||||
'third': 3,
|
||||
'fourth': 4,
|
||||
'last': -1,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def parse_date_time(date_string):
|
||||
try:
|
||||
return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
|
||||
except ValueError:
|
||||
return datetime.strptime(date_string, '%Y-%m-%d')
|
||||
|
||||
def run(self, terms, variables=None, **kwargs):
|
||||
if len(terms) != 1:
|
||||
raise AnsibleError('You may only pass one schedule type in at a time')
|
||||
|
||||
frequency = terms[0].lower()
|
||||
|
||||
return self.get_rrule(frequency, kwargs)
|
||||
|
||||
@staticmethod
|
||||
def get_rrule(frequency, kwargs):
|
||||
|
||||
if frequency not in LookupModule.frequencies:
|
||||
raise AnsibleError('Frequency of {0} is invalid'.format(frequency))
|
||||
|
||||
rrule_kwargs = {
|
||||
'freq': LookupModule.frequencies[frequency],
|
||||
'interval': kwargs.get('every', 1),
|
||||
}
|
||||
|
||||
# All frequencies can use a start date
|
||||
if 'start_date' in kwargs:
|
||||
try:
|
||||
rrule_kwargs['dtstart'] = LookupModule.parse_date_time(kwargs['start_date'])
|
||||
except Exception:
|
||||
raise AnsibleError('Parameter start_date must be in the format YYYY-MM-DD [HH:MM:SS]')
|
||||
|
||||
# If we are a none frequency we don't need anything else
|
||||
if frequency == 'none':
|
||||
rrule_kwargs['count'] = 1
|
||||
else:
|
||||
# All non-none frequencies can have an end_on option
|
||||
if 'end_on' in kwargs:
|
||||
end_on = kwargs['end_on']
|
||||
if re.match(r'^\d+$', end_on):
|
||||
rrule_kwargs['count'] = end_on
|
||||
else:
|
||||
try:
|
||||
rrule_kwargs['until'] = LookupModule.parse_date_time(end_on)
|
||||
except Exception:
|
||||
raise AnsibleError('Parameter end_on must either be an integer or in the format YYYY-MM-DD [HH:MM:SS]')
|
||||
|
||||
# A week-based frequency can also take the on_days parameter
|
||||
if frequency == 'week' and 'on_days' in kwargs:
|
||||
days = []
|
||||
for day in kwargs['on_days'].split(','):
|
||||
day = day.strip()
|
||||
if day not in LookupModule.weekdays:
|
||||
raise AnsibleError('Parameter on_days must only contain values {0}'.format(', '.join(LookupModule.weekdays.keys())))
|
||||
days.append(LookupModule.weekdays[day])
|
||||
|
||||
rrule_kwargs['byweekday'] = days
|
||||
|
||||
# A month-based frequency can also deal with month_day_number and on_the options
|
||||
if frequency == 'month':
|
||||
if 'month_day_number' in kwargs and 'on_the' in kwargs:
|
||||
raise AnsibleError('Month based frequencies can have month_day_number or on_the but not both')
|
||||
|
||||
if 'month_day_number' in kwargs:
|
||||
try:
|
||||
my_month_day = int(kwargs['month_day_number'])
|
||||
if my_month_day < 1 or my_month_day > 31:
|
||||
raise Exception()
|
||||
except Exception:
|
||||
raise AnsibleError('month_day_number must be between 1 and 31')
|
||||
|
||||
rrule_kwargs['bymonthday'] = my_month_day
|
||||
|
||||
if 'on_the' in kwargs:
|
||||
try:
|
||||
(occurance, weekday) = kwargs['on_the'].split(' ')
|
||||
except Exception:
|
||||
raise AnsibleError('on_the parameter must be two words separated by a space')
|
||||
|
||||
if weekday not in LookupModule.weekdays:
|
||||
raise AnsibleError('Weekday portion of on_the parameter is not valid')
|
||||
if occurance not in LookupModule.set_positions:
|
||||
raise AnsibleError('The first string of the on_the parameter is not valid')
|
||||
|
||||
rrule_kwargs['byweekday'] = LookupModule.weekdays[weekday]
|
||||
rrule_kwargs['bysetpos'] = LookupModule.set_positions[occurance]
|
||||
|
||||
my_rule = rrule.rrule(**rrule_kwargs)
|
||||
|
||||
# All frequencies can use a timezone but rrule can't support the format that Tower uses.
|
||||
# So we will do a string manip here if we need to
|
||||
timezone = 'America/New_York'
|
||||
if 'timezone' in kwargs:
|
||||
if kwargs['timezone'] not in pytz.all_timezones:
|
||||
raise AnsibleError('Timezone parameter is not valid')
|
||||
timezone = kwargs['timezone']
|
||||
|
||||
# rrule puts a \n in the rule instad of a space and can't handle timezones
|
||||
return_rrule = str(my_rule).replace('\n', ' ').replace('DTSTART:', 'DTSTART;TZID={0}:'.format(timezone))
|
||||
# Tower requires an interval. rrule will not add interval if it's set to 1
|
||||
if kwargs.get('every', 1) == 1:
|
||||
return_rrule = "{0};INTERVAL=1".format(return_rrule)
|
||||
|
||||
return return_rrule
|
||||
@@ -0,0 +1,687 @@
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
from . tower_module import TowerModule
|
||||
from ansible.module_utils.urls import Request, SSLValidationError, ConnectionError
|
||||
from ansible.module_utils.six import PY2
|
||||
from ansible.module_utils.six.moves.urllib.error import HTTPError
|
||||
from ansible.module_utils.six.moves.http_cookiejar import CookieJar
|
||||
import time
|
||||
from json import loads, dumps
|
||||
|
||||
|
||||
class TowerAPIModule(TowerModule):
|
||||
# TODO: Move the collection version check into tower_module.py
|
||||
# This gets set by the make process so whatever is in here is irrelevant
|
||||
_COLLECTION_VERSION = "0.0.1-devel"
|
||||
_COLLECTION_TYPE = "awx"
|
||||
# This maps the collections type (awx/tower) to the values returned by the API
|
||||
# Those values can be found in awx/api/generics.py line 204
|
||||
collection_to_version = {
|
||||
'awx': 'AWX',
|
||||
'tower': 'Red Hat Ansible Tower',
|
||||
}
|
||||
session = None
|
||||
IDENTITY_FIELDS = {
|
||||
'users': 'username',
|
||||
'workflow_job_template_nodes': 'identifier',
|
||||
'instances': 'hostname'
|
||||
}
|
||||
ENCRYPTED_STRING = "$encrypted$"
|
||||
|
||||
def __init__(self, argument_spec, direct_params=None, error_callback=None, warn_callback=None, **kwargs):
|
||||
kwargs['supports_check_mode'] = True
|
||||
|
||||
super(TowerAPIModule, self).__init__(argument_spec=argument_spec, direct_params=direct_params,
|
||||
error_callback=error_callback, warn_callback=warn_callback, **kwargs)
|
||||
self.session = Request(cookies=CookieJar(), validate_certs=self.verify_ssl)
|
||||
|
||||
if 'update_secrets' in self.params:
|
||||
self.update_secrets = self.params.pop('update_secrets')
|
||||
else:
|
||||
self.update_secrets = True
|
||||
|
||||
@staticmethod
|
||||
def param_to_endpoint(name):
|
||||
exceptions = {
|
||||
'inventory': 'inventories',
|
||||
'target_team': 'teams',
|
||||
'workflow': 'workflow_job_templates'
|
||||
}
|
||||
return exceptions.get(name, '{0}s'.format(name))
|
||||
|
||||
@staticmethod
|
||||
def get_name_field_from_endpoint(endpoint):
|
||||
return TowerAPIModule.IDENTITY_FIELDS.get(endpoint, 'name')
|
||||
|
||||
def get_item_name(self, item, allow_unknown=False):
|
||||
if item:
|
||||
if 'name' in item:
|
||||
return item['name']
|
||||
|
||||
for field_name in TowerAPIModule.IDENTITY_FIELDS.values():
|
||||
if field_name in item:
|
||||
return item[field_name]
|
||||
|
||||
if item.get('type', None) in ('o_auth2_access_token', 'credential_input_source'):
|
||||
return item['id']
|
||||
|
||||
if allow_unknown:
|
||||
return 'unknown'
|
||||
|
||||
if item:
|
||||
self.exit_json(msg='Cannot determine identity field for {0} object.'.format(item.get('type', 'unknown')))
|
||||
else:
|
||||
self.exit_json(msg='Cannot determine identity field for Undefined object.')
|
||||
|
||||
def head_endpoint(self, endpoint, *args, **kwargs):
|
||||
return self.make_request('HEAD', endpoint, **kwargs)
|
||||
|
||||
def get_endpoint(self, endpoint, *args, **kwargs):
|
||||
return self.make_request('GET', endpoint, **kwargs)
|
||||
|
||||
def patch_endpoint(self, endpoint, *args, **kwargs):
|
||||
# Handle check mode
|
||||
if self.check_mode:
|
||||
self.json_output['changed'] = True
|
||||
self.exit_json(**self.json_output)
|
||||
|
||||
return self.make_request('PATCH', endpoint, **kwargs)
|
||||
|
||||
def post_endpoint(self, endpoint, *args, **kwargs):
|
||||
# Handle check mode
|
||||
if self.check_mode:
|
||||
self.json_output['changed'] = True
|
||||
self.exit_json(**self.json_output)
|
||||
|
||||
return self.make_request('POST', endpoint, **kwargs)
|
||||
|
||||
def delete_endpoint(self, endpoint, *args, **kwargs):
|
||||
# Handle check mode
|
||||
if self.check_mode:
|
||||
self.json_output['changed'] = True
|
||||
self.exit_json(**self.json_output)
|
||||
|
||||
return self.make_request('DELETE', endpoint, **kwargs)
|
||||
|
||||
def get_all_endpoint(self, endpoint, *args, **kwargs):
|
||||
response = self.get_endpoint(endpoint, *args, **kwargs)
|
||||
if 'next' not in response['json']:
|
||||
raise RuntimeError('Expected list from API at {0}, got: {1}'.format(endpoint, response))
|
||||
next_page = response['json']['next']
|
||||
|
||||
if response['json']['count'] > 10000:
|
||||
self.fail_json(msg='The number of items being queried for is higher than 10,000.')
|
||||
|
||||
while next_page is not None:
|
||||
next_response = self.get_endpoint(next_page)
|
||||
response['json']['results'] = response['json']['results'] + next_response['json']['results']
|
||||
next_page = next_response['json']['next']
|
||||
response['json']['next'] = next_page
|
||||
return response
|
||||
|
||||
def get_one(self, endpoint, name_or_id=None, allow_none=True, **kwargs):
|
||||
new_kwargs = kwargs.copy()
|
||||
if name_or_id:
|
||||
name_field = self.get_name_field_from_endpoint(endpoint)
|
||||
new_data = kwargs.get('data', {}).copy()
|
||||
if name_field in new_data:
|
||||
self.fail_json(msg="You can't specify the field {0} in your search data if using the name_or_id field".format(name_field))
|
||||
|
||||
try:
|
||||
new_data['or__id'] = int(name_or_id)
|
||||
new_data['or__{0}'.format(name_field)] = name_or_id
|
||||
except ValueError:
|
||||
# If we get a value error, then we didn't have an integer so we can just pass and fall down to the fail
|
||||
new_data[name_field] = name_or_id
|
||||
new_kwargs['data'] = new_data
|
||||
|
||||
response = self.get_endpoint(endpoint, **new_kwargs)
|
||||
if response['status_code'] != 200:
|
||||
fail_msg = "Got a {0} response when trying to get one from {1}".format(response['status_code'], endpoint)
|
||||
if 'detail' in response.get('json', {}):
|
||||
fail_msg += ', detail: {0}'.format(response['json']['detail'])
|
||||
self.fail_json(msg=fail_msg)
|
||||
|
||||
if 'count' not in response['json'] or 'results' not in response['json']:
|
||||
self.fail_json(msg="The endpoint did not provide count and results")
|
||||
|
||||
if response['json']['count'] == 0:
|
||||
if allow_none:
|
||||
return None
|
||||
else:
|
||||
self.fail_wanted_one(response, endpoint, new_kwargs.get('data'))
|
||||
elif response['json']['count'] > 1:
|
||||
if name_or_id:
|
||||
# Since we did a name or ID search and got > 1 return something if the id matches
|
||||
for asset in response['json']['results']:
|
||||
if str(asset['id']) == name_or_id:
|
||||
return asset
|
||||
# We got > 1 and either didn't find something by ID (which means multiple names)
|
||||
# Or we weren't running with a or search and just got back too many to begin with.
|
||||
self.fail_wanted_one(response, endpoint, new_kwargs.get('data'))
|
||||
|
||||
return response['json']['results'][0]
|
||||
|
||||
def fail_wanted_one(self, response, endpoint, query_params):
|
||||
sample = response.copy()
|
||||
if len(sample['json']['results']) > 1:
|
||||
sample['json']['results'] = sample['json']['results'][:2] + ['...more results snipped...']
|
||||
url = self.build_url(endpoint, query_params)
|
||||
display_endpoint = url.geturl()[len(self.host):] # truncate to not include the base URL
|
||||
self.fail_json(
|
||||
msg="Request to {0} returned {1} items, expected 1".format(
|
||||
display_endpoint, response['json']['count']
|
||||
),
|
||||
query=query_params,
|
||||
response=sample,
|
||||
total_results=response['json']['count']
|
||||
)
|
||||
|
||||
def get_exactly_one(self, endpoint, name_or_id=None, **kwargs):
|
||||
return self.get_one(endpoint, name_or_id=name_or_id, allow_none=False, **kwargs)
|
||||
|
||||
def resolve_name_to_id(self, endpoint, name_or_id):
|
||||
return self.get_exactly_one(endpoint, name_or_id)['id']
|
||||
|
||||
def make_request(self, method, endpoint, *args, **kwargs):
|
||||
# In case someone is calling us directly; make sure we were given a method, let's not just assume a GET
|
||||
if not method:
|
||||
raise Exception("The HTTP method must be defined")
|
||||
|
||||
if method in ['POST', 'PUT', 'PATCH']:
|
||||
url = self.build_url(endpoint)
|
||||
else:
|
||||
url = self.build_url(endpoint, query_params=kwargs.get('data'))
|
||||
|
||||
# Extract the headers, this will be used in a couple of places
|
||||
headers = kwargs.get('headers', {})
|
||||
|
||||
# Authenticate to Tower (if we don't have a token and if not already done so)
|
||||
if not self.oauth_token and not self.authenticated:
|
||||
# This method will set a cookie in the cookie jar for us and also an oauth_token
|
||||
self.authenticate(**kwargs)
|
||||
if self.oauth_token:
|
||||
# If we have a oauth token, we just use a bearer header
|
||||
headers['Authorization'] = 'Bearer {0}'.format(self.oauth_token)
|
||||
|
||||
if method in ['POST', 'PUT', 'PATCH']:
|
||||
headers.setdefault('Content-Type', 'application/json')
|
||||
kwargs['headers'] = headers
|
||||
|
||||
data = None # Important, if content type is not JSON, this should not be dict type
|
||||
if headers.get('Content-Type', '') == 'application/json':
|
||||
data = dumps(kwargs.get('data', {}))
|
||||
|
||||
try:
|
||||
response = self.session.open(method, url.geturl(), headers=headers, validate_certs=self.verify_ssl, follow_redirects=True, data=data)
|
||||
except(SSLValidationError) as ssl_err:
|
||||
self.fail_json(msg="Could not establish a secure connection to your host ({1}): {0}.".format(url.netloc, ssl_err))
|
||||
except(ConnectionError) as con_err:
|
||||
self.fail_json(msg="There was a network error of some kind trying to connect to your host ({1}): {0}.".format(url.netloc, con_err))
|
||||
except(HTTPError) as he:
|
||||
# Sanity check: Did the server send back some kind of internal error?
|
||||
if he.code >= 500:
|
||||
self.fail_json(msg='The host sent back a server error ({1}): {0}. Please check the logs and try again later'.format(url.path, he))
|
||||
# Sanity check: Did we fail to authenticate properly? If so, fail out now; this is always a failure.
|
||||
elif he.code == 401:
|
||||
self.fail_json(msg='Invalid Tower authentication credentials for {0} (HTTP 401).'.format(url.path))
|
||||
# Sanity check: Did we get a forbidden response, which means that the user isn't allowed to do this? Report that.
|
||||
elif he.code == 403:
|
||||
self.fail_json(msg="You don't have permission to {1} to {0} (HTTP 403).".format(url.path, method))
|
||||
# Sanity check: Did we get a 404 response?
|
||||
# Requests with primary keys will return a 404 if there is no response, and we want to consistently trap these.
|
||||
elif he.code == 404:
|
||||
if kwargs.get('return_none_on_404', False):
|
||||
return None
|
||||
self.fail_json(msg='The requested object could not be found at {0}.'.format(url.path))
|
||||
# Sanity check: Did we get a 405 response?
|
||||
# A 405 means we used a method that isn't allowed. Usually this is a bad request, but it requires special treatment because the
|
||||
# API sends it as a logic error in a few situations (e.g. trying to cancel a job that isn't running).
|
||||
elif he.code == 405:
|
||||
self.fail_json(msg="The Tower server says you can't make a request with the {0} method to this endpoing {1}".format(method, url.path))
|
||||
# Sanity check: Did we get some other kind of error? If so, write an appropriate error message.
|
||||
elif he.code >= 400:
|
||||
# We are going to return a 400 so the module can decide what to do with it
|
||||
page_data = he.read()
|
||||
try:
|
||||
return {'status_code': he.code, 'json': loads(page_data)}
|
||||
# JSONDecodeError only available on Python 3.5+
|
||||
except ValueError:
|
||||
return {'status_code': he.code, 'text': page_data}
|
||||
elif he.code == 204 and method == 'DELETE':
|
||||
# A 204 is a normal response for a delete function
|
||||
pass
|
||||
else:
|
||||
self.fail_json(msg="Unexpected return code when calling {0}: {1}".format(url.geturl(), he))
|
||||
except(Exception) as e:
|
||||
self.fail_json(msg="There was an unknown error when trying to connect to {2}: {0} {1}".format(type(e).__name__, e, url.geturl()))
|
||||
|
||||
if not self.version_checked:
|
||||
# In PY2 we get back an HTTPResponse object but PY2 is returning an addinfourl
|
||||
# First try to get the headers in PY3 format and then drop down to PY2.
|
||||
try:
|
||||
tower_type = response.getheader('X-API-Product-Name', None)
|
||||
tower_version = response.getheader('X-API-Product-Version', None)
|
||||
except Exception:
|
||||
tower_type = response.info().getheader('X-API-Product-Name', None)
|
||||
tower_version = response.info().getheader('X-API-Product-Version', None)
|
||||
|
||||
if self._COLLECTION_TYPE not in self.collection_to_version or self.collection_to_version[self._COLLECTION_TYPE] != tower_type:
|
||||
self.warn("You are using the {0} version of this collection but connecting to {1}".format(
|
||||
self._COLLECTION_TYPE, tower_type
|
||||
))
|
||||
elif self._COLLECTION_VERSION != tower_version:
|
||||
self.warn("You are running collection version {0} but connecting to tower version {1}".format(
|
||||
self._COLLECTION_VERSION, tower_version
|
||||
))
|
||||
self.version_checked = True
|
||||
|
||||
response_body = ''
|
||||
try:
|
||||
response_body = response.read()
|
||||
except(Exception) as e:
|
||||
self.fail_json(msg="Failed to read response body: {0}".format(e))
|
||||
|
||||
response_json = {}
|
||||
if response_body and response_body != '':
|
||||
try:
|
||||
response_json = loads(response_body)
|
||||
except(Exception) as e:
|
||||
self.fail_json(msg="Failed to parse the response json: {0}".format(e))
|
||||
|
||||
if PY2:
|
||||
status_code = response.getcode()
|
||||
else:
|
||||
status_code = response.status
|
||||
return {'status_code': status_code, 'json': response_json}
|
||||
|
||||
def authenticate(self, **kwargs):
|
||||
if self.username and self.password:
|
||||
# Attempt to get a token from /api/v2/tokens/ by giving it our username/password combo
|
||||
# If we have a username and password, we need to get a session cookie
|
||||
login_data = {
|
||||
"description": "Ansible Tower Module Token",
|
||||
"application": None,
|
||||
"scope": "write",
|
||||
}
|
||||
# Post to the tokens endpoint with baisc auth to try and get a token
|
||||
api_token_url = (self.url._replace(path='/api/v2/tokens/')).geturl()
|
||||
|
||||
try:
|
||||
response = self.session.open(
|
||||
'POST', api_token_url,
|
||||
validate_certs=self.verify_ssl, follow_redirects=True,
|
||||
force_basic_auth=True, url_username=self.username, url_password=self.password,
|
||||
data=dumps(login_data), headers={'Content-Type': 'application/json'}
|
||||
)
|
||||
except HTTPError as he:
|
||||
try:
|
||||
resp = he.read()
|
||||
except Exception as e:
|
||||
resp = 'unknown {0}'.format(e)
|
||||
self.fail_json(msg='Failed to get token: {0}'.format(he), response=resp)
|
||||
except(Exception) as e:
|
||||
# Sanity check: Did the server send back some kind of internal error?
|
||||
self.fail_json(msg='Failed to get token: {0}'.format(e))
|
||||
|
||||
token_response = None
|
||||
try:
|
||||
token_response = response.read()
|
||||
response_json = loads(token_response)
|
||||
self.oauth_token_id = response_json['id']
|
||||
self.oauth_token = response_json['token']
|
||||
except(Exception) as e:
|
||||
self.fail_json(msg="Failed to extract token information from login response: {0}".format(e), **{'response': token_response})
|
||||
|
||||
# If we have neither of these, then we can try un-authenticated access
|
||||
self.authenticated = True
|
||||
|
||||
def delete_if_needed(self, existing_item, on_delete=None, auto_exit=True):
|
||||
# This will exit from the module on its own.
|
||||
# If the method successfully deletes an item and on_delete param is defined,
|
||||
# the on_delete parameter will be called as a method pasing in this object and the json from the response
|
||||
# This will return one of two things:
|
||||
# 1. None if the existing_item is not defined (so no delete needs to happen)
|
||||
# 2. The response from Tower from calling the delete on the endpont. It's up to you to process the response and exit from the module
|
||||
# Note: common error codes from the Tower API can cause the module to fail
|
||||
if existing_item:
|
||||
# If we have an item, we can try to delete it
|
||||
try:
|
||||
item_url = existing_item['url']
|
||||
item_type = existing_item['type']
|
||||
item_id = existing_item['id']
|
||||
item_name = self.get_item_name(existing_item, allow_unknown=True)
|
||||
except KeyError as ke:
|
||||
self.fail_json(msg="Unable to process delete of item due to missing data {0}".format(ke))
|
||||
|
||||
response = self.delete_endpoint(item_url)
|
||||
|
||||
if response['status_code'] in [202, 204]:
|
||||
if on_delete:
|
||||
on_delete(self, response['json'])
|
||||
self.json_output['changed'] = True
|
||||
self.json_output['id'] = item_id
|
||||
self.exit_json(**self.json_output)
|
||||
if auto_exit:
|
||||
self.exit_json(**self.json_output)
|
||||
else:
|
||||
return self.json_output
|
||||
else:
|
||||
if 'json' in response and '__all__' in response['json']:
|
||||
self.fail_json(msg="Unable to delete {0} {1}: {2}".format(item_type, item_name, response['json']['__all__'][0]))
|
||||
elif 'json' in response:
|
||||
# This is from a project delete (if there is an active job against it)
|
||||
if 'error' in response['json']:
|
||||
self.fail_json(msg="Unable to delete {0} {1}: {2}".format(item_type, item_name, response['json']['error']))
|
||||
else:
|
||||
self.fail_json(msg="Unable to delete {0} {1}: {2}".format(item_type, item_name, response['json']))
|
||||
else:
|
||||
self.fail_json(msg="Unable to delete {0} {1}: {2}".format(item_type, item_name, response['status_code']))
|
||||
else:
|
||||
if auto_exit:
|
||||
self.exit_json(**self.json_output)
|
||||
else:
|
||||
return self.json_output
|
||||
|
||||
def modify_associations(self, association_endpoint, new_association_list):
|
||||
# if we got None instead of [] we are not modifying the association_list
|
||||
if new_association_list is None:
|
||||
return
|
||||
|
||||
# First get the existing associations
|
||||
response = self.get_all_endpoint(association_endpoint)
|
||||
existing_associated_ids = [association['id'] for association in response['json']['results']]
|
||||
|
||||
# Disassociate anything that is in existing_associated_ids but not in new_association_list
|
||||
ids_to_remove = list(set(existing_associated_ids) - set(new_association_list))
|
||||
for an_id in ids_to_remove:
|
||||
response = self.post_endpoint(association_endpoint, **{'data': {'id': int(an_id), 'disassociate': True}})
|
||||
if response['status_code'] == 204:
|
||||
self.json_output['changed'] = True
|
||||
else:
|
||||
self.fail_json(msg="Failed to disassociate item {0}".format(response['json'].get('detail', response['json'])))
|
||||
|
||||
# Associate anything that is in new_association_list but not in `association`
|
||||
for an_id in list(set(new_association_list) - set(existing_associated_ids)):
|
||||
response = self.post_endpoint(association_endpoint, **{'data': {'id': int(an_id)}})
|
||||
if response['status_code'] == 204:
|
||||
self.json_output['changed'] = True
|
||||
else:
|
||||
self.fail_json(msg="Failed to associate item {0}".format(response['json'].get('detail', response['json'])))
|
||||
|
||||
def create_if_needed(self, existing_item, new_item, endpoint, on_create=None, auto_exit=True, item_type='unknown', associations=None):
|
||||
|
||||
# This will exit from the module on its own
|
||||
# If the method successfully creates an item and on_create param is defined,
|
||||
# the on_create parameter will be called as a method pasing in this object and the json from the response
|
||||
# This will return one of two things:
|
||||
# 1. None if the existing_item is already defined (so no create needs to happen)
|
||||
# 2. The response from Tower from calling the patch on the endpont. It's up to you to process the response and exit from the module
|
||||
# Note: common error codes from the Tower API can cause the module to fail
|
||||
|
||||
if not endpoint:
|
||||
self.fail_json(msg="Unable to create new {0} due to missing endpoint".format(item_type))
|
||||
|
||||
item_url = None
|
||||
if existing_item:
|
||||
try:
|
||||
item_url = existing_item['url']
|
||||
except KeyError as ke:
|
||||
self.fail_json(msg="Unable to process create of item due to missing data {0}".format(ke))
|
||||
else:
|
||||
# If we don't have an exisitng_item, we can try to create it
|
||||
|
||||
# We have to rely on item_type being passed in since we don't have an existing item that declares its type
|
||||
# We will pull the item_name out from the new_item, if it exists
|
||||
item_name = self.get_item_name(new_item, allow_unknown=True)
|
||||
|
||||
response = self.post_endpoint(endpoint, **{'data': new_item})
|
||||
|
||||
# 200 is response from approval node creation on tower 3.7.3 or awx 15.0.0 or earlier.
|
||||
if response['status_code'] in [200, 201]:
|
||||
self.json_output['name'] = 'unknown'
|
||||
for key in ('name', 'username', 'identifier', 'hostname'):
|
||||
if key in response['json']:
|
||||
self.json_output['name'] = response['json'][key]
|
||||
self.json_output['id'] = response['json']['id']
|
||||
self.json_output['changed'] = True
|
||||
item_url = response['json']['url']
|
||||
else:
|
||||
if 'json' in response and '__all__' in response['json']:
|
||||
self.fail_json(msg="Unable to create {0} {1}: {2}".format(item_type, item_name, response['json']['__all__'][0]))
|
||||
elif 'json' in response:
|
||||
self.fail_json(msg="Unable to create {0} {1}: {2}".format(item_type, item_name, response['json']))
|
||||
else:
|
||||
self.fail_json(msg="Unable to create {0} {1}: {2}".format(item_type, item_name, response['status_code']))
|
||||
|
||||
# Process any associations with this item
|
||||
if associations is not None:
|
||||
for association_type in associations:
|
||||
sub_endpoint = '{0}{1}/'.format(item_url, association_type)
|
||||
self.modify_associations(sub_endpoint, associations[association_type])
|
||||
|
||||
# If we have an on_create method and we actually changed something we can call on_create
|
||||
if on_create is not None and self.json_output['changed']:
|
||||
on_create(self, response['json'])
|
||||
elif auto_exit:
|
||||
self.exit_json(**self.json_output)
|
||||
else:
|
||||
last_data = response['json']
|
||||
return last_data
|
||||
|
||||
def _encrypted_changed_warning(self, field, old, warning=False):
|
||||
if not warning:
|
||||
return
|
||||
self.warn(
|
||||
'The field {0} of {1} {2} has encrypted data and may inaccurately report task is changed.'.format(
|
||||
field, old.get('type', 'unknown'), old.get('id', 'unknown')
|
||||
))
|
||||
|
||||
@staticmethod
|
||||
def has_encrypted_values(obj):
|
||||
"""Returns True if JSON-like python content in obj has $encrypted$
|
||||
anywhere in the data as a value
|
||||
"""
|
||||
if isinstance(obj, dict):
|
||||
for val in obj.values():
|
||||
if TowerAPIModule.has_encrypted_values(val):
|
||||
return True
|
||||
elif isinstance(obj, list):
|
||||
for val in obj:
|
||||
if TowerAPIModule.has_encrypted_values(val):
|
||||
return True
|
||||
elif obj == TowerAPIModule.ENCRYPTED_STRING:
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def fields_could_be_same(old_field, new_field):
|
||||
"""Treating $encrypted$ as a wild card,
|
||||
return False if the two values are KNOWN to be different
|
||||
return True if the two values are the same, or could potentially be the same,
|
||||
depending on the unknown $encrypted$ value or sub-values
|
||||
"""
|
||||
if isinstance(old_field, dict) and isinstance(new_field, dict):
|
||||
if set(old_field.keys()) != set(new_field.keys()):
|
||||
return False
|
||||
for key in new_field.keys():
|
||||
if not TowerAPIModule.fields_could_be_same(old_field[key], new_field[key]):
|
||||
return False
|
||||
return True # all sub-fields are either equal or could be equal
|
||||
else:
|
||||
if old_field == TowerAPIModule.ENCRYPTED_STRING:
|
||||
return True
|
||||
return bool(new_field == old_field)
|
||||
|
||||
def objects_could_be_different(self, old, new, field_set=None, warning=False):
|
||||
if field_set is None:
|
||||
field_set = set(fd for fd in new.keys() if fd not in ('modified', 'related', 'summary_fields'))
|
||||
for field in field_set:
|
||||
new_field = new.get(field, None)
|
||||
old_field = old.get(field, None)
|
||||
if old_field != new_field:
|
||||
if self.update_secrets or (not self.fields_could_be_same(old_field, new_field)):
|
||||
return True # Something doesn't match, or something might not match
|
||||
elif self.has_encrypted_values(new_field) or field not in new:
|
||||
if self.update_secrets or (not self.fields_could_be_same(old_field, new_field)):
|
||||
# case of 'field not in new' - user password write-only field that API will not display
|
||||
self._encrypted_changed_warning(field, old, warning=warning)
|
||||
return True
|
||||
return False
|
||||
|
||||
def update_if_needed(self, existing_item, new_item, on_update=None, auto_exit=True, associations=None):
|
||||
# This will exit from the module on its own
|
||||
# If the method successfully updates an item and on_update param is defined,
|
||||
# the on_update parameter will be called as a method pasing in this object and the json from the response
|
||||
# This will return one of two things:
|
||||
# 1. None if the existing_item does not need to be updated
|
||||
# 2. The response from Tower from patching to the endpoint. It's up to you to process the response and exit from the module.
|
||||
# Note: common error codes from the Tower API can cause the module to fail
|
||||
response = None
|
||||
if existing_item:
|
||||
|
||||
# If we have an item, we can see if it needs an update
|
||||
try:
|
||||
item_url = existing_item['url']
|
||||
item_type = existing_item['type']
|
||||
if item_type == 'user':
|
||||
item_name = existing_item['username']
|
||||
elif item_type == 'workflow_job_template_node':
|
||||
item_name = existing_item['identifier']
|
||||
elif item_type == 'credential_input_source':
|
||||
item_name = existing_item['id']
|
||||
else:
|
||||
item_name = existing_item['name']
|
||||
item_id = existing_item['id']
|
||||
except KeyError as ke:
|
||||
self.fail_json(msg="Unable to process update of item due to missing data {0}".format(ke))
|
||||
|
||||
# Check to see if anything within the item requires the item to be updated
|
||||
needs_patch = self.objects_could_be_different(existing_item, new_item)
|
||||
|
||||
# If we decided the item needs to be updated, update it
|
||||
self.json_output['id'] = item_id
|
||||
if needs_patch:
|
||||
response = self.patch_endpoint(item_url, **{'data': new_item})
|
||||
if response['status_code'] == 200:
|
||||
# compare apples-to-apples, old API data to new API data
|
||||
# but do so considering the fields given in parameters
|
||||
self.json_output['changed'] = self.objects_could_be_different(
|
||||
existing_item, response['json'], field_set=new_item.keys(), warning=True)
|
||||
elif 'json' in response and '__all__' in response['json']:
|
||||
self.fail_json(msg=response['json']['__all__'])
|
||||
else:
|
||||
self.fail_json(**{'msg': "Unable to update {0} {1}, see response".format(item_type, item_name), 'response': response})
|
||||
|
||||
else:
|
||||
raise RuntimeError('update_if_needed called incorrectly without existing_item')
|
||||
|
||||
# Process any associations with this item
|
||||
if associations is not None:
|
||||
for association_type, id_list in associations.items():
|
||||
endpoint = '{0}{1}/'.format(item_url, association_type)
|
||||
self.modify_associations(endpoint, id_list)
|
||||
|
||||
# If we change something and have an on_change call it
|
||||
if on_update is not None and self.json_output['changed']:
|
||||
if response is None:
|
||||
last_data = existing_item
|
||||
else:
|
||||
last_data = response['json']
|
||||
on_update(self, last_data)
|
||||
elif auto_exit:
|
||||
self.exit_json(**self.json_output)
|
||||
else:
|
||||
if response is None:
|
||||
last_data = existing_item
|
||||
else:
|
||||
last_data = response['json']
|
||||
return last_data
|
||||
|
||||
def create_or_update_if_needed(
|
||||
self, existing_item, new_item, endpoint=None, item_type='unknown', on_create=None, on_update=None, auto_exit=True, associations=None
|
||||
):
|
||||
if existing_item:
|
||||
return self.update_if_needed(existing_item, new_item, on_update=on_update, auto_exit=auto_exit, associations=associations)
|
||||
else:
|
||||
return self.create_if_needed(
|
||||
existing_item, new_item, endpoint, on_create=on_create, item_type=item_type, auto_exit=auto_exit, associations=associations)
|
||||
|
||||
def logout(self):
|
||||
if self.authenticated and self.oauth_token_id:
|
||||
# Attempt to delete our current token from /api/v2/tokens/
|
||||
# Post to the tokens endpoint with baisc auth to try and get a token
|
||||
api_token_url = (
|
||||
self.url._replace(
|
||||
path='/api/v2/tokens/{0}/'.format(self.oauth_token_id),
|
||||
query=None # in error cases, fail_json exists before exception handling
|
||||
)
|
||||
).geturl()
|
||||
|
||||
try:
|
||||
self.session.open(
|
||||
'DELETE',
|
||||
api_token_url,
|
||||
validate_certs=self.verify_ssl,
|
||||
follow_redirects=True,
|
||||
force_basic_auth=True,
|
||||
url_username=self.username,
|
||||
url_password=self.password
|
||||
)
|
||||
self.oauth_token_id = None
|
||||
self.authenticated = False
|
||||
except HTTPError as he:
|
||||
try:
|
||||
resp = he.read()
|
||||
except Exception as e:
|
||||
resp = 'unknown {0}'.format(e)
|
||||
self.warn('Failed to release tower token: {0}, response: {1}'.format(he, resp))
|
||||
except(Exception) as e:
|
||||
# Sanity check: Did the server send back some kind of internal error?
|
||||
self.warn('Failed to release tower token {0}: {1}'.format(self.oauth_token_id, e))
|
||||
|
||||
def is_job_done(self, job_status):
|
||||
if job_status in ['new', 'pending', 'waiting', 'running']:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def wait_on_url(self, url, object_name, object_type, timeout=30, interval=10):
|
||||
# Grab our start time to compare against for the timeout
|
||||
start = time.time()
|
||||
result = self.get_endpoint(url)
|
||||
while not result['json']['finished']:
|
||||
# If we are past our time out fail with a message
|
||||
if timeout and timeout < time.time() - start:
|
||||
# Account for Legacy messages
|
||||
if object_type == 'legacy_job_wait':
|
||||
self.json_output['msg'] = 'Monitoring of Job - {0} aborted due to timeout'.format(object_name)
|
||||
else:
|
||||
self.json_output['msg'] = 'Monitoring of {0} - {1} aborted due to timeout'.format(object_type, object_name)
|
||||
self.wait_output(result)
|
||||
self.fail_json(**self.json_output)
|
||||
|
||||
# Put the process to sleep for our interval
|
||||
time.sleep(interval)
|
||||
|
||||
result = self.get_endpoint(url)
|
||||
self.json_output['status'] = result['json']['status']
|
||||
|
||||
# If the job has failed, we want to raise a task failure for that so we get a non-zero response.
|
||||
if result['json']['failed']:
|
||||
# Account for Legacy messages
|
||||
if object_type == 'legacy_job_wait':
|
||||
self.json_output['msg'] = 'Job with id {0} failed'.format(object_name)
|
||||
else:
|
||||
self.json_output['msg'] = 'The {0} - {1}, failed'.format(object_type, object_name)
|
||||
self.wait_output(result)
|
||||
self.fail_json(**self.json_output)
|
||||
|
||||
self.wait_output(result)
|
||||
|
||||
return result
|
||||
|
||||
def wait_output(self, response):
|
||||
for k in ('id', 'status', 'elapsed', 'started', 'finished'):
|
||||
self.json_output[k] = response['json'].get(k)
|
||||
@@ -0,0 +1,53 @@
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
from . tower_module import TowerModule
|
||||
from ansible.module_utils.basic import missing_required_lib
|
||||
|
||||
try:
|
||||
from awxkit.api.client import Connection
|
||||
from awxkit.api.pages.api import ApiV2
|
||||
from awxkit.api import get_registered_page
|
||||
HAS_AWX_KIT = True
|
||||
except ImportError:
|
||||
HAS_AWX_KIT = False
|
||||
|
||||
|
||||
class TowerAWXKitModule(TowerModule):
|
||||
connection = None
|
||||
apiV2Ref = None
|
||||
|
||||
def __init__(self, argument_spec, **kwargs):
|
||||
kwargs['supports_check_mode'] = False
|
||||
|
||||
super(TowerAWXKitModule, self).__init__(argument_spec=argument_spec, **kwargs)
|
||||
|
||||
# Die if we don't have AWX_KIT installed
|
||||
if not HAS_AWX_KIT:
|
||||
self.fail_json(msg=missing_required_lib('awxkit'))
|
||||
|
||||
# Establish our conneciton object
|
||||
self.connection = Connection(self.host, verify=self.verify_ssl)
|
||||
|
||||
def authenticate(self):
|
||||
try:
|
||||
if self.oauth_token:
|
||||
self.connection.login(None, None, token=self.oauth_token)
|
||||
self.authenticated = True
|
||||
elif self.username:
|
||||
self.connection.login(username=self.username, password=self.password)
|
||||
self.authenticated = True
|
||||
except Exception:
|
||||
self.fail_json("Failed to authenticate")
|
||||
|
||||
def get_api_v2_object(self):
|
||||
if not self.apiV2Ref:
|
||||
if not self.authenticated:
|
||||
self.authenticate()
|
||||
v2_index = get_registered_page('/api/v2/')(self.connection).get()
|
||||
self.api_ref = ApiV2(connection=self.connection, **{'json': v2_index})
|
||||
return self.api_ref
|
||||
|
||||
def logout(self):
|
||||
if self.authenticated:
|
||||
self.connection.logout()
|
||||
@@ -0,0 +1,117 @@
|
||||
# This code is part of Ansible, but is an independent component.
|
||||
# This particular file snippet, and this file snippet only, is BSD licensed.
|
||||
# Modules you write using this snippet, which is embedded dynamically by Ansible
|
||||
# still belong to the author of the module, and may assign their own license
|
||||
# to the complete work.
|
||||
#
|
||||
# Copyright (c), Wayne Witzel III <wayne@riotousliving.com>
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without modification,
|
||||
# are permitted provided that the following conditions are met:
|
||||
#
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above copyright notice,
|
||||
# this list of conditions and the following disclaimer in the documentation
|
||||
# and/or other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
||||
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
|
||||
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
from __future__ import (absolute_import, division, print_function)
|
||||
__metaclass__ = type
|
||||
|
||||
import os
|
||||
import traceback
|
||||
|
||||
TOWER_CLI_IMP_ERR = None
|
||||
try:
|
||||
import tower_cli.utils.exceptions as exc
|
||||
from tower_cli.utils import parser
|
||||
from tower_cli.api import client
|
||||
|
||||
HAS_TOWER_CLI = True
|
||||
except ImportError:
|
||||
TOWER_CLI_IMP_ERR = traceback.format_exc()
|
||||
HAS_TOWER_CLI = False
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
|
||||
|
||||
def tower_auth_config(module):
|
||||
'''
|
||||
`tower_auth_config` attempts to load the tower-cli.cfg file
|
||||
specified from the `tower_config_file` parameter. If found,
|
||||
if returns the contents of the file as a dictionary, else
|
||||
it will attempt to fetch values from the module params and
|
||||
only pass those values that have been set.
|
||||
'''
|
||||
config_file = module.params.pop('tower_config_file', None)
|
||||
if config_file:
|
||||
if not os.path.exists(config_file):
|
||||
module.fail_json(msg='file not found: %s' % config_file)
|
||||
if os.path.isdir(config_file):
|
||||
module.fail_json(msg='directory can not be used as config file: %s' % config_file)
|
||||
|
||||
with open(config_file, 'r') as f:
|
||||
return parser.string_to_dict(f.read())
|
||||
else:
|
||||
auth_config = {}
|
||||
host = module.params.pop('tower_host', None)
|
||||
if host:
|
||||
auth_config['host'] = host
|
||||
username = module.params.pop('tower_username', None)
|
||||
if username:
|
||||
auth_config['username'] = username
|
||||
password = module.params.pop('tower_password', None)
|
||||
if password:
|
||||
auth_config['password'] = password
|
||||
module.params.pop('tower_verify_ssl', None) # pop alias if used
|
||||
verify_ssl = module.params.pop('validate_certs', None)
|
||||
if verify_ssl is not None:
|
||||
auth_config['verify_ssl'] = verify_ssl
|
||||
return auth_config
|
||||
|
||||
|
||||
def tower_check_mode(module):
|
||||
'''Execute check mode logic for Ansible Tower modules'''
|
||||
if module.check_mode:
|
||||
try:
|
||||
result = client.get('/ping').json()
|
||||
module.exit_json(changed=True, tower_version='{0}'.format(result['version']))
|
||||
except (exc.ServerError, exc.ConnectionError, exc.BadRequest) as excinfo:
|
||||
module.fail_json(changed=False, msg='Failed check mode: {0}'.format(excinfo))
|
||||
|
||||
|
||||
class TowerLegacyModule(AnsibleModule):
|
||||
def __init__(self, argument_spec, **kwargs):
|
||||
args = dict(
|
||||
tower_host=dict(),
|
||||
tower_username=dict(),
|
||||
tower_password=dict(no_log=True),
|
||||
validate_certs=dict(type='bool', aliases=['tower_verify_ssl']),
|
||||
tower_config_file=dict(type='path'),
|
||||
)
|
||||
args.update(argument_spec)
|
||||
|
||||
kwargs.setdefault('mutually_exclusive', [])
|
||||
kwargs['mutually_exclusive'].extend((
|
||||
('tower_config_file', 'tower_host'),
|
||||
('tower_config_file', 'tower_username'),
|
||||
('tower_config_file', 'tower_password'),
|
||||
('tower_config_file', 'validate_certs'),
|
||||
))
|
||||
|
||||
super(TowerLegacyModule, self).__init__(argument_spec=args, **kwargs)
|
||||
|
||||
if not HAS_TOWER_CLI:
|
||||
self.fail_json(msg=missing_required_lib('ansible-tower-cli'),
|
||||
exception=TOWER_CLI_IMP_ERR)
|
||||
@@ -0,0 +1,255 @@
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, env_fallback
|
||||
from ansible.module_utils.six import string_types
|
||||
from ansible.module_utils.six.moves import StringIO
|
||||
from ansible.module_utils.six.moves.urllib.parse import urlparse, urlencode
|
||||
from ansible.module_utils.six.moves.configparser import ConfigParser, NoOptionError
|
||||
from socket import gethostbyname
|
||||
import re
|
||||
from os.path import isfile, expanduser, split, join, exists, isdir
|
||||
from os import access, R_OK, getcwd
|
||||
from distutils.util import strtobool
|
||||
|
||||
try:
|
||||
import yaml
|
||||
HAS_YAML = True
|
||||
except ImportError:
|
||||
HAS_YAML = False
|
||||
|
||||
|
||||
class ConfigFileException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ItemNotDefined(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class TowerModule(AnsibleModule):
|
||||
url = None
|
||||
AUTH_ARGSPEC = dict(
|
||||
tower_host=dict(required=False, fallback=(env_fallback, ['TOWER_HOST'])),
|
||||
tower_username=dict(required=False, fallback=(env_fallback, ['TOWER_USERNAME'])),
|
||||
tower_password=dict(no_log=True, required=False, fallback=(env_fallback, ['TOWER_PASSWORD'])),
|
||||
validate_certs=dict(type='bool', aliases=['tower_verify_ssl'], required=False, fallback=(env_fallback, ['TOWER_VERIFY_SSL'])),
|
||||
tower_oauthtoken=dict(type='raw', no_log=True, required=False, fallback=(env_fallback, ['TOWER_OAUTH_TOKEN'])),
|
||||
tower_config_file=dict(type='path', required=False, default=None),
|
||||
)
|
||||
short_params = {
|
||||
'host': 'tower_host',
|
||||
'username': 'tower_username',
|
||||
'password': 'tower_password',
|
||||
'verify_ssl': 'validate_certs',
|
||||
'oauth_token': 'tower_oauthtoken',
|
||||
}
|
||||
host = '127.0.0.1'
|
||||
username = None
|
||||
password = None
|
||||
verify_ssl = True
|
||||
oauth_token = None
|
||||
oauth_token_id = None
|
||||
authenticated = False
|
||||
config_name = 'tower_cli.cfg'
|
||||
version_checked = False
|
||||
error_callback = None
|
||||
warn_callback = None
|
||||
|
||||
def __init__(self, argument_spec=None, direct_params=None, error_callback=None, warn_callback=None, **kwargs):
|
||||
full_argspec = {}
|
||||
full_argspec.update(TowerModule.AUTH_ARGSPEC)
|
||||
full_argspec.update(argument_spec)
|
||||
kwargs['supports_check_mode'] = True
|
||||
|
||||
self.error_callback = error_callback
|
||||
self.warn_callback = warn_callback
|
||||
|
||||
self.json_output = {'changed': False}
|
||||
|
||||
if direct_params is not None:
|
||||
self.params = direct_params
|
||||
else:
|
||||
super(TowerModule, self).__init__(argument_spec=full_argspec, **kwargs)
|
||||
|
||||
self.load_config_files()
|
||||
|
||||
# Parameters specified on command line will override settings in any config
|
||||
for short_param, long_param in self.short_params.items():
|
||||
direct_value = self.params.get(long_param)
|
||||
if direct_value is not None:
|
||||
setattr(self, short_param, direct_value)
|
||||
|
||||
# Perform magic depending on whether tower_oauthtoken is a string or a dict
|
||||
if self.params.get('tower_oauthtoken'):
|
||||
token_param = self.params.get('tower_oauthtoken')
|
||||
if type(token_param) is dict:
|
||||
if 'token' in token_param:
|
||||
self.oauth_token = self.params.get('tower_oauthtoken')['token']
|
||||
else:
|
||||
self.fail_json(msg="The provided dict in tower_oauthtoken did not properly contain the token entry")
|
||||
elif isinstance(token_param, string_types):
|
||||
self.oauth_token = self.params.get('tower_oauthtoken')
|
||||
else:
|
||||
error_msg = "The provided tower_oauthtoken type was not valid ({0}). Valid options are str or dict.".format(type(token_param).__name__)
|
||||
self.fail_json(msg=error_msg)
|
||||
|
||||
# Perform some basic validation
|
||||
if not re.match('^https{0,1}://', self.host):
|
||||
self.host = "https://{0}".format(self.host)
|
||||
|
||||
# Try to parse the hostname as a url
|
||||
try:
|
||||
self.url = urlparse(self.host)
|
||||
except Exception as e:
|
||||
self.fail_json(msg="Unable to parse tower_host as a URL ({1}): {0}".format(self.host, e))
|
||||
|
||||
# Try to resolve the hostname
|
||||
hostname = self.url.netloc.split(':')[0]
|
||||
try:
|
||||
gethostbyname(hostname)
|
||||
except Exception as e:
|
||||
self.fail_json(msg="Unable to resolve tower_host ({1}): {0}".format(hostname, e))
|
||||
|
||||
def build_url(self, endpoint, query_params=None):
|
||||
# Make sure we start with /api/vX
|
||||
if not endpoint.startswith("/"):
|
||||
endpoint = "/{0}".format(endpoint)
|
||||
if not endpoint.startswith("/api/"):
|
||||
endpoint = "/api/v2{0}".format(endpoint)
|
||||
if not endpoint.endswith('/') and '?' not in endpoint:
|
||||
endpoint = "{0}/".format(endpoint)
|
||||
|
||||
# Update the URL path with the endpoint
|
||||
url = self.url._replace(path=endpoint)
|
||||
|
||||
if query_params:
|
||||
url = url._replace(query=urlencode(query_params))
|
||||
|
||||
return url
|
||||
|
||||
def load_config_files(self):
|
||||
# Load configs like TowerCLI would have from least import to most
|
||||
config_files = ['/etc/tower/tower_cli.cfg', join(expanduser("~"), ".{0}".format(self.config_name))]
|
||||
local_dir = getcwd()
|
||||
config_files.append(join(local_dir, self.config_name))
|
||||
while split(local_dir)[1]:
|
||||
local_dir = split(local_dir)[0]
|
||||
config_files.insert(2, join(local_dir, ".{0}".format(self.config_name)))
|
||||
|
||||
# If we have a specified tower config, load it
|
||||
if self.params.get('tower_config_file'):
|
||||
duplicated_params = [
|
||||
fn for fn in self.AUTH_ARGSPEC
|
||||
if fn != 'tower_config_file' and self.params.get(fn) is not None
|
||||
]
|
||||
if duplicated_params:
|
||||
self.warn((
|
||||
'The parameter(s) {0} were provided at the same time as tower_config_file. '
|
||||
'Precedence may be unstable, we suggest either using config file or params.'
|
||||
).format(', '.join(duplicated_params)))
|
||||
try:
|
||||
# TODO: warn if there are conflicts with other params
|
||||
self.load_config(self.params.get('tower_config_file'))
|
||||
except ConfigFileException as cfe:
|
||||
# Since we were told specifically to load this we want it to fail if we have an error
|
||||
self.fail_json(msg=cfe)
|
||||
else:
|
||||
for config_file in config_files:
|
||||
if exists(config_file) and not isdir(config_file):
|
||||
# Only throw a formatting error if the file exists and is not a directory
|
||||
try:
|
||||
self.load_config(config_file)
|
||||
except ConfigFileException:
|
||||
self.fail_json(msg='The config file {0} is not properly formatted'.format(config_file))
|
||||
|
||||
def load_config(self, config_path):
|
||||
# Validate the config file is an actual file
|
||||
if not isfile(config_path):
|
||||
raise ConfigFileException('The specified config file does not exist')
|
||||
|
||||
if not access(config_path, R_OK):
|
||||
raise ConfigFileException("The specified config file cannot be read")
|
||||
|
||||
# Read in the file contents:
|
||||
with open(config_path, 'r') as f:
|
||||
config_string = f.read()
|
||||
|
||||
# First try to yaml load the content (which will also load json)
|
||||
try:
|
||||
try_config_parsing = True
|
||||
if HAS_YAML:
|
||||
try:
|
||||
config_data = yaml.load(config_string, Loader=yaml.SafeLoader)
|
||||
# If this is an actual ini file, yaml will return the whole thing as a string instead of a dict
|
||||
if type(config_data) is not dict:
|
||||
raise AssertionError("The yaml config file is not properly formatted as a dict.")
|
||||
try_config_parsing = False
|
||||
|
||||
except(AttributeError, yaml.YAMLError, AssertionError):
|
||||
try_config_parsing = True
|
||||
|
||||
if try_config_parsing:
|
||||
# TowerCLI used to support a config file with a missing [general] section by prepending it if missing
|
||||
if '[general]' not in config_string:
|
||||
config_string = '[general]\n{0}'.format(config_string)
|
||||
|
||||
config = ConfigParser()
|
||||
|
||||
try:
|
||||
placeholder_file = StringIO(config_string)
|
||||
# py2 ConfigParser has readfp, that has been deprecated in favor of read_file in py3
|
||||
# This "if" removes the deprecation warning
|
||||
if hasattr(config, 'read_file'):
|
||||
config.read_file(placeholder_file)
|
||||
else:
|
||||
config.readfp(placeholder_file)
|
||||
|
||||
# If we made it here then we have values from reading the ini file, so let's pull them out into a dict
|
||||
config_data = {}
|
||||
for honorred_setting in self.short_params:
|
||||
try:
|
||||
config_data[honorred_setting] = config.get('general', honorred_setting)
|
||||
except NoOptionError:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
raise ConfigFileException("An unknown exception occured trying to ini load config file: {0}".format(e))
|
||||
|
||||
except Exception as e:
|
||||
raise ConfigFileException("An unknown exception occured trying to load config file: {0}".format(e))
|
||||
|
||||
# If we made it here, we have a dict which has values in it from our config, any final settings logic can be performed here
|
||||
for honorred_setting in self.short_params:
|
||||
if honorred_setting in config_data:
|
||||
# Veriffy SSL must be a boolean
|
||||
if honorred_setting == 'verify_ssl':
|
||||
if type(config_data[honorred_setting]) is str:
|
||||
setattr(self, honorred_setting, strtobool(config_data[honorred_setting]))
|
||||
else:
|
||||
setattr(self, honorred_setting, bool(config_data[honorred_setting]))
|
||||
else:
|
||||
setattr(self, honorred_setting, config_data[honorred_setting])
|
||||
|
||||
def logout(self):
|
||||
# This method is intended to be overridden
|
||||
pass
|
||||
|
||||
def fail_json(self, **kwargs):
|
||||
# Try to log out if we are authenticated
|
||||
self.logout()
|
||||
if self.error_callback:
|
||||
self.error_callback(**kwargs)
|
||||
else:
|
||||
super(TowerModule, self).fail_json(**kwargs)
|
||||
|
||||
def exit_json(self, **kwargs):
|
||||
# Try to log out if we are authenticated
|
||||
self.logout()
|
||||
super(TowerModule, self).exit_json(**kwargs)
|
||||
|
||||
def warn(self, warning):
|
||||
if self.warn_callback is not None:
|
||||
self.warn_callback(warning)
|
||||
else:
|
||||
super(TowerModule, self).warn(warning)
|
||||
@@ -0,0 +1,187 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
|
||||
# (c) 2020, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_ad_hoc_command
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
version_added: "4.0"
|
||||
short_description: create, update, or destroy Ansible Tower ad hoc commands.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower ad hoc commands. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
job_type:
|
||||
description:
|
||||
- Job_type to use for the ad hoc command.
|
||||
type: str
|
||||
choices: [ 'run', 'check' ]
|
||||
inventory:
|
||||
description:
|
||||
- Inventory to use for the ad hoc command.
|
||||
required: True
|
||||
type: str
|
||||
limit:
|
||||
description:
|
||||
- Limit to use for the ad hoc command.
|
||||
type: str
|
||||
credential:
|
||||
description:
|
||||
- Credential to use for ad hoc command.
|
||||
required: True
|
||||
type: str
|
||||
module_name:
|
||||
description:
|
||||
- The Ansible module to execute.
|
||||
required: True
|
||||
type: str
|
||||
module_args:
|
||||
description:
|
||||
- The arguments to pass to the module.
|
||||
type: str
|
||||
default: ""
|
||||
forks:
|
||||
description:
|
||||
- The number of forks to use for this ad hoc execution.
|
||||
type: int
|
||||
verbosity:
|
||||
description:
|
||||
- Verbosity level for this ad hoc command run
|
||||
type: int
|
||||
choices: [ 0, 1, 2, 3, 4, 5 ]
|
||||
extra_vars:
|
||||
description:
|
||||
- Extra variables to use for the ad hoc command..
|
||||
type: dict
|
||||
become_enabled:
|
||||
description:
|
||||
- If the become flag should be set.
|
||||
type: bool
|
||||
diff_mode:
|
||||
description:
|
||||
- Show the changes made by Ansible tasks where supported
|
||||
type: bool
|
||||
wait:
|
||||
description:
|
||||
- Wait for the command to complete.
|
||||
default: False
|
||||
type: bool
|
||||
interval:
|
||||
description:
|
||||
- The interval to request an update from Tower.
|
||||
default: 1
|
||||
type: float
|
||||
timeout:
|
||||
description:
|
||||
- If waiting for the command to complete this will abort after this
|
||||
amount of seconds
|
||||
type: int
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
id:
|
||||
description: id of the newly launched command
|
||||
returned: success
|
||||
type: int
|
||||
sample: 86
|
||||
status:
|
||||
description: status of newly launched command
|
||||
returned: success
|
||||
type: str
|
||||
sample: pending
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
job_type=dict(choices=['run', 'check']),
|
||||
inventory=dict(required=True),
|
||||
limit=dict(),
|
||||
credential=dict(required=True),
|
||||
module_name=dict(required=True),
|
||||
module_args=dict(),
|
||||
forks=dict(type='int'),
|
||||
verbosity=dict(type='int', choices=['0', '1', '2', '3', '4', '5']),
|
||||
extra_vars=dict(type='dict'),
|
||||
become_enabled=dict(type='bool'),
|
||||
diff_mode=dict(type='bool'),
|
||||
wait=dict(default=False, type='bool'),
|
||||
interval=dict(default=1.0, type='float'),
|
||||
timeout=dict(default=None, type='int'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
inventory = module.params.get('inventory')
|
||||
credential = module.params.get('credential')
|
||||
module_name = module.params.get('module_name')
|
||||
module_args = module.params.get('module_args')
|
||||
|
||||
wait = module.params.get('wait')
|
||||
interval = module.params.get('interval')
|
||||
timeout = module.params.get('timeout')
|
||||
|
||||
# Create a datastructure to pass into our command launch
|
||||
post_data = {
|
||||
'module_name': module_name,
|
||||
'module_args': module_args,
|
||||
}
|
||||
for arg in ['job_type', 'limit', 'forks', 'verbosity', 'extra_vars', 'become_enabled', 'diff_mode']:
|
||||
if module.params.get(arg):
|
||||
post_data[arg] = module.params.get(arg)
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
post_data['inventory'] = module.resolve_name_to_id('inventories', inventory)
|
||||
post_data['credential'] = module.resolve_name_to_id('credentials', credential)
|
||||
|
||||
# Launch the ad hoc command
|
||||
results = module.post_endpoint('ad_hoc_commands', **{'data': post_data})
|
||||
|
||||
if results['status_code'] != 201:
|
||||
module.fail_json(msg="Failed to launch command, see response for details", **{'response': results})
|
||||
|
||||
if not wait:
|
||||
module.exit_json(**{
|
||||
'changed': True,
|
||||
'id': results['json']['id'],
|
||||
'status': results['json']['status'],
|
||||
})
|
||||
|
||||
# Invoke wait function
|
||||
results = module.wait_on_url(
|
||||
url=results['json']['url'],
|
||||
object_name=module_name,
|
||||
object_type='Ad Hoc Command',
|
||||
timeout=timeout, interval=interval
|
||||
)
|
||||
|
||||
module.exit_json(**{
|
||||
'changed': True,
|
||||
'id': results['json']['id'],
|
||||
'status': results['json']['status'],
|
||||
})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_ad_hoc_command_cancel
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
short_description: Cancel an Ansible Tower Ad Hoc Command.
|
||||
description:
|
||||
- Cancel Ansible Tower ad hoc command. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
command_id:
|
||||
description:
|
||||
- ID of the command to cancel
|
||||
required: True
|
||||
type: int
|
||||
fail_if_not_running:
|
||||
description:
|
||||
- Fail loudly if the I(command_id) can not be canceled
|
||||
default: False
|
||||
type: bool
|
||||
interval:
|
||||
description:
|
||||
- The interval in seconds, to request an update from Tower.
|
||||
required: False
|
||||
default: 1
|
||||
type: float
|
||||
timeout:
|
||||
description:
|
||||
- Maximum time in seconds to wait for a job to finish.
|
||||
- Not specifying means the task will wait until Tower cancels the command.
|
||||
type: int
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Cancel command
|
||||
tower_ad_hoc_command_cancel:
|
||||
command_id: command.id
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
id:
|
||||
description: command id requesting to cancel
|
||||
returned: success
|
||||
type: int
|
||||
sample: 94
|
||||
'''
|
||||
|
||||
|
||||
import time
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
command_id=dict(type='int', required=True),
|
||||
fail_if_not_running=dict(type='bool', default=False),
|
||||
interval=dict(type='float', default=1.0),
|
||||
timeout=dict(type='int', default=0),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
command_id = module.params.get('command_id')
|
||||
fail_if_not_running = module.params.get('fail_if_not_running')
|
||||
interval = module.params.get('interval')
|
||||
timeout = module.params.get('timeout')
|
||||
|
||||
# Attempt to look up the command based on the provided name
|
||||
command = module.get_one('ad_hoc_commands', **{
|
||||
'data': {
|
||||
'id': command_id,
|
||||
}
|
||||
})
|
||||
|
||||
if command is None:
|
||||
module.fail_json(msg="Unable to find command with id {0}".format(command_id))
|
||||
|
||||
cancel_page = module.get_endpoint(command['related']['cancel'])
|
||||
if 'json' not in cancel_page or 'can_cancel' not in cancel_page['json']:
|
||||
module.fail_json(msg="Failed to cancel command, got unexpected response from tower", **{'response': cancel_page})
|
||||
|
||||
if not cancel_page['json']['can_cancel']:
|
||||
if fail_if_not_running:
|
||||
module.fail_json(msg="Ad Hoc Command is not running")
|
||||
else:
|
||||
module.exit_json(**{'changed': False})
|
||||
|
||||
results = module.post_endpoint(command['related']['cancel'], **{'data': {}})
|
||||
|
||||
if results['status_code'] != 202:
|
||||
module.fail_json(msg="Failed to cancel command, see response for details", **{'response': results})
|
||||
|
||||
result = module.get_endpoint(command['related']['cancel'])
|
||||
start = time.time()
|
||||
while result['json']['can_cancel']:
|
||||
# If we are past our time out fail with a message
|
||||
if timeout and timeout < time.time() - start:
|
||||
# Account for Legacy messages
|
||||
module.json_output['msg'] = 'Monitoring of ad hoc command aborted due to timeout'
|
||||
module.fail_json(**module.json_output)
|
||||
|
||||
# Put the process to sleep for our interval
|
||||
time.sleep(interval)
|
||||
|
||||
result = module.get_endpoint(command['related']['cancel'])
|
||||
|
||||
module.exit_json(**{'changed': True})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,127 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_ad_hoc_command_wait
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
short_description: Wait for Ansible Tower Ad Hoc Command to finish.
|
||||
description:
|
||||
- Wait for Ansible Tower ad hoc command to finish and report success or failure. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
command_id:
|
||||
description:
|
||||
- ID of the ad hoc command to monitor.
|
||||
required: True
|
||||
type: int
|
||||
interval:
|
||||
description:
|
||||
- The interval in sections, to request an update from Tower.
|
||||
required: False
|
||||
default: 1
|
||||
type: float
|
||||
timeout:
|
||||
description:
|
||||
- Maximum time in seconds to wait for a ad hoc command to finish.
|
||||
type: int
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Launch an ad hoc command
|
||||
tower_ad_hoc_command:
|
||||
inventory: "Demo Inventory"
|
||||
credential: "Demo Credential"
|
||||
wait: false
|
||||
register: command
|
||||
|
||||
- name: Wait for ad joc command max 120s
|
||||
tower_ad_hoc_command_wait:
|
||||
command_id: "{{ command.id }}"
|
||||
timeout: 120
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
id:
|
||||
description: Ad hoc command id that is being waited on
|
||||
returned: success
|
||||
type: int
|
||||
sample: 99
|
||||
elapsed:
|
||||
description: total time in seconds the command took to run
|
||||
returned: success
|
||||
type: float
|
||||
sample: 10.879
|
||||
started:
|
||||
description: timestamp of when the command started running
|
||||
returned: success
|
||||
type: str
|
||||
sample: "2017-03-01T17:03:53.200234Z"
|
||||
finished:
|
||||
description: timestamp of when the command finished running
|
||||
returned: success
|
||||
type: str
|
||||
sample: "2017-03-01T17:04:04.078782Z"
|
||||
status:
|
||||
description: current status of command
|
||||
returned: success
|
||||
type: str
|
||||
sample: successful
|
||||
'''
|
||||
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
command_id=dict(type='int', required=True),
|
||||
timeout=dict(type='int'),
|
||||
interval=dict(type='float', default=1),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
command_id = module.params.get('command_id')
|
||||
timeout = module.params.get('timeout')
|
||||
interval = module.params.get('interval')
|
||||
|
||||
# Attempt to look up command based on the provided id
|
||||
command = module.get_one('ad_hoc_commands', **{
|
||||
'data': {
|
||||
'id': command_id,
|
||||
}
|
||||
})
|
||||
|
||||
if command is None:
|
||||
module.fail_json(msg='Unable to wait on ad hoc command {0}; that ID does not exist in Tower.'.format(command_id))
|
||||
|
||||
# Invoke wait function
|
||||
module.wait_on_url(
|
||||
url=command['url'],
|
||||
object_name=command_id,
|
||||
object_type='ad hoc command',
|
||||
timeout=timeout, interval=interval
|
||||
)
|
||||
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2020,Geoffrey Bachelot <bachelotg@gmail.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_application
|
||||
author: "Geoffrey Bacheot (@jffz)"
|
||||
short_description: create, update, or destroy Ansible Tower applications
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower applications. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name of the application.
|
||||
required: True
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- Description of the application.
|
||||
type: str
|
||||
authorization_grant_type:
|
||||
description:
|
||||
- The grant type the user must use for acquire tokens for this application.
|
||||
choices: ["password", "authorization-code"]
|
||||
type: str
|
||||
required: False
|
||||
client_type:
|
||||
description:
|
||||
- Set to public or confidential depending on how secure the client device is.
|
||||
choices: ["public", "confidential"]
|
||||
type: str
|
||||
required: False
|
||||
organization:
|
||||
description:
|
||||
- Name of organization for application.
|
||||
type: str
|
||||
required: True
|
||||
redirect_uris:
|
||||
description:
|
||||
- Allowed urls list, space separated. Required when authorization-grant-type=authorization-code
|
||||
type: list
|
||||
elements: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
default: "present"
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
skip_authorization:
|
||||
description:
|
||||
- Set True to skip authorization step for completely trusted applications.
|
||||
type: bool
|
||||
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Add Foo application
|
||||
tower_application:
|
||||
name: "Foo"
|
||||
description: "Foo bar application"
|
||||
organization: "test"
|
||||
state: present
|
||||
authorization_grant_type: password
|
||||
client-type: public
|
||||
|
||||
- name: Add Foo application
|
||||
tower_application:
|
||||
name: "Foo"
|
||||
description: "Foo bar application"
|
||||
organization: "test"
|
||||
state: present
|
||||
authorization_grant_type: authorization-code
|
||||
client-type: confidential
|
||||
redirect_uris:
|
||||
- http://tower.com/api/v2/
|
||||
'''
|
||||
|
||||
import time
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
description=dict(),
|
||||
authorization_grant_type=dict(choices=["password", "authorization-code"]),
|
||||
client_type=dict(choices=['public', 'confidential']),
|
||||
organization=dict(required=True),
|
||||
redirect_uris=dict(type="list", elements='str'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
skip_authorization=dict(type='bool')
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
description = module.params.get('description')
|
||||
authorization_grant_type = module.params.get('authorization_grant_type')
|
||||
client_type = module.params.get('client_type')
|
||||
organization = module.params.get('organization')
|
||||
redirect_uris = module.params.get('redirect_uris')
|
||||
state = module.params.get('state')
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
org_id = module.resolve_name_to_id('organizations', organization)
|
||||
|
||||
# Attempt to look up application based on the provided name and org ID
|
||||
application = module.get_one('applications', name_or_id=name, **{
|
||||
'data': {
|
||||
'organization': org_id
|
||||
}
|
||||
})
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(application)
|
||||
|
||||
# Attempt to look up associated field items the user specified.
|
||||
association_fields = {}
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
application_fields = {
|
||||
'name': name,
|
||||
'organization': org_id,
|
||||
}
|
||||
if authorization_grant_type is not None:
|
||||
application_fields['authorization_grant_type'] = authorization_grant_type
|
||||
if client_type is not None:
|
||||
application_fields['client_type'] = client_type
|
||||
if description is not None:
|
||||
application_fields['description'] = description
|
||||
if redirect_uris is not None:
|
||||
application_fields['redirect_uris'] = ' '.join(redirect_uris)
|
||||
|
||||
# If the state was present and we can let the module build or update the existing application, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
application, application_fields,
|
||||
endpoint='applications', item_type='application'
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,441 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_credential
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: create, update, or destroy Ansible Tower credential.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower credentials. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- The name to use for the credential.
|
||||
required: True
|
||||
type: str
|
||||
new_name:
|
||||
description:
|
||||
- Setting this option will change the existing name (looked up via the name field.
|
||||
required: False
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- The description to use for the credential.
|
||||
type: str
|
||||
organization:
|
||||
description:
|
||||
- Organization that should own the credential.
|
||||
type: str
|
||||
credential_type:
|
||||
description:
|
||||
- Name of credential type.
|
||||
- Will be preferred over kind
|
||||
type: str
|
||||
inputs:
|
||||
description:
|
||||
- >-
|
||||
Credential inputs where the keys are var names used in templating.
|
||||
Refer to the Ansible Tower documentation for example syntax.
|
||||
- Any fields in this dict will take prescedence over any fields mentioned below (i.e. host, username, etc)
|
||||
type: dict
|
||||
update_secrets:
|
||||
description:
|
||||
- C(true) will always update encrypted values.
|
||||
- C(false) will only updated encrypted values if a change is absolutely known to be needed.
|
||||
type: bool
|
||||
default: true
|
||||
user:
|
||||
description:
|
||||
- User that should own this credential.
|
||||
type: str
|
||||
team:
|
||||
description:
|
||||
- Team that should own this credential.
|
||||
type: str
|
||||
|
||||
kind:
|
||||
description:
|
||||
- Type of credential being added.
|
||||
- The ssh choice refers to a Tower Machine credential.
|
||||
- Deprecated, please use credential_type
|
||||
required: False
|
||||
type: str
|
||||
choices: ["aws", "tower", "gce", "azure_rm", "openstack", "satellite6", "rhv", "vmware", "aim", "conjur", "hashivault_kv", "hashivault_ssh",
|
||||
"azure_kv", "insights", "kubernetes_bearer_token", "net", "scm", "ssh", "github_token", "gitlab_token", "vault"]
|
||||
host:
|
||||
description:
|
||||
- Host for this credential.
|
||||
- Deprecated, will be removed in a future release
|
||||
type: str
|
||||
username:
|
||||
description:
|
||||
- Username for this credential. ``access_key`` for AWS.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
password:
|
||||
description:
|
||||
- Password for this credential. ``secret_key`` for AWS. ``api_key`` for RAX.
|
||||
- Use "ASK" and launch in Tower to be prompted.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
project:
|
||||
description:
|
||||
- Project that should use this credential for GCP.
|
||||
- Deprecated, will be removed in a future release
|
||||
type: str
|
||||
ssh_key_data:
|
||||
description:
|
||||
- SSH private key content. To extract the content from a file path, use the lookup function (see examples).
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
ssh_key_unlock:
|
||||
description:
|
||||
- Unlock password for ssh_key.
|
||||
- Use "ASK" and launch in Tower to be prompted.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
authorize:
|
||||
description:
|
||||
- Should use authorize for net type.
|
||||
- Deprecated, please use inputs
|
||||
type: bool
|
||||
default: 'no'
|
||||
authorize_password:
|
||||
description:
|
||||
- Password for net credentials that require authorize.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
client:
|
||||
description:
|
||||
- Client or application ID for azure_rm type.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
security_token:
|
||||
description:
|
||||
- STS token for aws type.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
secret:
|
||||
description:
|
||||
- Secret token for azure_rm type.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
subscription:
|
||||
description:
|
||||
- Subscription ID for azure_rm type.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
tenant:
|
||||
description:
|
||||
- Tenant ID for azure_rm type.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
domain:
|
||||
description:
|
||||
- Domain for openstack type.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
become_method:
|
||||
description:
|
||||
- Become method to use for privilege escalation.
|
||||
- Some examples are "None", "sudo", "su", "pbrun"
|
||||
- Due to become plugins, these can be arbitrary
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
become_username:
|
||||
description:
|
||||
- Become username.
|
||||
- Use "ASK" and launch in Tower to be prompted.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
become_password:
|
||||
description:
|
||||
- Become password.
|
||||
- Use "ASK" and launch in Tower to be prompted.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
vault_password:
|
||||
description:
|
||||
- Vault password.
|
||||
- Use "ASK" and launch in Tower to be prompted.
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
vault_id:
|
||||
description:
|
||||
- Vault identifier.
|
||||
- This parameter is only valid if C(kind) is specified as C(vault).
|
||||
- Deprecated, please use inputs
|
||||
type: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
choices: ["present", "absent"]
|
||||
default: "present"
|
||||
type: str
|
||||
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
|
||||
notes:
|
||||
- Values `inputs` and the other deprecated fields (such as `tenant`) are replacements of existing values.
|
||||
See the last 4 examples for details.
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Add tower machine credential
|
||||
tower_credential:
|
||||
name: Team Name
|
||||
description: Team Description
|
||||
organization: test-org
|
||||
credential_type: Machine
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Create a valid SCM credential from a private_key file
|
||||
tower_credential:
|
||||
name: SCM Credential
|
||||
organization: Default
|
||||
state: present
|
||||
credential_type: Source Control
|
||||
inputs:
|
||||
username: joe
|
||||
password: secret
|
||||
ssh_key_data: "{{ lookup('file', '/tmp/id_rsa') }}"
|
||||
ssh_key_unlock: "passphrase"
|
||||
|
||||
- name: Fetch private key
|
||||
slurp:
|
||||
src: '$HOME/.ssh/aws-private.pem'
|
||||
register: aws_ssh_key
|
||||
|
||||
- name: Add Credential Into Tower
|
||||
tower_credential:
|
||||
name: Workshop Credential
|
||||
credential_type: Machine
|
||||
organization: Default
|
||||
inputs:
|
||||
ssh_key_data: "{{ aws_ssh_key['content'] | b64decode }}"
|
||||
run_once: true
|
||||
delegate_to: localhost
|
||||
|
||||
- name: Add Credential with Custom Credential Type
|
||||
tower_credential:
|
||||
name: Workshop Credential
|
||||
credential_type: MyCloudCredential
|
||||
organization: Default
|
||||
tower_username: admin
|
||||
tower_password: ansible
|
||||
tower_host: https://localhost
|
||||
|
||||
- name: Create a Vaiult credential (example for notes)
|
||||
tower_credential:
|
||||
name: Example password
|
||||
credential_type: Vault
|
||||
organization: Default
|
||||
inputs:
|
||||
vault_password: 'hello'
|
||||
vault_id: 'My ID'
|
||||
|
||||
- name: Bad password update (will replace vault_id)
|
||||
tower_credential:
|
||||
name: Example password
|
||||
credential_type: Vault
|
||||
organization: Default
|
||||
inputs:
|
||||
vault_password: 'new_password'
|
||||
|
||||
- name: Another bad password update (will replace vault_id)
|
||||
tower_credential:
|
||||
name: Example password
|
||||
credential_type: Vault
|
||||
organization: Default
|
||||
vault_password: 'new_password'
|
||||
|
||||
- name: A safe way to update a password and keep vault_id
|
||||
tower_credential:
|
||||
name: Example password
|
||||
credential_type: Vault
|
||||
organization: Default
|
||||
inputs:
|
||||
vault_password: 'new_password'
|
||||
vault_id: 'My ID'
|
||||
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
KIND_CHOICES = {
|
||||
'aws': 'Amazon Web Services',
|
||||
'tower': 'Ansible Tower',
|
||||
'gce': 'Google Compute Engine',
|
||||
'azure_rm': 'Microsoft Azure Resource Manager',
|
||||
'openstack': 'OpenStack',
|
||||
'satellite6': 'Red Hat Satellite 6',
|
||||
'rhv': 'Red Hat Virtualization',
|
||||
'vmware': 'VMware vCenter',
|
||||
'aim': 'CyberArk AIM Central Credential Provider Lookup',
|
||||
'conjur': 'CyberArk Conjur Secret Lookup',
|
||||
'hashivault_kv': 'HashiCorp Vault Secret Lookup',
|
||||
'hashivault_ssh': 'HashiCorp Vault Signed SSH',
|
||||
'azure_kv': 'Microsoft Azure Key Vault',
|
||||
'insights': 'Insights',
|
||||
'kubernetes_bearer_token': 'OpenShift or Kubernetes API Bearer Token',
|
||||
'net': 'Network',
|
||||
'scm': 'Source Control',
|
||||
'ssh': 'Machine',
|
||||
'github_token': 'GitHub Personal Access Token',
|
||||
'gitlab_token': 'GitLab Personal Access Token',
|
||||
'vault': 'Vault',
|
||||
}
|
||||
|
||||
|
||||
OLD_INPUT_NAMES = (
|
||||
'authorize', 'authorize_password', 'client',
|
||||
'security_token', 'secret', 'tenant', 'subscription',
|
||||
'domain', 'become_method', 'become_username',
|
||||
'become_password', 'vault_password', 'project', 'host',
|
||||
'username', 'password', 'ssh_key_data', 'vault_id',
|
||||
'ssh_key_unlock'
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
description=dict(),
|
||||
organization=dict(),
|
||||
credential_type=dict(),
|
||||
inputs=dict(type='dict', no_log=True),
|
||||
update_secrets=dict(type='bool', default=True, no_log=False),
|
||||
user=dict(),
|
||||
team=dict(),
|
||||
# These are for backwards compatability
|
||||
kind=dict(choices=list(KIND_CHOICES.keys())),
|
||||
host=dict(),
|
||||
username=dict(),
|
||||
password=dict(no_log=True),
|
||||
project=dict(),
|
||||
ssh_key_data=dict(no_log=True),
|
||||
ssh_key_unlock=dict(no_log=True),
|
||||
authorize=dict(type='bool'),
|
||||
authorize_password=dict(no_log=True),
|
||||
client=dict(),
|
||||
security_token=dict(),
|
||||
secret=dict(no_log=True),
|
||||
subscription=dict(),
|
||||
tenant=dict(),
|
||||
domain=dict(),
|
||||
become_method=dict(),
|
||||
become_username=dict(),
|
||||
become_password=dict(no_log=True),
|
||||
vault_password=dict(no_log=True),
|
||||
vault_id=dict(),
|
||||
# End backwards compatability
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec, required_one_of=[['kind', 'credential_type']])
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get('new_name')
|
||||
description = module.params.get('description')
|
||||
organization = module.params.get('organization')
|
||||
credential_type = module.params.get('credential_type')
|
||||
inputs = module.params.get('inputs')
|
||||
user = module.params.get('user')
|
||||
team = module.params.get('team')
|
||||
# The legacy arguments are put into a hash down below
|
||||
kind = module.params.get('kind')
|
||||
# End backwards compatability
|
||||
state = module.params.get('state')
|
||||
|
||||
# Deprication warnings
|
||||
for legacy_input in OLD_INPUT_NAMES:
|
||||
if module.params.get(legacy_input) is not None:
|
||||
module.deprecate(msg='{0} parameter has been deprecated, please use inputs instead'.format(legacy_input), version="ansible.tower:4.0.0")
|
||||
if kind:
|
||||
module.deprecate(msg='The kind parameter has been deprecated, please use credential_type instead', version="ansible.tower:4.0.0")
|
||||
|
||||
cred_type_id = module.resolve_name_to_id('credential_types', credential_type if credential_type else KIND_CHOICES[kind])
|
||||
if organization:
|
||||
org_id = module.resolve_name_to_id('organizations', organization)
|
||||
|
||||
# Attempt to look up the object based on the provided name, credential type and optional organization
|
||||
lookup_data = {
|
||||
'credential_type': cred_type_id,
|
||||
}
|
||||
if organization:
|
||||
lookup_data['organization'] = org_id
|
||||
|
||||
credential = module.get_one('credentials', name_or_id=name, **{'data': lookup_data})
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(credential)
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
if user:
|
||||
user_id = module.resolve_name_to_id('users', user)
|
||||
if team:
|
||||
team_id = module.resolve_name_to_id('teams', team)
|
||||
|
||||
# Create credential input from legacy inputs
|
||||
has_inputs = False
|
||||
credential_inputs = {}
|
||||
for legacy_input in OLD_INPUT_NAMES:
|
||||
if module.params.get(legacy_input) is not None:
|
||||
has_inputs = True
|
||||
credential_inputs[legacy_input] = module.params.get(legacy_input)
|
||||
|
||||
if inputs:
|
||||
has_inputs = True
|
||||
credential_inputs.update(inputs)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
credential_fields = {
|
||||
'name': new_name if new_name else (module.get_item_name(credential) if credential else name),
|
||||
'credential_type': cred_type_id,
|
||||
}
|
||||
if has_inputs:
|
||||
credential_fields['inputs'] = credential_inputs
|
||||
|
||||
if description:
|
||||
credential_fields['description'] = description
|
||||
if organization:
|
||||
credential_fields['organization'] = org_id
|
||||
|
||||
# If we don't already have a credential (and we are creating one) we can add user/team
|
||||
# The API does not appear to do anything with these after creation anyway
|
||||
# NOTE: We can't just add these on a modification because they are never returned from a GET so it would always cause a changed=True
|
||||
if not credential:
|
||||
if user:
|
||||
credential_fields['user'] = user_id
|
||||
if team:
|
||||
credential_fields['team'] = team_id
|
||||
|
||||
# If the state was present we can let the module build or update the existing group, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
credential, credential_fields, endpoint='credentials', item_type='credential'
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2020, Tom Page <tpage@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_credential_input_source
|
||||
author: "Tom Page (@Tompage1994)"
|
||||
version_added: "2.3"
|
||||
short_description: create, update, or destroy Ansible Tower credential input sources.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower credential input sources. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
description:
|
||||
description:
|
||||
- The description to use for the credential input source.
|
||||
type: str
|
||||
input_field_name:
|
||||
description:
|
||||
- The input field the credential source will be used for
|
||||
required: True
|
||||
type: str
|
||||
metadata:
|
||||
description:
|
||||
- A JSON or YAML string
|
||||
required: False
|
||||
type: dict
|
||||
target_credential:
|
||||
description:
|
||||
- The credential which will have its input defined by this source
|
||||
required: true
|
||||
type: str
|
||||
source_credential:
|
||||
description:
|
||||
- The credential which is the source of the credential lookup
|
||||
type: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
choices: ["present", "absent"]
|
||||
default: "present"
|
||||
type: str
|
||||
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Use CyberArk Lookup credential as password source
|
||||
tower_credential_input_source:
|
||||
input_field_name: password
|
||||
target_credential: new_cred
|
||||
source_credential: cyberark_lookup
|
||||
metadata:
|
||||
object_query: "Safe=MY_SAFE;Object=awxuser"
|
||||
object_query_format: "Exact"
|
||||
state: present
|
||||
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
description=dict(),
|
||||
input_field_name=dict(required=True),
|
||||
target_credential=dict(required=True),
|
||||
source_credential=dict(),
|
||||
metadata=dict(type="dict"),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
description = module.params.get('description')
|
||||
input_field_name = module.params.get('input_field_name')
|
||||
target_credential = module.params.get('target_credential')
|
||||
source_credential = module.params.get('source_credential')
|
||||
metadata = module.params.get('metadata')
|
||||
state = module.params.get('state')
|
||||
|
||||
target_credential_id = module.resolve_name_to_id('credentials', target_credential)
|
||||
|
||||
# Attempt to look up the object based on the target credential and input field
|
||||
lookup_data = {
|
||||
'target_credential': target_credential_id,
|
||||
'input_field_name': input_field_name,
|
||||
}
|
||||
credential_input_source = module.get_one('credential_input_sources', **{'data': lookup_data})
|
||||
|
||||
if state == 'absent':
|
||||
module.delete_if_needed(credential_input_source)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
credential_input_source_fields = {
|
||||
'target_credential': target_credential_id,
|
||||
'input_field_name': input_field_name,
|
||||
}
|
||||
if source_credential:
|
||||
credential_input_source_fields['source_credential'] = module.resolve_name_to_id('credentials', source_credential)
|
||||
if metadata:
|
||||
credential_input_source_fields['metadata'] = metadata
|
||||
if description:
|
||||
credential_input_source_fields['description'] = description
|
||||
|
||||
# If the state was present we can let the module build or update the existing group, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
credential_input_source, credential_input_source_fields, endpoint='credential_input_sources', item_type='credential_input_source'
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
#
|
||||
# (c) 2018, Adrien Fleury <fleu42@gmail.com>
|
||||
# GNU General Public License v3.0+
|
||||
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'status': ['preview'],
|
||||
'supported_by': 'community',
|
||||
'metadata_version': '1.1'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_credential_type
|
||||
author: "Adrien Fleury (@fleu42)"
|
||||
short_description: Create, update, or destroy custom Ansible Tower credential type.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower credential type. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- The name of the credential type.
|
||||
required: True
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- The description of the credential type to give more detail about it.
|
||||
type: str
|
||||
kind:
|
||||
description:
|
||||
- >-
|
||||
The type of credential type being added. Note that only cloud and
|
||||
net can be used for creating credential types. Refer to the Ansible
|
||||
for more information.
|
||||
choices: [ 'ssh', 'vault', 'net', 'scm', 'cloud', 'insights' ]
|
||||
type: str
|
||||
inputs:
|
||||
description:
|
||||
- >-
|
||||
Enter inputs using either JSON or YAML syntax. Refer to the Ansible
|
||||
Tower documentation for example syntax.
|
||||
type: dict
|
||||
injectors:
|
||||
description:
|
||||
- >-
|
||||
Enter injectors using either JSON or YAML syntax. Refer to the
|
||||
Ansible Tower documentation for example syntax.
|
||||
type: dict
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
default: "present"
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- tower_credential_type:
|
||||
name: Nexus
|
||||
description: Credentials type for Nexus
|
||||
kind: cloud
|
||||
inputs: "{{ lookup('file', 'tower_credential_inputs_nexus.json') }}"
|
||||
injectors: {'extra_vars': {'nexus_credential': 'test' }}
|
||||
state: present
|
||||
validate_certs: false
|
||||
|
||||
- tower_credential_type:
|
||||
name: Nexus
|
||||
state: absent
|
||||
'''
|
||||
|
||||
|
||||
RETURN = ''' # '''
|
||||
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
KIND_CHOICES = {
|
||||
'ssh': 'Machine',
|
||||
'vault': 'Ansible Vault',
|
||||
'net': 'Network',
|
||||
'scm': 'Source Control',
|
||||
'cloud': 'Lots of others',
|
||||
'insights': 'Insights'
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
description=dict(),
|
||||
kind=dict(choices=list(KIND_CHOICES.keys())),
|
||||
inputs=dict(type='dict'),
|
||||
injectors=dict(type='dict'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
new_name = None
|
||||
kind = module.params.get('kind')
|
||||
state = module.params.get('state')
|
||||
|
||||
# These will be passed into the create/updates
|
||||
credential_type_params = {
|
||||
'managed_by_tower': False,
|
||||
}
|
||||
if kind:
|
||||
credential_type_params['kind'] = kind
|
||||
if module.params.get('description'):
|
||||
credential_type_params['description'] = module.params.get('description')
|
||||
if module.params.get('inputs'):
|
||||
credential_type_params['inputs'] = module.params.get('inputs')
|
||||
if module.params.get('injectors'):
|
||||
credential_type_params['injectors'] = module.params.get('injectors')
|
||||
|
||||
# Attempt to look up credential_type based on the provided name
|
||||
credential_type = module.get_one('credential_types', name_or_id=name)
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(credential_type)
|
||||
|
||||
credential_type_params['name'] = new_name if new_name else (module.get_item_name(credential_type) if credential_type else name)
|
||||
|
||||
# If the state was present and we can let the module build or update the existing credential type, this will return on its own
|
||||
module.create_or_update_if_needed(credential_type, credential_type_params, endpoint='credential_types', item_type='credential type')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_export
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
version_added: "3.7"
|
||||
short_description: export resources from Ansible Tower.
|
||||
description:
|
||||
- Export assets from Ansible Tower.
|
||||
options:
|
||||
all:
|
||||
description:
|
||||
- Export all assets
|
||||
type: bool
|
||||
default: 'False'
|
||||
organizations:
|
||||
description:
|
||||
- organization name to export
|
||||
type: str
|
||||
users:
|
||||
description:
|
||||
- user name to export
|
||||
type: str
|
||||
teams:
|
||||
description:
|
||||
- team name to export
|
||||
type: str
|
||||
credential_types:
|
||||
description:
|
||||
- credential type name to export
|
||||
type: str
|
||||
credentials:
|
||||
description:
|
||||
- credential name to export
|
||||
type: str
|
||||
notification_templates:
|
||||
description:
|
||||
- notification template name to export
|
||||
type: str
|
||||
inventory_sources:
|
||||
description:
|
||||
- inventory soruce to export
|
||||
type: str
|
||||
inventory:
|
||||
description:
|
||||
- inventory name to export
|
||||
type: str
|
||||
projects:
|
||||
description:
|
||||
- project name to export
|
||||
type: str
|
||||
job_templates:
|
||||
description:
|
||||
- job template name to export
|
||||
type: str
|
||||
workflow_job_templates:
|
||||
description:
|
||||
- workflow name to export
|
||||
type: str
|
||||
requirements:
|
||||
- "awxkit >= 9.3.0"
|
||||
notes:
|
||||
- Specifying a name of "all" for any asset type will export all items of that asset type.
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Export all tower assets
|
||||
tower_export:
|
||||
all: True
|
||||
|
||||
- name: Export all inventories
|
||||
tower_export:
|
||||
inventory: 'all'
|
||||
|
||||
- name: Export a job template named "My Template" and all Credentials
|
||||
tower_export:
|
||||
job_template: "My Template"
|
||||
credential: 'all'
|
||||
'''
|
||||
|
||||
from os import environ
|
||||
import logging
|
||||
from ansible.module_utils.six.moves import StringIO
|
||||
from ..module_utils.tower_awxkit import TowerAWXKitModule
|
||||
|
||||
try:
|
||||
from awxkit.api.pages.api import EXPORTABLE_RESOURCES
|
||||
HAS_EXPORTABLE_RESOURCES = True
|
||||
except ImportError:
|
||||
HAS_EXPORTABLE_RESOURCES = False
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = dict(
|
||||
all=dict(type='bool', default=False),
|
||||
)
|
||||
|
||||
# We are not going to raise an error here because the __init__ method of TowerAWXKitModule will do that for us
|
||||
if HAS_EXPORTABLE_RESOURCES:
|
||||
for resource in EXPORTABLE_RESOURCES:
|
||||
argument_spec[resource] = dict(type='str')
|
||||
|
||||
module = TowerAWXKitModule(argument_spec=argument_spec)
|
||||
|
||||
if not HAS_EXPORTABLE_RESOURCES:
|
||||
module.fail_json(msg="Your version of awxkit does not have import/export")
|
||||
|
||||
# The export process will never change a Tower system
|
||||
module.json_output['changed'] = False
|
||||
|
||||
# The exporter code currently works like the following:
|
||||
# Empty string == all assets of that type
|
||||
# Non-Empty string = just one asset of that type (by name or ID)
|
||||
# Asset type not present or None = skip asset type (unless everything is None, then export all)
|
||||
# Here we are going to setup a dict of values to export
|
||||
export_args = {}
|
||||
for resource in EXPORTABLE_RESOURCES:
|
||||
if module.params.get('all') or module.params.get(resource) == 'all':
|
||||
# If we are exporting everything or we got the keyword "all" we pass in an empty string for this asset type
|
||||
export_args[resource] = ''
|
||||
else:
|
||||
# Otherwise we take either the string or None (if the parameter was not passed) to get one or no items
|
||||
export_args[resource] = module.params.get(resource)
|
||||
|
||||
# Currently the export process does not return anything on error
|
||||
# It simply just logs to Python's logger
|
||||
# Set up a log gobbler to get error messages from export_assets
|
||||
log_capture_string = StringIO()
|
||||
ch = logging.StreamHandler(log_capture_string)
|
||||
for logger_name in ['awxkit.api.pages.api', 'awxkit.api.pages.page']:
|
||||
logger = logging.getLogger(logger_name)
|
||||
logger.setLevel(logging.ERROR)
|
||||
ch.setLevel(logging.ERROR)
|
||||
|
||||
logger.addHandler(ch)
|
||||
log_contents = ''
|
||||
|
||||
# Run the export process
|
||||
try:
|
||||
module.json_output['assets'] = module.get_api_v2_object().export_assets(**export_args)
|
||||
module.exit_json(**module.json_output)
|
||||
except Exception as e:
|
||||
module.fail_json(msg="Failed to export assets {0}".format(e))
|
||||
finally:
|
||||
# Finally, consume the logs in case there were any errors and die if there were
|
||||
log_contents = log_capture_string.getvalue()
|
||||
log_capture_string.close()
|
||||
if log_contents != '':
|
||||
module.fail_json(msg=log_contents)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,155 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_group
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: create, update, or destroy Ansible Tower group.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower groups. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- The name to use for the group.
|
||||
required: True
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- The description to use for the group.
|
||||
type: str
|
||||
inventory:
|
||||
description:
|
||||
- Inventory the group should be made a member of.
|
||||
required: True
|
||||
type: str
|
||||
variables:
|
||||
description:
|
||||
- Variables to use for the group.
|
||||
type: dict
|
||||
hosts:
|
||||
description:
|
||||
- List of hosts that should be put in this group.
|
||||
type: list
|
||||
elements: str
|
||||
children:
|
||||
description:
|
||||
- List of groups that should be nested inside in this group.
|
||||
type: list
|
||||
elements: str
|
||||
aliases:
|
||||
- groups
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
default: "present"
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
new_name:
|
||||
description:
|
||||
- A new name for this group (for renaming)
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Add tower group
|
||||
tower_group:
|
||||
name: localhost
|
||||
description: "Local Host Group"
|
||||
inventory: "Local Inventory"
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
import json
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
description=dict(),
|
||||
inventory=dict(required=True),
|
||||
variables=dict(type='dict'),
|
||||
hosts=dict(type='list', elements='str'),
|
||||
children=dict(type='list', elements='str', aliases=['groups']),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get('new_name')
|
||||
inventory = module.params.get('inventory')
|
||||
description = module.params.get('description')
|
||||
state = module.params.pop('state')
|
||||
variables = module.params.get('variables')
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
inventory_id = module.resolve_name_to_id('inventories', inventory)
|
||||
|
||||
# Attempt to look up the object based on the provided name and inventory ID
|
||||
group = module.get_one('groups', name_or_id=name, **{
|
||||
'data': {
|
||||
'inventory': inventory_id
|
||||
}
|
||||
})
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(group)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
group_fields = {
|
||||
'name': new_name if new_name else (module.get_item_name(group) if group else name),
|
||||
'inventory': inventory_id,
|
||||
}
|
||||
if description is not None:
|
||||
group_fields['description'] = description
|
||||
if variables is not None:
|
||||
group_fields['variables'] = json.dumps(variables)
|
||||
|
||||
association_fields = {}
|
||||
for resource, relationship in (('hosts', 'hosts'), ('groups', 'children')):
|
||||
name_list = module.params.get(relationship)
|
||||
if name_list is None:
|
||||
continue
|
||||
id_list = []
|
||||
for sub_name in name_list:
|
||||
sub_obj = module.get_one(resource, name_or_id=sub_name, **{
|
||||
'data': {'inventory': inventory_id},
|
||||
})
|
||||
if sub_obj is None:
|
||||
module.fail_json(msg='Could not find {0} with name {1}'.format(resource, sub_name))
|
||||
id_list.append(sub_obj['id'])
|
||||
if id_list:
|
||||
association_fields[relationship] = id_list
|
||||
|
||||
# If the state was present we can let the module build or update the existing group, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
group, group_fields, endpoint='groups', item_type='group',
|
||||
associations=association_fields
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_host
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: create, update, or destroy Ansible Tower host.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower hosts. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- The name to use for the host.
|
||||
required: True
|
||||
type: str
|
||||
new_name:
|
||||
description:
|
||||
- To use when changing a hosts's name.
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- The description to use for the host.
|
||||
type: str
|
||||
inventory:
|
||||
description:
|
||||
- Inventory the host should be made a member of.
|
||||
required: True
|
||||
type: str
|
||||
enabled:
|
||||
description:
|
||||
- If the host should be enabled.
|
||||
type: bool
|
||||
default: 'yes'
|
||||
variables:
|
||||
description:
|
||||
- Variables to use for the host.
|
||||
type: dict
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
choices: ["present", "absent"]
|
||||
default: "present"
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Add tower host
|
||||
tower_host:
|
||||
name: localhost
|
||||
description: "Local Host Group"
|
||||
inventory: "Local Inventory"
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
variables:
|
||||
example_var: 123
|
||||
'''
|
||||
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
import json
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
description=dict(),
|
||||
inventory=dict(required=True),
|
||||
enabled=dict(type='bool', default=True),
|
||||
variables=dict(type='dict'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get('new_name')
|
||||
description = module.params.get('description')
|
||||
inventory = module.params.get('inventory')
|
||||
enabled = module.params.get('enabled')
|
||||
state = module.params.get('state')
|
||||
variables = module.params.get('variables')
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
inventory_id = module.resolve_name_to_id('inventories', inventory)
|
||||
|
||||
# Attempt to look up host based on the provided name and inventory ID
|
||||
host = module.get_one('hosts', name_or_id=name, **{
|
||||
'data': {
|
||||
'inventory': inventory_id
|
||||
}
|
||||
})
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(host)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
host_fields = {
|
||||
'name': new_name if new_name else (module.get_item_name(host) if host else name),
|
||||
'inventory': inventory_id,
|
||||
'enabled': enabled,
|
||||
}
|
||||
if description is not None:
|
||||
host_fields['description'] = description
|
||||
if variables is not None:
|
||||
host_fields['variables'] = json.dumps(variables)
|
||||
|
||||
# If the state was present and we can let the module build or update the existing host, this will return on its own
|
||||
module.create_or_update_if_needed(host, host_fields, endpoint='hosts', item_type='host')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_import
|
||||
author: "John Westcott (@john-westcott-iv)"
|
||||
version_added: "3.7"
|
||||
short_description: import resources into Ansible Tower.
|
||||
description:
|
||||
- Import assets into Ansible Tower. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
assets:
|
||||
description:
|
||||
- The assets to import.
|
||||
- This can be the output of tower_export or loaded from a file
|
||||
required: True
|
||||
type: dict
|
||||
requirements:
|
||||
- "awxkit >= 9.3.0"
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Export all assets
|
||||
tower_export:
|
||||
all: True
|
||||
register: export_output
|
||||
|
||||
- name: Import all tower assets from our export
|
||||
tower_import:
|
||||
assets: "{{ export_output.assets }}"
|
||||
|
||||
- name: Load data from a json file created by a command like awx export --organization Default
|
||||
tower_import:
|
||||
assets: "{{ lookup('file', 'org.json') | from_json() }}"
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_awxkit import TowerAWXKitModule
|
||||
|
||||
# These two lines are not needed if awxkit changes to do programatic notifications on issues
|
||||
from ansible.module_utils.six.moves import StringIO
|
||||
import logging
|
||||
|
||||
# In this module we don't use EXPORTABLE_RESOURCES, we just want to validate that our installed awxkit has import/export
|
||||
try:
|
||||
from awxkit.api.pages.api import EXPORTABLE_RESOURCES
|
||||
HAS_EXPORTABLE_RESOURCES = True
|
||||
except ImportError:
|
||||
HAS_EXPORTABLE_RESOURCES = False
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = dict(
|
||||
assets=dict(type='dict', required=True)
|
||||
)
|
||||
|
||||
module = TowerAWXKitModule(argument_spec=argument_spec, supports_check_mode=False)
|
||||
|
||||
assets = module.params.get('assets')
|
||||
|
||||
if not HAS_EXPORTABLE_RESOURCES:
|
||||
module.fail_json(msg="Your version of awxkit does not appear to have import/export")
|
||||
|
||||
# Currently the import process does not return anything on error
|
||||
# It simply just logs to Python's logger
|
||||
# Set up a log gobbler to get error messages from import_assets
|
||||
logger = logging.getLogger('awxkit.api.pages.api')
|
||||
logger.setLevel(logging.ERROR)
|
||||
|
||||
log_capture_string = StringIO()
|
||||
ch = logging.StreamHandler(log_capture_string)
|
||||
ch.setLevel(logging.ERROR)
|
||||
|
||||
logger.addHandler(ch)
|
||||
log_contents = ''
|
||||
|
||||
# Run the import process
|
||||
try:
|
||||
module.json_output['changed'] = module.get_api_v2_object().import_assets(assets)
|
||||
except Exception as e:
|
||||
module.fail_json(msg="Failed to import assets {0}".format(e))
|
||||
finally:
|
||||
# Finally, consume the logs in case there were any errors and die if there were
|
||||
log_contents = log_capture_string.getvalue()
|
||||
log_capture_string.close()
|
||||
if log_contents != '':
|
||||
module.fail_json(msg=log_contents)
|
||||
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
|
||||
# (c) 2020, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_instance_group
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
version_added: "4.0"
|
||||
short_description: create, update, or destroy Ansible Tower instance groups.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower instance groups. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name of this instance group.
|
||||
required: True
|
||||
type: str
|
||||
new_name:
|
||||
description:
|
||||
- Setting this option will change the existing name (looked up via the name field.
|
||||
type: str
|
||||
credential:
|
||||
description:
|
||||
- Credential to authenticate with Kubernetes or OpenShift. Must be of type "Kubernetes/OpenShift API Bearer Token".
|
||||
required: False
|
||||
type: str
|
||||
policy_instance_percentage:
|
||||
description:
|
||||
- Minimum percentage of all instances that will be automatically assigned to this group when new instances come online.
|
||||
required: False
|
||||
type: int
|
||||
default: '0'
|
||||
policy_instance_minimum:
|
||||
description:
|
||||
- Static minimum number of Instances that will be automatically assign to this group when new instances come online.
|
||||
required: False
|
||||
type: int
|
||||
default: '0'
|
||||
policy_instance_list:
|
||||
description:
|
||||
- List of exact-match Instances that will be assigned to this group
|
||||
required: False
|
||||
type: list
|
||||
pod_spec_override:
|
||||
description:
|
||||
- A custom Kubernetes or OpenShift Pod specification.
|
||||
required: False
|
||||
type: str
|
||||
instances:
|
||||
description:
|
||||
- The instances associated with this instance_group
|
||||
required: False
|
||||
type: list
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
choices: ["present", "absent"]
|
||||
default: "present"
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
credential=dict(),
|
||||
policy_instance_percentage=dict(type='int', default='0'),
|
||||
policy_instance_minimum=dict(type='int', default='0'),
|
||||
policy_instance_list=dict(type='list'),
|
||||
pod_spec_override=dict(),
|
||||
instances=dict(required=False, type="list", default=None),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get("new_name")
|
||||
credential = module.params.get('credential')
|
||||
policy_instance_percentage = module.params.get('policy_instance_percentage')
|
||||
policy_instance_minimum = module.params.get('policy_instance_minimum')
|
||||
policy_instance_list = module.params.get('policy_instance_list')
|
||||
pod_spec_override = module.params.get('pod_spec_override')
|
||||
instances = module.params.get('instances')
|
||||
state = module.params.get('state')
|
||||
|
||||
# Attempt to look up an existing item based on the provided data
|
||||
existing_item = module.get_one('instance_groups', name_or_id=name)
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(existing_item)
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
credential_id = None
|
||||
if credential:
|
||||
credential_id = module.resolve_name_to_id('credentials', credential)
|
||||
instances_ids = None
|
||||
if instances is not None:
|
||||
instances_ids = []
|
||||
for item in instances:
|
||||
instances_ids.append(module.resolve_name_to_id('instances', item))
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
new_fields = {}
|
||||
new_fields['name'] = new_name if new_name else (module.get_item_name(existing_item) if existing_item else name)
|
||||
if credential is not None:
|
||||
new_fields['credential'] = credential_id
|
||||
if policy_instance_percentage is not None:
|
||||
new_fields['policy_instance_percentage'] = policy_instance_percentage
|
||||
if policy_instance_minimum is not None:
|
||||
new_fields['policy_instance_minimum'] = policy_instance_minimum
|
||||
if policy_instance_list is not None:
|
||||
new_fields['policy_instance_list'] = policy_instance_list
|
||||
if pod_spec_override is not None:
|
||||
new_fields['pod_spec_override'] = pod_spec_override
|
||||
|
||||
# If the state was present and we can let the module build or update the existing item, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
existing_item, new_fields,
|
||||
endpoint='instance_groups', item_type='instance_group',
|
||||
associations={
|
||||
'instances': instances_ids,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_inventory
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: create, update, or destroy Ansible Tower inventory.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower inventories. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- The name to use for the inventory.
|
||||
required: True
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- The description to use for the inventory.
|
||||
type: str
|
||||
organization:
|
||||
description:
|
||||
- Organization the inventory belongs to.
|
||||
required: True
|
||||
type: str
|
||||
variables:
|
||||
description:
|
||||
- Inventory variables.
|
||||
type: dict
|
||||
kind:
|
||||
description:
|
||||
- The kind field. Cannot be modified after created.
|
||||
default: ""
|
||||
choices: ["", "smart"]
|
||||
type: str
|
||||
host_filter:
|
||||
description:
|
||||
- The host_filter field. Only useful when C(kind=smart).
|
||||
type: str
|
||||
insights_credential:
|
||||
description:
|
||||
- Credentials to be used by hosts belonging to this inventory when accessing Red Hat Insights API.
|
||||
type: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
default: "present"
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Add tower inventory
|
||||
tower_inventory:
|
||||
name: "Foo Inventory"
|
||||
description: "Our Foo Cloud Servers"
|
||||
organization: "Bar Org"
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
'''
|
||||
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
import json
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
description=dict(),
|
||||
organization=dict(required=True),
|
||||
variables=dict(type='dict'),
|
||||
kind=dict(choices=['', 'smart'], default=''),
|
||||
host_filter=dict(),
|
||||
insights_credential=dict(),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
description = module.params.get('description')
|
||||
organization = module.params.get('organization')
|
||||
variables = module.params.get('variables')
|
||||
state = module.params.get('state')
|
||||
kind = module.params.get('kind')
|
||||
host_filter = module.params.get('host_filter')
|
||||
insights_credential = module.params.get('insights_credential')
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
org_id = module.resolve_name_to_id('organizations', organization)
|
||||
|
||||
# Attempt to look up inventory based on the provided name and org ID
|
||||
inventory = module.get_one('inventories', name_or_id=name, **{
|
||||
'data': {
|
||||
'organization': org_id
|
||||
}
|
||||
})
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(inventory)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
inventory_fields = {
|
||||
'name': module.get_item_name(inventory) if inventory else name,
|
||||
'organization': org_id,
|
||||
'kind': kind,
|
||||
'host_filter': host_filter,
|
||||
}
|
||||
if description is not None:
|
||||
inventory_fields['description'] = description
|
||||
if variables is not None:
|
||||
inventory_fields['variables'] = json.dumps(variables)
|
||||
if insights_credential is not None:
|
||||
inventory_fields['insights_credential'] = module.resolve_name_to_id('credentials', insights_credential)
|
||||
|
||||
# We need to perform a check to make sure you are not trying to convert a regular inventory into a smart one.
|
||||
if inventory and inventory['kind'] == '' and inventory_fields['kind'] == 'smart':
|
||||
module.fail_json(msg='You cannot turn a regular inventory into a "smart" inventory.')
|
||||
|
||||
# If the state was present and we can let the module build or update the existing inventory, this will return on its own
|
||||
module.create_or_update_if_needed(inventory, inventory_fields, endpoint='inventories', item_type='inventory')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,288 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2018, Adrien Fleury <fleu42@gmail.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_inventory_source
|
||||
author: "Adrien Fleury (@fleu42)"
|
||||
short_description: create, update, or destroy Ansible Tower inventory source.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower inventory source. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- The name to use for the inventory source.
|
||||
required: True
|
||||
type: str
|
||||
new_name:
|
||||
description:
|
||||
- A new name for this assets (will rename the asset)
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- The description to use for the inventory source.
|
||||
type: str
|
||||
inventory:
|
||||
description:
|
||||
- Inventory the group should be made a member of.
|
||||
required: True
|
||||
type: str
|
||||
source:
|
||||
description:
|
||||
- The source to use for this group.
|
||||
choices: [ "scm", "ec2", "gce", "azure_rm", "vmware", "satellite6", "openstack", "rhv", "tower", "custom" ]
|
||||
type: str
|
||||
source_path:
|
||||
description:
|
||||
- For an SCM based inventory source, the source path points to the file within the repo to use as an inventory.
|
||||
type: str
|
||||
source_script:
|
||||
description:
|
||||
- Inventory script to be used when group type is C(custom).
|
||||
type: str
|
||||
source_vars:
|
||||
description:
|
||||
- The variables or environment fields to apply to this source type.
|
||||
type: dict
|
||||
enabled_var:
|
||||
description:
|
||||
- The variable to use to determine enabled state e.g., "status.power_state"
|
||||
type: str
|
||||
enabled_value:
|
||||
description:
|
||||
- Value when the host is considered enabled, e.g., "powered_on"
|
||||
type: str
|
||||
host_filter:
|
||||
description:
|
||||
- If specified, AWX will only import hosts that match this regular expression.
|
||||
type: str
|
||||
credential:
|
||||
description:
|
||||
- Credential to use for the source.
|
||||
type: str
|
||||
overwrite:
|
||||
description:
|
||||
- Delete child groups and hosts not found in source.
|
||||
type: bool
|
||||
overwrite_vars:
|
||||
description:
|
||||
- Override vars in child groups and hosts with those from external source.
|
||||
type: bool
|
||||
custom_virtualenv:
|
||||
description:
|
||||
- Local absolute file path containing a custom Python virtualenv to use.
|
||||
type: str
|
||||
timeout:
|
||||
description: The amount of time (in seconds) to run before the task is canceled.
|
||||
type: int
|
||||
verbosity:
|
||||
description: The verbosity level to run this inventory source under.
|
||||
type: int
|
||||
choices: [ 0, 1, 2 ]
|
||||
update_on_launch:
|
||||
description:
|
||||
- Refresh inventory data from its source each time a job is run.
|
||||
type: bool
|
||||
update_cache_timeout:
|
||||
description:
|
||||
- Time in seconds to consider an inventory sync to be current.
|
||||
type: int
|
||||
source_project:
|
||||
description:
|
||||
- Project to use as source with scm option
|
||||
type: str
|
||||
update_on_project_update:
|
||||
description: Update this source when the related project updates if source is C(scm)
|
||||
type: bool
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
default: "present"
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
notification_templates_started:
|
||||
description:
|
||||
- list of notifications to send on start
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_success:
|
||||
description:
|
||||
- list of notifications to send on success
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_error:
|
||||
description:
|
||||
- list of notifications to send on error
|
||||
type: list
|
||||
elements: str
|
||||
organization:
|
||||
description:
|
||||
- Name of the inventory source's inventory's organization.
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Add an inventory source
|
||||
tower_inventory_source:
|
||||
name: "source-inventory"
|
||||
description: Source for inventory
|
||||
inventory: previously-created-inventory
|
||||
credential: previously-created-credential
|
||||
overwrite: True
|
||||
update_on_launch: True
|
||||
organization: Default
|
||||
source_vars:
|
||||
private: false
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
from json import dumps
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
description=dict(),
|
||||
inventory=dict(required=True),
|
||||
#
|
||||
# How do we handle manual and file? Tower does not seem to be able to activate them
|
||||
#
|
||||
source=dict(choices=["scm", "ec2", "gce",
|
||||
"azure_rm", "vmware", "satellite6",
|
||||
"openstack", "rhv", "tower", "custom"]),
|
||||
source_path=dict(),
|
||||
source_script=dict(),
|
||||
source_vars=dict(type='dict'),
|
||||
enabled_var=dict(),
|
||||
enabled_value=dict(),
|
||||
host_filter=dict(),
|
||||
credential=dict(),
|
||||
organization=dict(),
|
||||
overwrite=dict(type='bool'),
|
||||
overwrite_vars=dict(type='bool'),
|
||||
custom_virtualenv=dict(),
|
||||
timeout=dict(type='int'),
|
||||
verbosity=dict(type='int', choices=[0, 1, 2]),
|
||||
update_on_launch=dict(type='bool'),
|
||||
update_cache_timeout=dict(type='int'),
|
||||
source_project=dict(),
|
||||
update_on_project_update=dict(type='bool'),
|
||||
notification_templates_started=dict(type="list", elements='str'),
|
||||
notification_templates_success=dict(type="list", elements='str'),
|
||||
notification_templates_error=dict(type="list", elements='str'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get('new_name')
|
||||
inventory = module.params.get('inventory')
|
||||
organization = module.params.get('organization')
|
||||
source_script = module.params.get('source_script')
|
||||
credential = module.params.get('credential')
|
||||
source_project = module.params.get('source_project')
|
||||
state = module.params.get('state')
|
||||
|
||||
lookup_data = {}
|
||||
if organization:
|
||||
lookup_data['organization'] = module.resolve_name_to_id('organizations', organization)
|
||||
inventory_object = module.get_one('inventories', name_or_id=inventory, data=lookup_data)
|
||||
|
||||
if not inventory_object:
|
||||
module.fail_json(msg='The specified inventory, {0}, was not found.'.format(lookup_data))
|
||||
|
||||
inventory_source_object = module.get_one('inventory_sources', name_or_id=name, **{
|
||||
'data': {
|
||||
'inventory': inventory_object['id'],
|
||||
}
|
||||
})
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(inventory_source_object)
|
||||
|
||||
# Attempt to look up associated field items the user specified.
|
||||
association_fields = {}
|
||||
|
||||
notifications_start = module.params.get('notification_templates_started')
|
||||
if notifications_start is not None:
|
||||
association_fields['notification_templates_started'] = []
|
||||
for item in notifications_start:
|
||||
association_fields['notification_templates_started'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_success = module.params.get('notification_templates_success')
|
||||
if notifications_success is not None:
|
||||
association_fields['notification_templates_success'] = []
|
||||
for item in notifications_success:
|
||||
association_fields['notification_templates_success'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_error = module.params.get('notification_templates_error')
|
||||
if notifications_error is not None:
|
||||
association_fields['notification_templates_error'] = []
|
||||
for item in notifications_error:
|
||||
association_fields['notification_templates_error'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
inventory_source_fields = {
|
||||
'name': new_name if new_name else name,
|
||||
'inventory': inventory_object['id'],
|
||||
}
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
if credential is not None:
|
||||
inventory_source_fields['credential'] = module.resolve_name_to_id('credentials', credential)
|
||||
if source_project is not None:
|
||||
inventory_source_fields['source_project'] = module.resolve_name_to_id('projects', source_project)
|
||||
if source_script is not None:
|
||||
inventory_source_fields['source_script'] = module.resolve_name_to_id('inventory_scripts', source_script)
|
||||
|
||||
OPTIONAL_VARS = (
|
||||
'description', 'source', 'source_path', 'source_vars',
|
||||
'overwrite', 'overwrite_vars', 'custom_virtualenv',
|
||||
'timeout', 'verbosity', 'update_on_launch', 'update_cache_timeout',
|
||||
'update_on_project_update', 'enabled_var', 'enabled_value', 'host_filter',
|
||||
)
|
||||
|
||||
# Layer in all remaining optional information
|
||||
for field_name in OPTIONAL_VARS:
|
||||
field_val = module.params.get(field_name)
|
||||
if field_val is not None:
|
||||
inventory_source_fields[field_name] = field_val
|
||||
|
||||
# Attempt to JSON encode source vars
|
||||
if inventory_source_fields.get('source_vars', None):
|
||||
inventory_source_fields['source_vars'] = dumps(inventory_source_fields['source_vars'])
|
||||
|
||||
# Sanity check on arguments
|
||||
if state == 'present' and not inventory_source_object and not inventory_source_fields['source']:
|
||||
module.fail_json(msg="If creating a new inventory source, the source param must be present")
|
||||
|
||||
# If the state was present we can let the module build or update the existing inventory_source_object, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
inventory_source_object, inventory_source_fields,
|
||||
endpoint='inventory_sources', item_type='inventory source',
|
||||
associations=association_fields
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2020, Bianca Henderson <bianca@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_inventory_source_update
|
||||
author: "Bianca Henderson (@beeankha)"
|
||||
short_description: Update inventory source(s).
|
||||
description:
|
||||
- Update Ansible Tower inventory source(s). See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- The name or id of the inventory source to update.
|
||||
required: True
|
||||
type: str
|
||||
aliases:
|
||||
- inventory_source
|
||||
inventory:
|
||||
description:
|
||||
- Name or id of the inventory that contains the inventory source(s) to update.
|
||||
required: True
|
||||
type: str
|
||||
organization:
|
||||
description:
|
||||
- Name of the inventory source's inventory's organization.
|
||||
type: str
|
||||
wait:
|
||||
description:
|
||||
- Wait for the job to complete.
|
||||
default: False
|
||||
type: bool
|
||||
interval:
|
||||
description:
|
||||
- The interval to request an update from Tower.
|
||||
required: False
|
||||
default: 1
|
||||
type: float
|
||||
timeout:
|
||||
description:
|
||||
- If waiting for the job to complete this will abort after this
|
||||
amount of seconds
|
||||
type: int
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Update a single inventory source
|
||||
tower_inventory_source_update:
|
||||
name: "Example Inventory Source"
|
||||
inventory: "My Inventory"
|
||||
organization: Default
|
||||
|
||||
- name: Update all inventory sources
|
||||
tower_inventory_source_update:
|
||||
name: "{{ item }}"
|
||||
inventory: "My Other Inventory"
|
||||
loop: "{{ query('awx.awx.tower_api', 'inventory_sources', query_params={ 'inventory': 30 }, return_ids=True ) }}"
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
id:
|
||||
description: id of the inventory update
|
||||
returned: success
|
||||
type: int
|
||||
sample: 86
|
||||
status:
|
||||
description: status of the inventory update
|
||||
returned: success
|
||||
type: str
|
||||
sample: pending
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True, aliases=['inventory_source']),
|
||||
inventory=dict(required=True),
|
||||
organization=dict(),
|
||||
wait=dict(default=False, type='bool'),
|
||||
interval=dict(default=1.0, type='float'),
|
||||
timeout=dict(default=None, type='int'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
inventory = module.params.get('inventory')
|
||||
organization = module.params.get('organization')
|
||||
wait = module.params.get('wait')
|
||||
interval = module.params.get('interval')
|
||||
timeout = module.params.get('timeout')
|
||||
|
||||
lookup_data = {}
|
||||
if organization:
|
||||
lookup_data['organization'] = module.resolve_name_to_id('organizations', organization)
|
||||
inventory_object = module.get_one('inventories', name_or_id=inventory, data=lookup_data)
|
||||
|
||||
if not inventory_object:
|
||||
module.fail_json(msg='The specified inventory, {0}, was not found.'.format(lookup_data))
|
||||
|
||||
inventory_source_object = module.get_one('inventory_sources',
|
||||
name_or_id=name,
|
||||
data={'inventory': inventory_object['id']})
|
||||
|
||||
if not inventory_source_object:
|
||||
module.fail_json(msg='The specified inventory source was not found.')
|
||||
|
||||
# Sync the inventory source(s)
|
||||
inventory_source_update_results = module.post_endpoint(inventory_source_object['related']['update'])
|
||||
|
||||
if inventory_source_update_results['status_code'] != 202:
|
||||
module.fail_json(msg="Failed to update inventory source, see response for details", response=inventory_source_update_results)
|
||||
|
||||
module.json_output['changed'] = True
|
||||
module.json_output['id'] = inventory_source_update_results['json']['id']
|
||||
module.json_output['status'] = inventory_source_update_results['json']['status']
|
||||
|
||||
if not wait:
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
# Invoke wait function
|
||||
module.wait_on_url(
|
||||
url=inventory_source_update_results['json']['url'],
|
||||
object_name=inventory_object,
|
||||
object_type='inventory_update',
|
||||
timeout=timeout, interval=interval
|
||||
)
|
||||
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_job_cancel
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: Cancel an Ansible Tower Job.
|
||||
description:
|
||||
- Cancel Ansible Tower jobs. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
job_id:
|
||||
description:
|
||||
- ID of the job to cancel
|
||||
required: True
|
||||
type: int
|
||||
fail_if_not_running:
|
||||
description:
|
||||
- Fail loudly if the I(job_id) can not be canceled
|
||||
default: False
|
||||
type: bool
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Cancel job
|
||||
tower_job_cancel:
|
||||
job_id: job.id
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
id:
|
||||
description: job id requesting to cancel
|
||||
returned: success
|
||||
type: int
|
||||
sample: 94
|
||||
'''
|
||||
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
job_id=dict(type='int', required=True),
|
||||
fail_if_not_running=dict(type='bool', default=False),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
job_id = module.params.get('job_id')
|
||||
fail_if_not_running = module.params.get('fail_if_not_running')
|
||||
|
||||
# Attempt to look up the job based on the provided name
|
||||
job = module.get_one('jobs', **{
|
||||
'data': {
|
||||
'id': job_id,
|
||||
}
|
||||
})
|
||||
|
||||
if job is None:
|
||||
module.fail_json(msg="Unable to find job with id {0}".format(job_id))
|
||||
|
||||
cancel_page = module.get_endpoint(job['related']['cancel'])
|
||||
if 'json' not in cancel_page or 'can_cancel' not in cancel_page['json']:
|
||||
module.fail_json(msg="Failed to cancel job, got unexpected response from tower", **{'response': cancel_page})
|
||||
|
||||
if not cancel_page['json']['can_cancel']:
|
||||
if fail_if_not_running:
|
||||
module.fail_json(msg="Job is not running")
|
||||
else:
|
||||
module.exit_json(**{'changed': False})
|
||||
|
||||
results = module.post_endpoint(job['related']['cancel'], **{'data': {}})
|
||||
|
||||
if results['status_code'] != 202:
|
||||
module.fail_json(msg="Failed to cancel job, see response for details", **{'response': results})
|
||||
|
||||
module.exit_json(**{'changed': True})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,273 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_job_launch
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: Launch an Ansible Job.
|
||||
description:
|
||||
- Launch an Ansible Tower jobs. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name of the job template to use.
|
||||
required: True
|
||||
type: str
|
||||
aliases: ['job_template']
|
||||
job_type:
|
||||
description:
|
||||
- Job_type to use for the job, only used if prompt for job_type is set.
|
||||
choices: ["run", "check"]
|
||||
type: str
|
||||
inventory:
|
||||
description:
|
||||
- Inventory to use for the job, only used if prompt for inventory is set.
|
||||
type: str
|
||||
organization:
|
||||
description:
|
||||
- Organization the job template exists in.
|
||||
- Used to help lookup the object, cannot be modified using this module.
|
||||
- If not provided, will lookup by name only, which does not work with duplicates.
|
||||
type: str
|
||||
credentials:
|
||||
description:
|
||||
- Credential to use for job, only used if prompt for credential is set.
|
||||
type: list
|
||||
aliases: ['credential']
|
||||
elements: str
|
||||
extra_vars:
|
||||
description:
|
||||
- extra_vars to use for the Job Template.
|
||||
- ask_extra_vars needs to be set to True via tower_job_template module
|
||||
when creating the Job Template.
|
||||
type: dict
|
||||
limit:
|
||||
description:
|
||||
- Limit to use for the I(job_template).
|
||||
type: str
|
||||
tags:
|
||||
description:
|
||||
- Specific tags to use for from playbook.
|
||||
type: list
|
||||
elements: str
|
||||
scm_branch:
|
||||
description:
|
||||
- A specific of the SCM project to run the template on.
|
||||
- This is only applicable if your project allows for branch override.
|
||||
type: str
|
||||
skip_tags:
|
||||
description:
|
||||
- Specific tags to skip from the playbook.
|
||||
type: list
|
||||
elements: str
|
||||
verbosity:
|
||||
description:
|
||||
- Verbosity level for this job run
|
||||
type: int
|
||||
choices: [ 0, 1, 2, 3, 4, 5 ]
|
||||
diff_mode:
|
||||
description:
|
||||
- Show the changes made by Ansible tasks where supported
|
||||
type: bool
|
||||
credential_passwords:
|
||||
description:
|
||||
- Passwords for credentials which are set to prompt on launch
|
||||
type: dict
|
||||
wait:
|
||||
description:
|
||||
- Wait for the job to complete.
|
||||
default: False
|
||||
type: bool
|
||||
interval:
|
||||
description:
|
||||
- The interval to request an update from Tower.
|
||||
required: False
|
||||
default: 1
|
||||
type: float
|
||||
timeout:
|
||||
description:
|
||||
- If waiting for the job to complete this will abort after this
|
||||
amount of seconds
|
||||
type: int
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Launch a job
|
||||
tower_job_launch:
|
||||
job_template: "My Job Template"
|
||||
register: job
|
||||
|
||||
- name: Launch a job template with extra_vars on remote Tower instance
|
||||
tower_job_launch:
|
||||
job_template: "My Job Template"
|
||||
extra_vars:
|
||||
var1: "My First Variable"
|
||||
var2: "My Second Variable"
|
||||
var3: "My Third Variable"
|
||||
job_type: run
|
||||
|
||||
- name: Launch a job with inventory and credential
|
||||
tower_job_launch:
|
||||
job_template: "My Job Template"
|
||||
inventory: "My Inventory"
|
||||
credential: "My Credential"
|
||||
register: job
|
||||
- name: Wait for job max 120s
|
||||
tower_job_wait:
|
||||
job_id: "{{ job.id }}"
|
||||
timeout: 120
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
id:
|
||||
description: job id of the newly launched job
|
||||
returned: success
|
||||
type: int
|
||||
sample: 86
|
||||
status:
|
||||
description: status of newly launched job
|
||||
returned: success
|
||||
type: str
|
||||
sample: pending
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True, aliases=['job_template']),
|
||||
job_type=dict(choices=['run', 'check']),
|
||||
inventory=dict(default=None),
|
||||
organization=dict(),
|
||||
# Credentials will be a str instead of a list for backwards compatability
|
||||
credentials=dict(type='list', default=None, aliases=['credential'], elements='str'),
|
||||
limit=dict(),
|
||||
tags=dict(type='list', elements='str'),
|
||||
extra_vars=dict(type='dict'),
|
||||
scm_branch=dict(),
|
||||
skip_tags=dict(type='list', elements='str'),
|
||||
verbosity=dict(type='int', choices=[0, 1, 2, 3, 4, 5]),
|
||||
diff_mode=dict(type='bool'),
|
||||
credential_passwords=dict(type='dict'),
|
||||
wait=dict(default=False, type='bool'),
|
||||
interval=dict(default=1.0, type='float'),
|
||||
timeout=dict(default=None, type='int'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
optional_args = {}
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
optional_args['job_type'] = module.params.get('job_type')
|
||||
inventory = module.params.get('inventory')
|
||||
organization = module.params.get('organization')
|
||||
credentials = module.params.get('credentials')
|
||||
optional_args['limit'] = module.params.get('limit')
|
||||
optional_args['tags'] = module.params.get('tags')
|
||||
optional_args['extra_vars'] = module.params.get('extra_vars')
|
||||
optional_args['scm_branch'] = module.params.get('scm_branch')
|
||||
optional_args['skip_tags'] = module.params.get('skip_tags')
|
||||
optional_args['verbosity'] = module.params.get('verbosity')
|
||||
optional_args['diff_mode'] = module.params.get('diff_mode')
|
||||
optional_args['credential_passwords'] = module.params.get('credential_passwords')
|
||||
wait = module.params.get('wait')
|
||||
interval = module.params.get('interval')
|
||||
timeout = module.params.get('timeout')
|
||||
|
||||
# Create a datastructure to pass into our job launch
|
||||
post_data = {}
|
||||
for key in optional_args.keys():
|
||||
if optional_args[key]:
|
||||
post_data[key] = optional_args[key]
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
if inventory:
|
||||
post_data['inventory'] = module.resolve_name_to_id('inventories', inventory)
|
||||
|
||||
if credentials:
|
||||
post_data['credentials'] = []
|
||||
for credential in credentials:
|
||||
post_data['credentials'].append(module.resolve_name_to_id('credentials', credential))
|
||||
|
||||
# Attempt to look up job_template based on the provided name
|
||||
lookup_data = {}
|
||||
if organization:
|
||||
lookup_data['organization'] = module.resolve_name_to_id('organizations', organization)
|
||||
job_template = module.get_one('job_templates', name_or_id=name, data=lookup_data)
|
||||
|
||||
if job_template is None:
|
||||
module.fail_json(msg="Unable to find job template by name {0}".format(name))
|
||||
|
||||
# The API will allow you to submit values to a jb launch that are not prompt on launch.
|
||||
# Therefore, we will test to see if anything is set which is not prompt on launch and fail.
|
||||
check_vars_to_prompts = {
|
||||
'scm_branch': 'ask_scm_branch_on_launch',
|
||||
'diff_mode': 'ask_diff_mode_on_launch',
|
||||
'limit': 'ask_limit_on_launch',
|
||||
'tags': 'ask_tags_on_launch',
|
||||
'skip_tags': 'ask_skip_tags_on_launch',
|
||||
'job_type': 'ask_job_type_on_launch',
|
||||
'verbosity': 'ask_verbosity_on_launch',
|
||||
'inventory': 'ask_inventory_on_launch',
|
||||
'credentials': 'ask_credential_on_launch',
|
||||
}
|
||||
|
||||
param_errors = []
|
||||
for variable_name in check_vars_to_prompts:
|
||||
if module.params.get(variable_name) and not job_template[check_vars_to_prompts[variable_name]]:
|
||||
param_errors.append("The field {0} was specified but the job template does not allow for it to be overridden".format(variable_name))
|
||||
# Check if Either ask_variables_on_launch, or survey_enabled is enabled for use of extra vars.
|
||||
if module.params.get('extra_vars') and not (job_template['ask_variables_on_launch'] or job_template['survey_enabled']):
|
||||
param_errors.append("The field extra_vars was specified but the job template does not allow for it to be overridden")
|
||||
if len(param_errors) > 0:
|
||||
module.fail_json(msg="Parameters specified which can not be passed into job template, see errors for details", **{'errors': param_errors})
|
||||
|
||||
# Launch the job
|
||||
results = module.post_endpoint(job_template['related']['launch'], **{'data': post_data})
|
||||
|
||||
if results['status_code'] != 201:
|
||||
module.fail_json(msg="Failed to launch job, see response for details", **{'response': results})
|
||||
|
||||
if not wait:
|
||||
module.exit_json(**{
|
||||
'changed': True,
|
||||
'id': results['json']['id'],
|
||||
'status': results['json']['status'],
|
||||
})
|
||||
|
||||
# Invoke wait function
|
||||
results = module.wait_on_url(
|
||||
url=results['json']['url'],
|
||||
object_name=name,
|
||||
object_type='Job',
|
||||
timeout=timeout, interval=interval
|
||||
)
|
||||
|
||||
module.exit_json(**{
|
||||
'changed': True,
|
||||
'id': results['json']['id'],
|
||||
'status': results['json']['status'],
|
||||
})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_job_list
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: List Ansible Tower jobs.
|
||||
description:
|
||||
- List Ansible Tower jobs. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
status:
|
||||
description:
|
||||
- Only list jobs with this status.
|
||||
choices: ['pending', 'waiting', 'running', 'error', 'failed', 'canceled', 'successful']
|
||||
type: str
|
||||
page:
|
||||
description:
|
||||
- Page number of the results to fetch.
|
||||
type: int
|
||||
all_pages:
|
||||
description:
|
||||
- Fetch all the pages and return a single result.
|
||||
type: bool
|
||||
default: 'no'
|
||||
query:
|
||||
description:
|
||||
- Query used to further filter the list of jobs. C({"foo":"bar"}) will be passed at C(?foo=bar)
|
||||
type: dict
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: List running jobs for the testing.yml playbook
|
||||
tower_job_list:
|
||||
status: running
|
||||
query: {"playbook": "testing.yml"}
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
register: testing_jobs
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
count:
|
||||
description: Total count of objects return
|
||||
returned: success
|
||||
type: int
|
||||
sample: 51
|
||||
next:
|
||||
description: next page available for the listing
|
||||
returned: success
|
||||
type: int
|
||||
sample: 3
|
||||
previous:
|
||||
description: previous page available for the listing
|
||||
returned: success
|
||||
type: int
|
||||
sample: 1
|
||||
results:
|
||||
description: a list of job objects represented as dictionaries
|
||||
returned: success
|
||||
type: list
|
||||
sample: [{"allow_simultaneous": false, "artifacts": {}, "ask_credential_on_launch": false,
|
||||
"ask_inventory_on_launch": false, "ask_job_type_on_launch": false, "failed": false,
|
||||
"finished": "2017-02-22T15:09:05.633942Z", "force_handlers": false, "forks": 0, "id": 2,
|
||||
"inventory": 1, "job_explanation": "", "job_tags": "", "job_template": 5, "job_type": "run"}, ...]
|
||||
'''
|
||||
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
status=dict(choices=['pending', 'waiting', 'running', 'error', 'failed', 'canceled', 'successful']),
|
||||
page=dict(type='int'),
|
||||
all_pages=dict(type='bool', default=False),
|
||||
query=dict(type='dict'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(
|
||||
argument_spec=argument_spec,
|
||||
mutually_exclusive=[
|
||||
('page', 'all_pages'),
|
||||
]
|
||||
)
|
||||
|
||||
# Extract our parameters
|
||||
query = module.params.get('query')
|
||||
status = module.params.get('status')
|
||||
page = module.params.get('page')
|
||||
all_pages = module.params.get('all_pages')
|
||||
|
||||
job_search_data = {}
|
||||
if page:
|
||||
job_search_data['page'] = page
|
||||
if status:
|
||||
job_search_data['status'] = status
|
||||
if query:
|
||||
job_search_data.update(query)
|
||||
if all_pages:
|
||||
job_list = module.get_all_endpoint('jobs', **{'data': job_search_data})
|
||||
else:
|
||||
job_list = module.get_endpoint('jobs', **{'data': job_search_data})
|
||||
|
||||
# Attempt to look up jobs based on the status
|
||||
module.exit_json(**job_list['json'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,531 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_job_template
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: create, update, or destroy Ansible Tower job templates.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower job templates. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name to use for the job template.
|
||||
required: True
|
||||
type: str
|
||||
new_name:
|
||||
description:
|
||||
- Setting this option will change the existing name (looed up via the name field.
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- Description to use for the job template.
|
||||
type: str
|
||||
job_type:
|
||||
description:
|
||||
- The job type to use for the job template.
|
||||
choices: ["run", "check"]
|
||||
type: str
|
||||
inventory:
|
||||
description:
|
||||
- Name of the inventory to use for the job template.
|
||||
type: str
|
||||
organization:
|
||||
description:
|
||||
- Organization the job template exists in.
|
||||
- Used to help lookup the object, cannot be modified using this module.
|
||||
- The Organization is inferred from the associated project
|
||||
- If not provided, will lookup by name only, which does not work with duplicates.
|
||||
- Requires Tower Version 3.7.0 or AWX 10.0.0 IS NOT backwards compatible with earlier versions.
|
||||
type: str
|
||||
project:
|
||||
description:
|
||||
- Name of the project to use for the job template.
|
||||
type: str
|
||||
playbook:
|
||||
description:
|
||||
- Path to the playbook to use for the job template within the project provided.
|
||||
type: str
|
||||
credential:
|
||||
description:
|
||||
- Name of the credential to use for the job template.
|
||||
- Deprecated, use 'credentials'.
|
||||
type: str
|
||||
credentials:
|
||||
description:
|
||||
- List of credentials to use for the job template.
|
||||
type: list
|
||||
elements: str
|
||||
vault_credential:
|
||||
description:
|
||||
- Name of the vault credential to use for the job template.
|
||||
- Deprecated, use 'credentials'.
|
||||
type: str
|
||||
forks:
|
||||
description:
|
||||
- The number of parallel or simultaneous processes to use while executing the playbook.
|
||||
type: int
|
||||
limit:
|
||||
description:
|
||||
- A host pattern to further constrain the list of hosts managed or affected by the playbook
|
||||
type: str
|
||||
verbosity:
|
||||
description:
|
||||
- Control the output level Ansible produces as the playbook runs. 0 - Normal, 1 - Verbose, 2 - More Verbose, 3 - Debug, 4 - Connection Debug.
|
||||
choices: [0, 1, 2, 3, 4]
|
||||
default: 0
|
||||
type: int
|
||||
extra_vars:
|
||||
description:
|
||||
- Specify C(extra_vars) for the template.
|
||||
type: dict
|
||||
job_tags:
|
||||
description:
|
||||
- Comma separated list of the tags to use for the job template.
|
||||
type: str
|
||||
force_handlers:
|
||||
description:
|
||||
- Enable forcing playbook handlers to run even if a task fails.
|
||||
type: bool
|
||||
default: 'no'
|
||||
aliases:
|
||||
- force_handlers_enabled
|
||||
skip_tags:
|
||||
description:
|
||||
- Comma separated list of the tags to skip for the job template.
|
||||
type: str
|
||||
start_at_task:
|
||||
description:
|
||||
- Start the playbook at the task matching this name.
|
||||
type: str
|
||||
diff_mode:
|
||||
description:
|
||||
- Enable diff mode for the job template.
|
||||
type: bool
|
||||
aliases:
|
||||
- diff_mode_enabled
|
||||
default: 'no'
|
||||
use_fact_cache:
|
||||
description:
|
||||
- Enable use of fact caching for the job template.
|
||||
type: bool
|
||||
default: 'no'
|
||||
aliases:
|
||||
- fact_caching_enabled
|
||||
host_config_key:
|
||||
description:
|
||||
- Allow provisioning callbacks using this host config key.
|
||||
type: str
|
||||
ask_scm_branch_on_launch:
|
||||
description:
|
||||
- Prompt user for (scm branch) on launch.
|
||||
type: bool
|
||||
default: 'False'
|
||||
ask_diff_mode_on_launch:
|
||||
description:
|
||||
- Prompt user to enable diff mode (show changes) to files when supported by modules.
|
||||
type: bool
|
||||
default: 'False'
|
||||
aliases:
|
||||
- ask_diff_mode
|
||||
ask_variables_on_launch:
|
||||
description:
|
||||
- Prompt user for (extra_vars) on launch.
|
||||
type: bool
|
||||
default: 'False'
|
||||
aliases:
|
||||
- ask_extra_vars
|
||||
ask_limit_on_launch:
|
||||
description:
|
||||
- Prompt user for a limit on launch.
|
||||
type: bool
|
||||
default: 'False'
|
||||
aliases:
|
||||
- ask_limit
|
||||
ask_tags_on_launch:
|
||||
description:
|
||||
- Prompt user for job tags on launch.
|
||||
type: bool
|
||||
default: 'False'
|
||||
aliases:
|
||||
- ask_tags
|
||||
ask_skip_tags_on_launch:
|
||||
description:
|
||||
- Prompt user for job tags to skip on launch.
|
||||
type: bool
|
||||
default: 'False'
|
||||
aliases:
|
||||
- ask_skip_tags
|
||||
ask_job_type_on_launch:
|
||||
description:
|
||||
- Prompt user for job type on launch.
|
||||
type: bool
|
||||
default: 'False'
|
||||
aliases:
|
||||
- ask_job_type
|
||||
ask_verbosity_on_launch:
|
||||
description:
|
||||
- Prompt user to choose a verbosity level on launch.
|
||||
type: bool
|
||||
default: 'False'
|
||||
aliases:
|
||||
- ask_verbosity
|
||||
ask_inventory_on_launch:
|
||||
description:
|
||||
- Prompt user for inventory on launch.
|
||||
type: bool
|
||||
default: 'False'
|
||||
aliases:
|
||||
- ask_inventory
|
||||
ask_credential_on_launch:
|
||||
description:
|
||||
- Prompt user for credential on launch.
|
||||
type: bool
|
||||
default: 'False'
|
||||
aliases:
|
||||
- ask_credential
|
||||
survey_enabled:
|
||||
description:
|
||||
- Enable a survey on the job template.
|
||||
type: bool
|
||||
default: 'no'
|
||||
survey_spec:
|
||||
description:
|
||||
- JSON/YAML dict formatted survey definition.
|
||||
type: dict
|
||||
become_enabled:
|
||||
description:
|
||||
- Activate privilege escalation.
|
||||
type: bool
|
||||
default: 'no'
|
||||
allow_simultaneous:
|
||||
description:
|
||||
- Allow simultaneous runs of the job template.
|
||||
type: bool
|
||||
default: 'no'
|
||||
aliases:
|
||||
- concurrent_jobs_enabled
|
||||
timeout:
|
||||
description:
|
||||
- Maximum time in seconds to wait for a job to finish (server-side).
|
||||
type: int
|
||||
custom_virtualenv:
|
||||
description:
|
||||
- Local absolute file path containing a custom Python virtualenv to use.
|
||||
type: str
|
||||
job_slice_count:
|
||||
description:
|
||||
- The number of jobs to slice into at runtime. Will cause the Job Template to launch a workflow if value is greater than 1.
|
||||
type: int
|
||||
default: '1'
|
||||
webhook_service:
|
||||
description:
|
||||
- Service that webhook requests will be accepted from
|
||||
type: str
|
||||
choices:
|
||||
- ''
|
||||
- 'github'
|
||||
- 'gitlab'
|
||||
webhook_credential:
|
||||
description:
|
||||
- Personal Access Token for posting back the status to the service API
|
||||
type: str
|
||||
scm_branch:
|
||||
description:
|
||||
- Branch to use in job run. Project default used if blank. Only allowed if project allow_override field is set to true.
|
||||
type: str
|
||||
default: ''
|
||||
labels:
|
||||
description:
|
||||
- The labels applied to this job template
|
||||
type: list
|
||||
elements: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
default: "present"
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
notification_templates_started:
|
||||
description:
|
||||
- list of notifications to send on start
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_success:
|
||||
description:
|
||||
- list of notifications to send on success
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_error:
|
||||
description:
|
||||
- list of notifications to send on error
|
||||
type: list
|
||||
elements: str
|
||||
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
|
||||
notes:
|
||||
- JSON for survey_spec can be found in Tower API Documentation. See
|
||||
U(https://docs.ansible.com/ansible-tower/latest/html/towerapi/api_ref.html#/Job_Templates/Job_Templates_job_templates_survey_spec_create)
|
||||
for POST operation payload example.
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create Tower Ping job template
|
||||
tower_job_template:
|
||||
name: "Ping"
|
||||
job_type: "run"
|
||||
organization: "Default"
|
||||
inventory: "Local"
|
||||
project: "Demo"
|
||||
playbook: "ping.yml"
|
||||
credentials:
|
||||
- "Local"
|
||||
state: "present"
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
survey_enabled: yes
|
||||
survey_spec: "{{ lookup('file', 'my_survey.json') }}"
|
||||
custom_virtualenv: "/var/lib/awx/venv/custom-venv/"
|
||||
|
||||
- name: Add start notification to Job Template
|
||||
tower_job_template:
|
||||
name: "Ping"
|
||||
notification_templates_started:
|
||||
- Notification1
|
||||
- Notification2
|
||||
|
||||
- name: Remove Notification1 start notification from Job Template
|
||||
tower_job_template:
|
||||
name: "Ping"
|
||||
notification_templates_started:
|
||||
- Notification2
|
||||
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
import json
|
||||
|
||||
|
||||
def update_survey(module, last_request):
|
||||
spec_endpoint = last_request.get('related', {}).get('survey_spec')
|
||||
if module.params.get('survey_spec') == {}:
|
||||
response = module.delete_endpoint(spec_endpoint)
|
||||
if response['status_code'] != 200:
|
||||
# Not sure how to make this actually return a non 200 to test what to dump in the respinse
|
||||
module.fail_json(msg="Failed to delete survey: {0}".format(response['json']))
|
||||
else:
|
||||
response = module.post_endpoint(spec_endpoint, **{'data': module.params.get('survey_spec')})
|
||||
if response['status_code'] != 200:
|
||||
module.fail_json(msg="Failed to update survey: {0}".format(response['json']['error']))
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
description=dict(),
|
||||
organization=dict(),
|
||||
job_type=dict(choices=['run', 'check']),
|
||||
inventory=dict(),
|
||||
project=dict(),
|
||||
playbook=dict(),
|
||||
credential=dict(),
|
||||
vault_credential=dict(),
|
||||
custom_virtualenv=dict(),
|
||||
credentials=dict(type='list', elements='str'),
|
||||
forks=dict(type='int'),
|
||||
limit=dict(),
|
||||
verbosity=dict(type='int', choices=[0, 1, 2, 3, 4], default=0),
|
||||
extra_vars=dict(type='dict'),
|
||||
job_tags=dict(),
|
||||
force_handlers=dict(type='bool', default=False, aliases=['force_handlers_enabled']),
|
||||
skip_tags=dict(),
|
||||
start_at_task=dict(),
|
||||
timeout=dict(type='int', default=0),
|
||||
use_fact_cache=dict(type='bool', aliases=['fact_caching_enabled']),
|
||||
host_config_key=dict(),
|
||||
ask_diff_mode_on_launch=dict(type='bool', aliases=['ask_diff_mode']),
|
||||
ask_variables_on_launch=dict(type='bool', aliases=['ask_extra_vars']),
|
||||
ask_limit_on_launch=dict(type='bool', aliases=['ask_limit']),
|
||||
ask_tags_on_launch=dict(type='bool', aliases=['ask_tags']),
|
||||
ask_skip_tags_on_launch=dict(type='bool', aliases=['ask_skip_tags']),
|
||||
ask_job_type_on_launch=dict(type='bool', aliases=['ask_job_type']),
|
||||
ask_verbosity_on_launch=dict(type='bool', aliases=['ask_verbosity']),
|
||||
ask_inventory_on_launch=dict(type='bool', aliases=['ask_inventory']),
|
||||
ask_credential_on_launch=dict(type='bool', aliases=['ask_credential']),
|
||||
survey_enabled=dict(type='bool'),
|
||||
survey_spec=dict(type="dict"),
|
||||
become_enabled=dict(type='bool'),
|
||||
diff_mode=dict(type='bool', aliases=['diff_mode_enabled']),
|
||||
allow_simultaneous=dict(type='bool', aliases=['concurrent_jobs_enabled']),
|
||||
scm_branch=dict(),
|
||||
ask_scm_branch_on_launch=dict(type='bool'),
|
||||
job_slice_count=dict(type='int', default='1'),
|
||||
webhook_service=dict(choices=['github', 'gitlab', '']),
|
||||
webhook_credential=dict(),
|
||||
labels=dict(type="list", elements='str'),
|
||||
notification_templates_started=dict(type="list", elements='str'),
|
||||
notification_templates_success=dict(type="list", elements='str'),
|
||||
notification_templates_error=dict(type="list", elements='str'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get("new_name")
|
||||
state = module.params.get('state')
|
||||
|
||||
# Deal with legacy credential and vault_credential
|
||||
credential = module.params.get('credential')
|
||||
vault_credential = module.params.get('vault_credential')
|
||||
credentials = module.params.get('credentials')
|
||||
if vault_credential:
|
||||
if credentials is None:
|
||||
credentials = []
|
||||
credentials.append(vault_credential)
|
||||
if credential:
|
||||
if credentials is None:
|
||||
credentials = []
|
||||
credentials.append(credential)
|
||||
|
||||
new_fields = {}
|
||||
search_fields = {}
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
organization_id = None
|
||||
organization = module.params.get('organization')
|
||||
if organization:
|
||||
organization_id = module.resolve_name_to_id('organizations', organization)
|
||||
search_fields['organization'] = new_fields['organization'] = organization_id
|
||||
|
||||
# Attempt to look up an existing item based on the provided data
|
||||
existing_item = module.get_one('job_templates', name_or_id=name, **{'data': search_fields})
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(existing_item)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
new_fields['name'] = new_name if new_name else (module.get_item_name(existing_item) if existing_item else name)
|
||||
for field_name in (
|
||||
'description', 'job_type', 'playbook', 'scm_branch', 'forks', 'limit', 'verbosity',
|
||||
'job_tags', 'force_handlers', 'skip_tags', 'start_at_task', 'timeout', 'use_fact_cache',
|
||||
'host_config_key', 'ask_scm_branch_on_launch', 'ask_diff_mode_on_launch', 'ask_variables_on_launch',
|
||||
'ask_limit_on_launch', 'ask_tags_on_launch', 'ask_skip_tags_on_launch', 'ask_job_type_on_launch',
|
||||
'ask_verbosity_on_launch', 'ask_inventory_on_launch', 'ask_credential_on_launch', 'survey_enabled',
|
||||
'become_enabled', 'diff_mode', 'allow_simultaneous', 'custom_virtualenv', 'job_slice_count', 'webhook_service',
|
||||
):
|
||||
field_val = module.params.get(field_name)
|
||||
if field_val is not None:
|
||||
new_fields[field_name] = field_val
|
||||
|
||||
# Special treatment of extra_vars parameter
|
||||
extra_vars = module.params.get('extra_vars')
|
||||
if extra_vars is not None:
|
||||
new_fields['extra_vars'] = json.dumps(extra_vars)
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
inventory = module.params.get('inventory')
|
||||
project = module.params.get('project')
|
||||
webhook_credential = module.params.get('webhook_credential')
|
||||
|
||||
if inventory is not None:
|
||||
new_fields['inventory'] = module.resolve_name_to_id('inventories', inventory)
|
||||
if project is not None:
|
||||
if organization_id is not None:
|
||||
project_data = module.get_one('projects', name_or_id=project, **{
|
||||
'data': {
|
||||
'organization': organization_id,
|
||||
}
|
||||
})
|
||||
if project_data is None:
|
||||
module.fail_json(msg="The project {0} in organization {1} was not found on the Tower server".format(
|
||||
project, organization
|
||||
))
|
||||
new_fields['project'] = project_data['id']
|
||||
else:
|
||||
new_fields['project'] = module.resolve_name_to_id('projects', project)
|
||||
if webhook_credential is not None:
|
||||
new_fields['webhook_credential'] = module.resolve_name_to_id('credentials', webhook_credential)
|
||||
|
||||
association_fields = {}
|
||||
|
||||
if credentials is not None:
|
||||
association_fields['credentials'] = []
|
||||
for item in credentials:
|
||||
association_fields['credentials'].append(module.resolve_name_to_id('credentials', item))
|
||||
|
||||
labels = module.params.get('labels')
|
||||
if labels is not None:
|
||||
association_fields['labels'] = []
|
||||
for item in labels:
|
||||
association_fields['labels'].append(module.resolve_name_to_id('labels', item))
|
||||
# Code to use once Issue #7567 is resolved
|
||||
# search_fields = {'name': item}
|
||||
# if organization:
|
||||
# search_fields['organization'] = organization_id
|
||||
# label_id = module.get_one('labels', **{'data': search_fields})
|
||||
# association_fields['labels'].append(label_id)
|
||||
|
||||
notifications_start = module.params.get('notification_templates_started')
|
||||
if notifications_start is not None:
|
||||
association_fields['notification_templates_started'] = []
|
||||
for item in notifications_start:
|
||||
association_fields['notification_templates_started'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_success = module.params.get('notification_templates_success')
|
||||
if notifications_success is not None:
|
||||
association_fields['notification_templates_success'] = []
|
||||
for item in notifications_success:
|
||||
association_fields['notification_templates_success'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_error = module.params.get('notification_templates_error')
|
||||
if notifications_error is not None:
|
||||
association_fields['notification_templates_error'] = []
|
||||
for item in notifications_error:
|
||||
association_fields['notification_templates_error'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
on_change = None
|
||||
new_spec = module.params.get('survey_spec')
|
||||
if new_spec is not None:
|
||||
existing_spec = None
|
||||
if existing_item:
|
||||
spec_endpoint = existing_item.get('related', {}).get('survey_spec')
|
||||
existing_spec = module.get_endpoint(spec_endpoint)['json']
|
||||
if new_spec != existing_spec:
|
||||
module.json_output['changed'] = True
|
||||
if existing_item and module.has_encrypted_values(existing_spec):
|
||||
module._encrypted_changed_warning('survey_spec', existing_item, warning=True)
|
||||
on_change = update_survey
|
||||
|
||||
# If the state was present and we can let the module build or update the existing item, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
existing_item, new_fields,
|
||||
endpoint='job_templates', item_type='job_template',
|
||||
associations=association_fields,
|
||||
on_create=on_change, on_update=on_change,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_job_wait
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: Wait for Ansible Tower job to finish.
|
||||
description:
|
||||
- Wait for Ansible Tower job to finish and report success or failure. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
job_id:
|
||||
description:
|
||||
- ID of the job to monitor.
|
||||
required: True
|
||||
type: int
|
||||
interval:
|
||||
description:
|
||||
- The interval in sections, to request an update from Tower.
|
||||
- For backwards compatibility if unset this will be set to the average of min and max intervals
|
||||
required: False
|
||||
default: 1
|
||||
type: float
|
||||
min_interval:
|
||||
description:
|
||||
- Minimum interval in seconds, to request an update from Tower.
|
||||
- deprecated, use interval instead
|
||||
type: float
|
||||
max_interval:
|
||||
description:
|
||||
- Maximum interval in seconds, to request an update from Tower.
|
||||
- deprecated, use interval instead
|
||||
type: float
|
||||
timeout:
|
||||
description:
|
||||
- Maximum time in seconds to wait for a job to finish.
|
||||
type: int
|
||||
job_type:
|
||||
description:
|
||||
- Job type to wait for
|
||||
choices: ['project_updates', 'jobs', 'inventory_updates', 'workflow_jobs']
|
||||
default: 'jobs'
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Launch a job
|
||||
tower_job_launch:
|
||||
job_template: "My Job Template"
|
||||
register: job
|
||||
|
||||
- name: Wait for job max 120s
|
||||
tower_job_wait:
|
||||
job_id: "{{ job.id }}"
|
||||
timeout: 120
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
id:
|
||||
description: job id that is being waited on
|
||||
returned: success
|
||||
type: int
|
||||
sample: 99
|
||||
elapsed:
|
||||
description: total time in seconds the job took to run
|
||||
returned: success
|
||||
type: float
|
||||
sample: 10.879
|
||||
started:
|
||||
description: timestamp of when the job started running
|
||||
returned: success
|
||||
type: str
|
||||
sample: "2017-03-01T17:03:53.200234Z"
|
||||
finished:
|
||||
description: timestamp of when the job finished running
|
||||
returned: success
|
||||
type: str
|
||||
sample: "2017-03-01T17:04:04.078782Z"
|
||||
status:
|
||||
description: current status of job
|
||||
returned: success
|
||||
type: str
|
||||
sample: successful
|
||||
'''
|
||||
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
job_id=dict(type='int', required=True),
|
||||
job_type=dict(choices=['project_updates', 'jobs', 'inventory_updates', 'workflow_jobs'], default='jobs'),
|
||||
timeout=dict(type='int'),
|
||||
min_interval=dict(type='float'),
|
||||
max_interval=dict(type='float'),
|
||||
interval=dict(type='float', default=1),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
job_id = module.params.get('job_id')
|
||||
job_type = module.params.get('job_type')
|
||||
timeout = module.params.get('timeout')
|
||||
min_interval = module.params.get('min_interval')
|
||||
max_interval = module.params.get('max_interval')
|
||||
interval = module.params.get('interval')
|
||||
|
||||
if min_interval is not None or max_interval is not None:
|
||||
# We can't tell if we got the default or if someone actually set this to 1.
|
||||
# For now if we find 1 and had a min or max then we will do the average logic.
|
||||
if interval == 1:
|
||||
if not min_interval:
|
||||
min_interval = 1
|
||||
if not max_interval:
|
||||
max_interval = 30
|
||||
interval = abs((min_interval + max_interval) / 2)
|
||||
module.deprecate(
|
||||
msg="Min and max interval have been deprecated, please use interval instead; interval will be set to {0}".format(interval),
|
||||
version="ansible.tower:4.0.0"
|
||||
)
|
||||
|
||||
# Attempt to look up job based on the provided id
|
||||
job = module.get_one(job_type, **{
|
||||
'data': {
|
||||
'id': job_id,
|
||||
}
|
||||
})
|
||||
|
||||
if job is None:
|
||||
module.fail_json(msg='Unable to wait on ' + job_type.rstrip("s") + ' {0}; that ID does not exist in Tower.'.format(job_id))
|
||||
|
||||
# Invoke wait function
|
||||
result = module.wait_on_url(
|
||||
url=job['url'],
|
||||
object_name=job_id,
|
||||
object_type='legacy_job_wait',
|
||||
timeout=timeout, interval=interval
|
||||
)
|
||||
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_label
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: create, update, or destroy Ansible Tower labels.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower labels. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
- Note, labels can only be created via the Tower API, they can not be deleted.
|
||||
Once they are fully disassociated the API will clean them up on its own.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name of this label.
|
||||
required: True
|
||||
type: str
|
||||
new_name:
|
||||
description:
|
||||
- Setting this option will change the existing name (looked up via the name field).
|
||||
type: str
|
||||
organization:
|
||||
description:
|
||||
- Organization this label belongs to.
|
||||
required: True
|
||||
type: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
default: "present"
|
||||
choices: ["present"]
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Add label to tower organization
|
||||
tower_label:
|
||||
name: Custom Label
|
||||
organization: My Organization
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
organization=dict(required=True),
|
||||
state=dict(choices=['present'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get("new_name")
|
||||
organization = module.params.get('organization')
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
organization_id = None
|
||||
if organization:
|
||||
organization_id = module.resolve_name_to_id('organizations', organization)
|
||||
|
||||
# Attempt to look up an existing item based on the provided data
|
||||
existing_item = module.get_one('labels', name_or_id=name, **{
|
||||
'data': {
|
||||
'organization': organization_id,
|
||||
}
|
||||
})
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
new_fields = {}
|
||||
new_fields['name'] = new_name if new_name else (module.get_item_name(existing_item) if existing_item else name)
|
||||
if organization:
|
||||
new_fields['organization'] = organization_id
|
||||
|
||||
module.create_or_update_if_needed(
|
||||
existing_item, new_fields,
|
||||
endpoint='labels', item_type='label',
|
||||
associations={
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2019, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_license
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
short_description: Set the license for Ansible Tower
|
||||
description:
|
||||
- Get or Set Ansible Tower license. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
manifest:
|
||||
description:
|
||||
- file path to a Red Hat subscription manifest (a .zip file)
|
||||
required: True
|
||||
type: str
|
||||
eula_accepted:
|
||||
description:
|
||||
- Whether or not the EULA is accepted.
|
||||
required: True
|
||||
type: bool
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
RETURN = ''' # '''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Set the license using a file
|
||||
tower_license:
|
||||
manifest: "/tmp/my_manifest.zip"
|
||||
eula_accepted: True
|
||||
'''
|
||||
|
||||
import base64
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
module = TowerAPIModule(
|
||||
argument_spec=dict(
|
||||
manifest=dict(type='str', required=True),
|
||||
eula_accepted=dict(type='bool', required=True),
|
||||
),
|
||||
)
|
||||
|
||||
json_output = {'changed': True}
|
||||
|
||||
if not module.params.get('eula_accepted'):
|
||||
module.fail_json(msg='You must accept the EULA by passing in the param eula_accepted as True')
|
||||
|
||||
try:
|
||||
manifest = base64.b64encode(
|
||||
open(module.params.get('manifest'), 'rb').read()
|
||||
)
|
||||
except OSError as e:
|
||||
module.fail_json(msg=str(e))
|
||||
|
||||
# Deal with check mode
|
||||
if module.check_mode:
|
||||
module.exit_json(**json_output)
|
||||
|
||||
module.post_endpoint('config', data={
|
||||
'eula_accepted': True,
|
||||
'manifest': manifest.decode()
|
||||
})
|
||||
|
||||
module.exit_json(**json_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2020, Ansible by Red Hat, Inc
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_meta
|
||||
author: "Alan Rominger (@alancoding)"
|
||||
short_description: Returns metadata about the collection this module lives in.
|
||||
description:
|
||||
- Allows a user to find out what collection this module exists in.
|
||||
- This takes common module parameters, but does nothing with them.
|
||||
options: {}
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
RETURN = '''
|
||||
prefix:
|
||||
description: Collection namespace and name in the namespace.name format
|
||||
returned: success
|
||||
sample: awx.awx
|
||||
type: str
|
||||
name:
|
||||
description: Collection name
|
||||
returned: success
|
||||
sample: awx
|
||||
type: str
|
||||
namespace:
|
||||
description: Collection namespace
|
||||
returned: success
|
||||
sample: awx
|
||||
type: str
|
||||
version:
|
||||
description: Version of the collection
|
||||
returned: success
|
||||
sample: 0.0.1-devel
|
||||
type: str
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- tower_meta:
|
||||
register: result
|
||||
|
||||
- name: Show details about the collection
|
||||
debug: var=result
|
||||
|
||||
- name: Load the UI setting without hard-coding the collection name
|
||||
debug:
|
||||
msg: "{{ lookup(result.prefix + '.tower_api', 'settings/ui') }}"
|
||||
'''
|
||||
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
module = TowerAPIModule(argument_spec={})
|
||||
namespace = {
|
||||
'awx': 'awx',
|
||||
'tower': 'ansible'
|
||||
}.get(module._COLLECTION_TYPE, 'unknown')
|
||||
namespace_name = '{0}.{1}'.format(namespace, module._COLLECTION_TYPE)
|
||||
module.exit_json(
|
||||
prefix=namespace_name,
|
||||
name=module._COLLECTION_TYPE,
|
||||
namespace=namespace,
|
||||
version=module._COLLECTION_VERSION
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,426 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2018, Samuel Carpentier <samuelcarpentier0@gmail.ca>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_notification_template
|
||||
author: "Samuel Carpentier (@samcarpentier)"
|
||||
short_description: create, update, or destroy Ansible Tower notification.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower notifications. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- The name of the notification.
|
||||
type: str
|
||||
required: True
|
||||
new_name:
|
||||
description:
|
||||
- Setting this option will change the existing name (looked up via the name field.
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- The description of the notification.
|
||||
type: str
|
||||
organization:
|
||||
description:
|
||||
- The organization the notification belongs to.
|
||||
type: str
|
||||
notification_type:
|
||||
description:
|
||||
- The type of notification to be sent.
|
||||
choices:
|
||||
- 'email'
|
||||
- 'grafana'
|
||||
- 'irc'
|
||||
- 'mattermost'
|
||||
- 'pagerduty'
|
||||
- 'rocketchat'
|
||||
- 'slack'
|
||||
- 'twilio'
|
||||
- 'webhook'
|
||||
type: str
|
||||
notification_configuration:
|
||||
description:
|
||||
- The notification configuration file. Note providing this field would disable all notification-configuration-related fields.
|
||||
type: dict
|
||||
messages:
|
||||
description:
|
||||
- Optional custom messages for notification template.
|
||||
type: dict
|
||||
username:
|
||||
description:
|
||||
- The mail server username.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
sender:
|
||||
description:
|
||||
- The sender email address.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
recipients:
|
||||
description:
|
||||
- The recipients email addresses.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: list
|
||||
elements: str
|
||||
use_tls:
|
||||
description:
|
||||
- The TLS trigger.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: bool
|
||||
host:
|
||||
description:
|
||||
- The mail server host.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
use_ssl:
|
||||
description:
|
||||
- The SSL trigger.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: bool
|
||||
password:
|
||||
description:
|
||||
- The mail server password.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
port:
|
||||
description:
|
||||
- The mail server port.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: int
|
||||
channels:
|
||||
description:
|
||||
- The destination Slack channels.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: list
|
||||
elements: str
|
||||
token:
|
||||
description:
|
||||
- The access token.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
account_token:
|
||||
description:
|
||||
- The Twillio account token.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
from_number:
|
||||
description:
|
||||
- The source phone number.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
to_numbers:
|
||||
description:
|
||||
- The destination phone numbers.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: list
|
||||
elements: str
|
||||
account_sid:
|
||||
description:
|
||||
- The Twillio account SID.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
subdomain:
|
||||
description:
|
||||
- The PagerDuty subdomain.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
service_key:
|
||||
description:
|
||||
- The PagerDuty service/integration API key.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
client_name:
|
||||
description:
|
||||
- The PagerDuty client identifier.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
message_from:
|
||||
description:
|
||||
- The label to be shown with the notification.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
color:
|
||||
description:
|
||||
- The notification color.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
choices: ["yellow", "green", "red", "purple", "gray", "random"]
|
||||
type: str
|
||||
notify:
|
||||
description:
|
||||
- The notify channel trigger.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: bool
|
||||
url:
|
||||
description:
|
||||
- The target URL.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
headers:
|
||||
description:
|
||||
- The HTTP headers as JSON string.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: dict
|
||||
server:
|
||||
description:
|
||||
- The IRC server address.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
nickname:
|
||||
description:
|
||||
- The IRC nickname.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: str
|
||||
targets:
|
||||
description:
|
||||
- The destination channels or users.
|
||||
- This parameter has been deprecated, please use 'notification_configuration' instead.
|
||||
type: list
|
||||
elements: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
default: "present"
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Add Slack notification with custom messages
|
||||
tower_notification_template:
|
||||
name: slack notification
|
||||
organization: Default
|
||||
notification_type: slack
|
||||
notification_configuration:
|
||||
channels:
|
||||
- general
|
||||
token: cefda9e2be1f21d11cdd9452f5b7f97fda977f42
|
||||
messages:
|
||||
started:
|
||||
message: "{{ '{{ job_friendly_name }}{{ job.id }} started' }}"
|
||||
success:
|
||||
message: "{{ '{{ job_friendly_name }} completed in {{ job.elapsed }} seconds' }}"
|
||||
error:
|
||||
message: "{{ '{{ job_friendly_name }} FAILED! Please look at {{ job.url }}' }}"
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Add webhook notification
|
||||
tower_notification_template:
|
||||
name: webhook notification
|
||||
notification_type: webhook
|
||||
notification_configuration:
|
||||
url: http://www.example.com/hook
|
||||
headers:
|
||||
X-Custom-Header: value123
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Add email notification
|
||||
tower_notification_template:
|
||||
name: email notification
|
||||
notification_type: email
|
||||
notification_configuration:
|
||||
username: user
|
||||
password: s3cr3t
|
||||
sender: tower@example.com
|
||||
recipients:
|
||||
- user1@example.com
|
||||
host: smtp.example.com
|
||||
port: 25
|
||||
use_tls: no
|
||||
use_ssl: no
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Add twilio notification
|
||||
tower_notification_template:
|
||||
name: twilio notification
|
||||
notification_type: twilio
|
||||
notification_configuration:
|
||||
account_token: a_token
|
||||
account_sid: a_sid
|
||||
from_number: '+15551112222'
|
||||
to_numbers:
|
||||
- '+15553334444'
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Add PagerDuty notification
|
||||
tower_notification_template:
|
||||
name: pagerduty notification
|
||||
notification_type: pagerduty
|
||||
notification_configuration:
|
||||
token: a_token
|
||||
subdomain: sub
|
||||
client_name: client
|
||||
service_key: a_key
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Add IRC notification
|
||||
tower_notification_template:
|
||||
name: irc notification
|
||||
notification_type: irc
|
||||
notification_configuration:
|
||||
nickname: tower
|
||||
password: s3cr3t
|
||||
targets:
|
||||
- user1
|
||||
port: 8080
|
||||
server: irc.example.com
|
||||
use_ssl: no
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Delete notification
|
||||
tower_notification_template:
|
||||
name: old notification
|
||||
state: absent
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
'''
|
||||
|
||||
|
||||
RETURN = ''' # '''
|
||||
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
OLD_INPUT_NAMES = (
|
||||
'username', 'sender', 'recipients', 'use_tls',
|
||||
'host', 'use_ssl', 'password', 'port',
|
||||
'channels', 'token', 'account_token', 'from_number',
|
||||
'to_numbers', 'account_sid', 'subdomain', 'service_key',
|
||||
'client_name', 'message_from', 'color',
|
||||
'notify', 'url', 'headers', 'server',
|
||||
'nickname', 'targets',
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
description=dict(),
|
||||
organization=dict(),
|
||||
notification_type=dict(choices=[
|
||||
'email', 'grafana', 'irc', 'mattermost',
|
||||
'pagerduty', 'rocketchat', 'slack', 'twilio', 'webhook'
|
||||
]),
|
||||
notification_configuration=dict(type='dict'),
|
||||
messages=dict(type='dict'),
|
||||
username=dict(),
|
||||
sender=dict(),
|
||||
recipients=dict(type='list', elements='str'),
|
||||
use_tls=dict(type='bool'),
|
||||
host=dict(),
|
||||
use_ssl=dict(type='bool'),
|
||||
password=dict(no_log=True),
|
||||
port=dict(type='int'),
|
||||
channels=dict(type='list', elements='str'),
|
||||
token=dict(no_log=True),
|
||||
account_token=dict(no_log=True),
|
||||
from_number=dict(),
|
||||
to_numbers=dict(type='list', elements='str'),
|
||||
account_sid=dict(),
|
||||
subdomain=dict(),
|
||||
service_key=dict(no_log=True),
|
||||
client_name=dict(),
|
||||
message_from=dict(),
|
||||
color=dict(choices=['yellow', 'green', 'red', 'purple', 'gray', 'random']),
|
||||
notify=dict(type='bool'),
|
||||
url=dict(),
|
||||
headers=dict(type='dict'),
|
||||
server=dict(),
|
||||
nickname=dict(),
|
||||
targets=dict(type='list', elements='str'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get('new_name')
|
||||
description = module.params.get('description')
|
||||
organization = module.params.get('organization')
|
||||
notification_type = module.params.get('notification_type')
|
||||
notification_configuration = module.params.get('notification_configuration')
|
||||
messages = module.params.get('messages')
|
||||
state = module.params.get('state')
|
||||
|
||||
# Deprecation warnings for all other params
|
||||
for legacy_input in OLD_INPUT_NAMES:
|
||||
if module.params.get(legacy_input) is not None:
|
||||
module.deprecate(
|
||||
msg='{0} parameter has been deprecated, please use notification_configuration instead'.format(legacy_input),
|
||||
version="ansible.tower:4.0.0")
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
organization_id = None
|
||||
if organization:
|
||||
organization_id = module.resolve_name_to_id('organizations', organization)
|
||||
|
||||
# Attempt to look up an existing item based on the provided data
|
||||
existing_item = module.get_one('notification_templates', name_or_id=name, **{
|
||||
'data': {
|
||||
'organization': organization_id,
|
||||
}
|
||||
})
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(existing_item)
|
||||
|
||||
# Create notification_configuration from legacy inputs
|
||||
final_notification_configuration = {}
|
||||
for legacy_input in OLD_INPUT_NAMES:
|
||||
if module.params.get(legacy_input) is not None:
|
||||
final_notification_configuration[legacy_input] = module.params.get(legacy_input)
|
||||
# Give anything in notification_configuration prescedence over the individual inputs
|
||||
if notification_configuration is not None:
|
||||
final_notification_configuration.update(notification_configuration)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
new_fields = {}
|
||||
if final_notification_configuration:
|
||||
new_fields['notification_configuration'] = final_notification_configuration
|
||||
new_fields['name'] = new_name if new_name else (module.get_item_name(existing_item) if existing_item else name)
|
||||
if description is not None:
|
||||
new_fields['description'] = description
|
||||
if organization is not None:
|
||||
new_fields['organization'] = organization_id
|
||||
if notification_type is not None:
|
||||
new_fields['notification_type'] = notification_type
|
||||
if messages is not None:
|
||||
new_fields['messages'] = messages
|
||||
|
||||
# If the state was present and we can let the module build or update the existing item, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
existing_item, new_fields,
|
||||
endpoint='notification_templates', item_type='notification_template',
|
||||
associations={
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,190 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_organization
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: create, update, or destroy Ansible Tower organizations
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower organizations. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name to use for the organization.
|
||||
required: True
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- The description to use for the organization.
|
||||
type: str
|
||||
custom_virtualenv:
|
||||
description:
|
||||
- Local absolute file path containing a custom Python virtualenv to use.
|
||||
type: str
|
||||
default: ''
|
||||
max_hosts:
|
||||
description:
|
||||
- The max hosts allowed in this organizations
|
||||
default: "0"
|
||||
type: int
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
default: "present"
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
notification_templates_started:
|
||||
description:
|
||||
- list of notifications to send on start
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_success:
|
||||
description:
|
||||
- list of notifications to send on success
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_error:
|
||||
description:
|
||||
- list of notifications to send on error
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_approvals:
|
||||
description:
|
||||
- list of notifications to send on start
|
||||
type: list
|
||||
elements: str
|
||||
galaxy_credentials:
|
||||
description:
|
||||
- list of Ansible Galaxy credentials to associate to the organization
|
||||
type: list
|
||||
elements: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create tower organization
|
||||
tower_organization:
|
||||
name: "Foo"
|
||||
description: "Foo bar organization"
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Create tower organization using 'foo-venv' as default Python virtualenv
|
||||
tower_organization:
|
||||
name: "Foo"
|
||||
description: "Foo bar organization using foo-venv"
|
||||
custom_virtualenv: "/var/lib/awx/venv/foo-venv/"
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Create tower organization that pulls content from galaxy.ansible.com
|
||||
tower_organization:
|
||||
name: "Foo"
|
||||
state: present
|
||||
galaxy_credentials:
|
||||
- Ansible Galaxy
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
description=dict(),
|
||||
custom_virtualenv=dict(),
|
||||
max_hosts=dict(type='int', default="0"),
|
||||
notification_templates_started=dict(type="list", elements='str'),
|
||||
notification_templates_success=dict(type="list", elements='str'),
|
||||
notification_templates_error=dict(type="list", elements='str'),
|
||||
notification_templates_approvals=dict(type="list", elements='str'),
|
||||
galaxy_credentials=dict(type="list", elements='str'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
description = module.params.get('description')
|
||||
custom_virtualenv = module.params.get('custom_virtualenv')
|
||||
max_hosts = module.params.get('max_hosts')
|
||||
# instance_group_names = module.params.get('instance_groups')
|
||||
state = module.params.get('state')
|
||||
|
||||
# Attempt to look up organization based on the provided name
|
||||
organization = module.get_one('organizations', name_or_id=name)
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(organization)
|
||||
# Attempt to look up associated field items the user specified.
|
||||
association_fields = {}
|
||||
|
||||
notifications_start = module.params.get('notification_templates_started')
|
||||
if notifications_start is not None:
|
||||
association_fields['notification_templates_started'] = []
|
||||
for item in notifications_start:
|
||||
association_fields['notification_templates_started'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_success = module.params.get('notification_templates_success')
|
||||
if notifications_success is not None:
|
||||
association_fields['notification_templates_success'] = []
|
||||
for item in notifications_success:
|
||||
association_fields['notification_templates_success'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_error = module.params.get('notification_templates_error')
|
||||
if notifications_error is not None:
|
||||
association_fields['notification_templates_error'] = []
|
||||
for item in notifications_error:
|
||||
association_fields['notification_templates_error'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_approval = module.params.get('notification_templates_approvals')
|
||||
if notifications_approval is not None:
|
||||
association_fields['notification_templates_approvals'] = []
|
||||
for item in notifications_approval:
|
||||
association_fields['notification_templates_approvals'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
galaxy_credentials = module.params.get('galaxy_credentials')
|
||||
if galaxy_credentials is not None:
|
||||
association_fields['galaxy_credentials'] = []
|
||||
for item in galaxy_credentials:
|
||||
association_fields['galaxy_credentials'].append(module.resolve_name_to_id('credentials', item))
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
org_fields = {'name': module.get_item_name(organization) if organization else name}
|
||||
if description is not None:
|
||||
org_fields['description'] = description
|
||||
if custom_virtualenv is not None:
|
||||
org_fields['custom_virtualenv'] = custom_virtualenv
|
||||
if max_hosts is not None:
|
||||
org_fields['max_hosts'] = max_hosts
|
||||
|
||||
# If the state was present and we can let the module build or update the existing organization, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
organization, org_fields,
|
||||
endpoint='organizations', item_type='organization',
|
||||
associations=association_fields,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,360 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_project
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: create, update, or destroy Ansible Tower projects
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower projects. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name to use for the project.
|
||||
required: True
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- Description to use for the project.
|
||||
type: str
|
||||
scm_type:
|
||||
description:
|
||||
- Type of SCM resource.
|
||||
choices: ["manual", "git", "svn", "insights"]
|
||||
default: "manual"
|
||||
type: str
|
||||
scm_url:
|
||||
description:
|
||||
- URL of SCM resource.
|
||||
type: str
|
||||
local_path:
|
||||
description:
|
||||
- The server playbook directory for manual projects.
|
||||
type: str
|
||||
scm_branch:
|
||||
description:
|
||||
- The branch to use for the SCM resource.
|
||||
type: str
|
||||
default: ''
|
||||
scm_refspec:
|
||||
description:
|
||||
- The refspec to use for the SCM resource.
|
||||
type: str
|
||||
default: ''
|
||||
credential:
|
||||
description:
|
||||
- Name of the credential to use with this SCM resource.
|
||||
type: str
|
||||
aliases:
|
||||
- scm_credential
|
||||
scm_clean:
|
||||
description:
|
||||
- Remove local modifications before updating.
|
||||
type: bool
|
||||
default: 'no'
|
||||
scm_delete_on_update:
|
||||
description:
|
||||
- Remove the repository completely before updating.
|
||||
type: bool
|
||||
default: 'no'
|
||||
scm_update_on_launch:
|
||||
description:
|
||||
- Before an update to the local repository before launching a job with this project.
|
||||
type: bool
|
||||
default: 'no'
|
||||
scm_update_cache_timeout:
|
||||
description:
|
||||
- Cache Timeout to cache prior project syncs for a certain number of seconds.
|
||||
Only valid if scm_update_on_launch is to True, otherwise ignored.
|
||||
type: int
|
||||
default: 0
|
||||
allow_override:
|
||||
description:
|
||||
- Allow changing the SCM branch or revision in a job template that uses this project.
|
||||
type: bool
|
||||
aliases:
|
||||
- scm_allow_override
|
||||
timeout:
|
||||
description:
|
||||
- The amount of time (in seconds) to run before the SCM Update is canceled. A value of 0 means no timeout.
|
||||
- If waiting for the project to update this will abort after this
|
||||
amount of seconds
|
||||
default: 0
|
||||
type: int
|
||||
aliases:
|
||||
- job_timeout
|
||||
custom_virtualenv:
|
||||
description:
|
||||
- Local absolute file path containing a custom Python virtualenv to use
|
||||
type: str
|
||||
default: ''
|
||||
organization:
|
||||
description:
|
||||
- Name of organization for project.
|
||||
type: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
default: "present"
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
wait:
|
||||
description:
|
||||
- Provides option (True by default) to wait for completed project sync
|
||||
before returning
|
||||
- Can assure playbook files are populated so that job templates that rely
|
||||
on the project may be successfully created
|
||||
type: bool
|
||||
default: True
|
||||
notification_templates_started:
|
||||
description:
|
||||
- list of notifications to send on start
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_success:
|
||||
description:
|
||||
- list of notifications to send on success
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_error:
|
||||
description:
|
||||
- list of notifications to send on error
|
||||
type: list
|
||||
elements: str
|
||||
update_project:
|
||||
description:
|
||||
- Force project to update after changes.
|
||||
- Used in conjunction with wait, interval, and timeout.
|
||||
default: False
|
||||
type: bool
|
||||
interval:
|
||||
description:
|
||||
- The interval to request an update from Tower.
|
||||
- Requires wait.
|
||||
required: False
|
||||
default: 1
|
||||
type: float
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Add tower project
|
||||
tower_project:
|
||||
name: "Foo"
|
||||
description: "Foo bar project"
|
||||
organization: "test"
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Add Tower Project with cache timeout and custom virtualenv
|
||||
tower_project:
|
||||
name: "Foo"
|
||||
description: "Foo bar project"
|
||||
organization: "test"
|
||||
scm_update_on_launch: True
|
||||
scm_update_cache_timeout: 60
|
||||
custom_virtualenv: "/var/lib/awx/var/lib/awx/venv/ansible-2.2"
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
'''
|
||||
|
||||
import time
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def wait_for_project_update(module, last_request):
|
||||
# The current running job for the update is in last_request['summary_fields']['current_update']['id']
|
||||
|
||||
# Get parameters that were not passed in
|
||||
update_project = module.params.get('update_project')
|
||||
wait = module.params.get('wait')
|
||||
timeout = module.params.get('timeout')
|
||||
interval = module.params.get('interval')
|
||||
|
||||
if 'current_update' in last_request['summary_fields']:
|
||||
running = True
|
||||
while running:
|
||||
result = module.get_endpoint('/project_updates/{0}/'.format(last_request['summary_fields']['current_update']['id']))['json']
|
||||
|
||||
if module.is_job_done(result['status']):
|
||||
time.sleep(1)
|
||||
running = False
|
||||
|
||||
if result['status'] != 'successful':
|
||||
module.fail_json(msg="Project update failed")
|
||||
elif update_project:
|
||||
result = module.post_endpoint(last_request['related']['update'])
|
||||
|
||||
if result['status_code'] != 202:
|
||||
module.fail_json(msg="Failed to update project, see response for details", response=result)
|
||||
|
||||
if not wait:
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
# Grab our start time to compare against for the timeout
|
||||
start = time.time()
|
||||
|
||||
# Invoke wait function
|
||||
module.wait_on_url(
|
||||
url=result['json']['url'],
|
||||
object_name=module.get_item_name(last_request),
|
||||
object_type='Project Update',
|
||||
timeout=timeout, interval=interval
|
||||
)
|
||||
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
description=dict(),
|
||||
scm_type=dict(choices=['manual', 'git', 'svn', 'insights'], default='manual'),
|
||||
scm_url=dict(),
|
||||
local_path=dict(),
|
||||
scm_branch=dict(),
|
||||
scm_refspec=dict(),
|
||||
credential=dict(aliases=['scm_credential']),
|
||||
scm_clean=dict(type='bool', default=False),
|
||||
scm_delete_on_update=dict(type='bool', default=False),
|
||||
scm_update_on_launch=dict(type='bool', default=False),
|
||||
scm_update_cache_timeout=dict(type='int', default=0),
|
||||
allow_override=dict(type='bool', aliases=['scm_allow_override']),
|
||||
timeout=dict(type='int', default=0, aliases=['job_timeout']),
|
||||
custom_virtualenv=dict(),
|
||||
organization=dict(),
|
||||
notification_templates_started=dict(type="list", elements='str'),
|
||||
notification_templates_success=dict(type="list", elements='str'),
|
||||
notification_templates_error=dict(type="list", elements='str'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
wait=dict(type='bool', default=True),
|
||||
update_project=dict(default=False, type='bool'),
|
||||
interval=dict(default=1.0, type='float'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
description = module.params.get('description')
|
||||
scm_type = module.params.get('scm_type')
|
||||
if scm_type == "manual":
|
||||
scm_type = ""
|
||||
scm_url = module.params.get('scm_url')
|
||||
local_path = module.params.get('local_path')
|
||||
scm_branch = module.params.get('scm_branch')
|
||||
scm_refspec = module.params.get('scm_refspec')
|
||||
credential = module.params.get('credential')
|
||||
scm_clean = module.params.get('scm_clean')
|
||||
scm_delete_on_update = module.params.get('scm_delete_on_update')
|
||||
scm_update_on_launch = module.params.get('scm_update_on_launch')
|
||||
scm_update_cache_timeout = module.params.get('scm_update_cache_timeout')
|
||||
allow_override = module.params.get('allow_override')
|
||||
timeout = module.params.get('timeout')
|
||||
custom_virtualenv = module.params.get('custom_virtualenv')
|
||||
organization = module.params.get('organization')
|
||||
state = module.params.get('state')
|
||||
wait = module.params.get('wait')
|
||||
update_project = module.params.get('update_project')
|
||||
interval = module.params.get('interval')
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
lookup_data = {}
|
||||
org_id = None
|
||||
if organization:
|
||||
org_id = module.resolve_name_to_id('organizations', organization)
|
||||
lookup_data['organization'] = org_id
|
||||
|
||||
# Attempt to look up project based on the provided name and org ID
|
||||
project = module.get_one('projects', name_or_id=name, data=lookup_data)
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(project)
|
||||
|
||||
if credential is not None:
|
||||
credential = module.resolve_name_to_id('credentials', credential)
|
||||
|
||||
# Attempt to look up associated field items the user specified.
|
||||
association_fields = {}
|
||||
|
||||
notifications_start = module.params.get('notification_templates_started')
|
||||
if notifications_start is not None:
|
||||
association_fields['notification_templates_started'] = []
|
||||
for item in notifications_start:
|
||||
association_fields['notification_templates_started'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_success = module.params.get('notification_templates_success')
|
||||
if notifications_success is not None:
|
||||
association_fields['notification_templates_success'] = []
|
||||
for item in notifications_success:
|
||||
association_fields['notification_templates_success'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_error = module.params.get('notification_templates_error')
|
||||
if notifications_error is not None:
|
||||
association_fields['notification_templates_error'] = []
|
||||
for item in notifications_error:
|
||||
association_fields['notification_templates_error'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
project_fields = {
|
||||
'name': module.get_item_name(project) if project else name,
|
||||
'scm_type': scm_type,
|
||||
'scm_url': scm_url,
|
||||
'scm_branch': scm_branch,
|
||||
'scm_refspec': scm_refspec,
|
||||
'scm_clean': scm_clean,
|
||||
'scm_delete_on_update': scm_delete_on_update,
|
||||
'timeout': timeout,
|
||||
'organization': org_id,
|
||||
'scm_update_on_launch': scm_update_on_launch,
|
||||
'scm_update_cache_timeout': scm_update_cache_timeout,
|
||||
'custom_virtualenv': custom_virtualenv,
|
||||
}
|
||||
if description is not None:
|
||||
project_fields['description'] = description
|
||||
if credential is not None:
|
||||
project_fields['credential'] = credential
|
||||
if allow_override is not None:
|
||||
project_fields['allow_override'] = allow_override
|
||||
if scm_type == '':
|
||||
project_fields['local_path'] = local_path
|
||||
|
||||
if scm_update_cache_timeout != 0 and scm_update_on_launch is not True:
|
||||
module.warn('scm_update_cache_timeout will be ignored since scm_update_on_launch was not set to true')
|
||||
|
||||
# If we are doing a not manual project, register our on_change method
|
||||
# An on_change function, if registered, will fire after an post_endpoint or update_if_needed completes successfully
|
||||
on_change = None
|
||||
if wait and scm_type != '' or update_project and scm_type != '':
|
||||
on_change = wait_for_project_update
|
||||
|
||||
# If the state was present and we can let the module build or update the existing project, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
project, project_fields,
|
||||
endpoint='projects', item_type='project',
|
||||
associations=association_fields,
|
||||
on_create=on_change, on_update=on_change
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.0',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_project_update
|
||||
author: "Sean Sullivan (@sean-m-sullivan)"
|
||||
short_description: Update a Project in Ansible Tower
|
||||
description:
|
||||
- Update a Ansible Tower Project. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- The name or id of the project to update.
|
||||
required: True
|
||||
type: str
|
||||
aliases:
|
||||
- project
|
||||
organization:
|
||||
description:
|
||||
- Organization the project exists in.
|
||||
- Used to help lookup the object, cannot be modified using this module.
|
||||
- If not provided, will lookup by name only, which does not work with duplicates.
|
||||
type: str
|
||||
wait:
|
||||
description:
|
||||
- Wait for the project to update.
|
||||
default: True
|
||||
type: bool
|
||||
interval:
|
||||
description:
|
||||
- The interval to request an update from Tower.
|
||||
required: False
|
||||
default: 1
|
||||
type: float
|
||||
timeout:
|
||||
description:
|
||||
- If waiting for the project to update this will abort after this
|
||||
amount of seconds
|
||||
type: int
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
id:
|
||||
description: project id of the updated project
|
||||
returned: success
|
||||
type: int
|
||||
sample: 86
|
||||
status:
|
||||
description: status of the updated project
|
||||
returned: success
|
||||
type: str
|
||||
sample: pending
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Launch a project with a timeout of 10 seconds
|
||||
tower_project_update:
|
||||
project: "Networking Project"
|
||||
timeout: 10
|
||||
|
||||
- name: Launch a Project with extra_vars without waiting
|
||||
tower_project_update:
|
||||
project: "Networking Project"
|
||||
wait: False
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
import json
|
||||
import time
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True, aliases=['project']),
|
||||
organization=dict(),
|
||||
wait=dict(default=True, type='bool'),
|
||||
interval=dict(default=1.0, type='float'),
|
||||
timeout=dict(default=None, type='int'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
organization = module.params.get('organization')
|
||||
wait = module.params.get('wait')
|
||||
interval = module.params.get('interval')
|
||||
timeout = module.params.get('timeout')
|
||||
|
||||
# Attempt to look up project based on the provided name or id
|
||||
lookup_data = {}
|
||||
if organization:
|
||||
lookup_data['organization'] = module.resolve_name_to_id('organizations', organization)
|
||||
project = module.get_one('projects', name_or_id=name, data=lookup_data)
|
||||
if project is None:
|
||||
module.fail_json(msg="Unable to find project")
|
||||
|
||||
# Update the project
|
||||
result = module.post_endpoint(project['related']['update'])
|
||||
|
||||
if result['status_code'] != 202:
|
||||
module.fail_json(msg="Failed to update project, see response for details", response=result)
|
||||
|
||||
module.json_output['changed'] = True
|
||||
module.json_output['id'] = result['json']['id']
|
||||
module.json_output['status'] = result['json']['status']
|
||||
|
||||
if not wait:
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
# Grab our start time to compare against for the timeout
|
||||
start = time.time()
|
||||
|
||||
# Invoke wait function
|
||||
module.wait_on_url(
|
||||
url=result['json']['url'],
|
||||
object_name=module.get_item_name(project),
|
||||
object_type='Project Update',
|
||||
timeout=timeout, interval=interval
|
||||
)
|
||||
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['deprecated'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_receive
|
||||
deprecated:
|
||||
removed_in: "14.0.0"
|
||||
why: Deprecated in favor of upcoming C(_export) module.
|
||||
alternative: Once published, use M(tower_export) instead.
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
short_description: Receive assets from Ansible Tower.
|
||||
description:
|
||||
- Receive assets from Ansible Tower. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
all:
|
||||
description:
|
||||
- Export all assets
|
||||
type: bool
|
||||
default: 'False'
|
||||
organization:
|
||||
description:
|
||||
- List of organization names to export
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
user:
|
||||
description:
|
||||
- List of user names to export
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
team:
|
||||
description:
|
||||
- List of team names to export
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
credential_type:
|
||||
description:
|
||||
- List of credential type names to export
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
credential:
|
||||
description:
|
||||
- List of credential names to export
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
notification_template:
|
||||
description:
|
||||
- List of notification template names to export
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
inventory_script:
|
||||
description:
|
||||
- List of inventory script names to export
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
inventory:
|
||||
description:
|
||||
- List of inventory names to export
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
project:
|
||||
description:
|
||||
- List of project names to export
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
job_template:
|
||||
description:
|
||||
- List of job template names to export
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
workflow:
|
||||
description:
|
||||
- List of workflow names to export
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
|
||||
requirements:
|
||||
- "ansible-tower-cli >= 3.3.0"
|
||||
|
||||
notes:
|
||||
- Specifying a name of "all" for any asset type will export all items of that asset type.
|
||||
|
||||
extends_documentation_fragment: awx.awx.auth_legacy
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Export all tower assets
|
||||
tower_receive:
|
||||
all: True
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Export all inventories
|
||||
tower_receive:
|
||||
inventory:
|
||||
- all
|
||||
|
||||
- name: Export a job template named "My Template" and all Credentials
|
||||
tower_receive:
|
||||
job_template:
|
||||
- "My Template"
|
||||
credential:
|
||||
- all
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
assets:
|
||||
description: The exported assets
|
||||
returned: success
|
||||
type: dict
|
||||
sample: [ {}, {} ]
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_legacy import TowerLegacyModule, tower_auth_config, HAS_TOWER_CLI
|
||||
|
||||
try:
|
||||
from tower_cli.cli.transfer.receive import Receiver
|
||||
from tower_cli.cli.transfer.common import SEND_ORDER
|
||||
from tower_cli.utils.exceptions import TowerCLIError
|
||||
|
||||
from tower_cli.conf import settings
|
||||
TOWER_CLI_HAS_EXPORT = True
|
||||
except ImportError:
|
||||
TOWER_CLI_HAS_EXPORT = False
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = dict(
|
||||
all=dict(type='bool', default=False),
|
||||
credential=dict(type='list', default=[], elements='str'),
|
||||
credential_type=dict(type='list', default=[], elements='str'),
|
||||
inventory=dict(type='list', default=[], elements='str'),
|
||||
inventory_script=dict(type='list', default=[], elements='str'),
|
||||
job_template=dict(type='list', default=[], elements='str'),
|
||||
notification_template=dict(type='list', default=[], elements='str'),
|
||||
organization=dict(type='list', default=[], elements='str'),
|
||||
project=dict(type='list', default=[], elements='str'),
|
||||
team=dict(type='list', default=[], elements='str'),
|
||||
user=dict(type='list', default=[], elements='str'),
|
||||
workflow=dict(type='list', default=[], elements='str'),
|
||||
)
|
||||
|
||||
module = TowerLegacyModule(argument_spec=argument_spec, supports_check_mode=False)
|
||||
|
||||
module.deprecate(msg="This module is deprecated and will be replaced by the AWX CLI export command.", version="awx.awx:14.0.0")
|
||||
|
||||
if not HAS_TOWER_CLI:
|
||||
module.fail_json(msg='ansible-tower-cli required for this module')
|
||||
|
||||
if not TOWER_CLI_HAS_EXPORT:
|
||||
module.fail_json(msg='ansible-tower-cli version does not support export')
|
||||
|
||||
export_all = module.params.get('all')
|
||||
assets_to_export = {}
|
||||
for asset_type in SEND_ORDER:
|
||||
assets_to_export[asset_type] = module.params.get(asset_type)
|
||||
|
||||
result = dict(
|
||||
assets=None,
|
||||
changed=False,
|
||||
message='',
|
||||
)
|
||||
|
||||
tower_auth = tower_auth_config(module)
|
||||
with settings.runtime_values(**tower_auth):
|
||||
try:
|
||||
receiver = Receiver()
|
||||
result['assets'] = receiver.export_assets(all=export_all, asset_input=assets_to_export)
|
||||
module.exit_json(**result)
|
||||
except TowerCLIError as e:
|
||||
result['message'] = e.message
|
||||
module.fail_json(msg='Receive Failed', **result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,291 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_role
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: grant or revoke an Ansible Tower role.
|
||||
description:
|
||||
- Roles are used for access control, this module is for managing user access to server resources.
|
||||
- Grant or revoke Ansible Tower roles to users. See U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
user:
|
||||
description:
|
||||
- User that receives the permissions specified by the role.
|
||||
type: str
|
||||
team:
|
||||
description:
|
||||
- Team that receives the permissions specified by the role.
|
||||
type: str
|
||||
role:
|
||||
description:
|
||||
- The role type to grant/revoke.
|
||||
required: True
|
||||
choices: ["admin", "read", "member", "execute", "adhoc", "update", "use", "approval", "auditor", "project_admin", "inventory_admin", "credential_admin",
|
||||
"workflow_admin", "notification_admin", "job_template_admin"]
|
||||
type: str
|
||||
target_team:
|
||||
description:
|
||||
- Team that the role acts on.
|
||||
- For example, make someone a member or an admin of a team.
|
||||
- Members of a team implicitly receive the permissions that the team has.
|
||||
- Deprecated, use 'target_teams'.
|
||||
type: str
|
||||
target_teams:
|
||||
description:
|
||||
- Team that the role acts on.
|
||||
- For example, make someone a member or an admin of a team.
|
||||
- Members of a team implicitly receive the permissions that the team has.
|
||||
type: list
|
||||
elements: str
|
||||
inventory:
|
||||
description:
|
||||
- Inventory the role acts on.
|
||||
- Deprecated, use 'inventories'.
|
||||
type: str
|
||||
inventories:
|
||||
description:
|
||||
- Inventory the role acts on.
|
||||
type: list
|
||||
elements: str
|
||||
job_template:
|
||||
description:
|
||||
- The job template the role acts on.
|
||||
- Deprecated, use 'job_templates'.
|
||||
type: str
|
||||
job_templates:
|
||||
description:
|
||||
- The job template the role acts on.
|
||||
type: list
|
||||
elements: str
|
||||
workflow:
|
||||
description:
|
||||
- The workflow job template the role acts on.
|
||||
- Deprecated, use 'workflows'.
|
||||
type: str
|
||||
workflows:
|
||||
description:
|
||||
- The workflow job template the role acts on.
|
||||
type: list
|
||||
elements: str
|
||||
credential:
|
||||
description:
|
||||
- Credential the role acts on.
|
||||
- Deprecated, use 'credentials'.
|
||||
type: str
|
||||
credentials:
|
||||
description:
|
||||
- Credential the role acts on.
|
||||
type: list
|
||||
elements: str
|
||||
organization:
|
||||
description:
|
||||
- Organization the role acts on.
|
||||
- Deprecated, use 'organizations'.
|
||||
type: str
|
||||
organizations:
|
||||
description:
|
||||
- Organization the role acts on.
|
||||
type: list
|
||||
elements: str
|
||||
lookup_organization:
|
||||
description:
|
||||
- Organization the inventories, job templates, projects, or workflows the items exists in.
|
||||
- Used to help lookup the object, for organization roles see organization.
|
||||
- If not provided, will lookup by name only, which does not work with duplicates.
|
||||
type: str
|
||||
project:
|
||||
description:
|
||||
- Project the role acts on.
|
||||
- Deprecated, use 'projects'.
|
||||
type: str
|
||||
projects:
|
||||
description:
|
||||
- Project the role acts on.
|
||||
type: list
|
||||
elements: str
|
||||
state:
|
||||
description:
|
||||
- Desired state.
|
||||
- State of present indicates the user should have the role.
|
||||
- State of absent indicates the user should have the role taken away, if they have it.
|
||||
default: "present"
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Add jdoe to the member role of My Team
|
||||
tower_role:
|
||||
user: jdoe
|
||||
target_team: "My Team"
|
||||
role: member
|
||||
state: present
|
||||
|
||||
- name: Add Joe to multiple job templates and a workflow
|
||||
tower_role:
|
||||
user: joe
|
||||
role: execute
|
||||
workflow: test-role-workflow
|
||||
job_templates:
|
||||
- jt1
|
||||
- jt2
|
||||
state: present
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
argument_spec = dict(
|
||||
user=dict(),
|
||||
team=dict(),
|
||||
role=dict(choices=["admin", "read", "member", "execute", "adhoc", "update", "use", "approval",
|
||||
"auditor", "project_admin", "inventory_admin", "credential_admin",
|
||||
"workflow_admin", "notification_admin", "job_template_admin"], required=True),
|
||||
target_team=dict(),
|
||||
target_teams=dict(type='list', elements='str'),
|
||||
inventory=dict(),
|
||||
inventories=dict(type='list', elements='str'),
|
||||
job_template=dict(),
|
||||
job_templates=dict(type='list', elements='str'),
|
||||
workflow=dict(),
|
||||
workflows=dict(type='list', elements='str'),
|
||||
credential=dict(),
|
||||
credentials=dict(type='list', elements='str'),
|
||||
organization=dict(),
|
||||
organizations=dict(type='list', elements='str'),
|
||||
lookup_organization=dict(),
|
||||
project=dict(),
|
||||
projects=dict(type='list', elements='str'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
role_type = module.params.pop('role')
|
||||
role_field = role_type + '_role'
|
||||
state = module.params.pop('state')
|
||||
|
||||
module.json_output['role'] = role_type
|
||||
|
||||
# Deal with legacy parameters
|
||||
resource_list_param_keys = {
|
||||
'credentials': 'credential',
|
||||
'inventories': 'inventory',
|
||||
'job_templates': 'job_template',
|
||||
'organizations': 'organization',
|
||||
'projects': 'project',
|
||||
'target_teams': 'target_team',
|
||||
'workflows': 'workflow'
|
||||
}
|
||||
# Singular parameters
|
||||
resource_param_keys = (
|
||||
'user', 'team', 'lookup_organization'
|
||||
)
|
||||
|
||||
resources = {}
|
||||
for resource_group in resource_list_param_keys:
|
||||
if module.params.get(resource_group) is not None:
|
||||
resources.setdefault(resource_group, []).extend(module.params.get(resource_group))
|
||||
if module.params.get(resource_list_param_keys[resource_group]) is not None:
|
||||
resources.setdefault(resource_group, []).append(module.params.get(resource_list_param_keys[resource_group]))
|
||||
for resource_group in resource_param_keys:
|
||||
if module.params.get(resource_group) is not None:
|
||||
resources[resource_group] = module.params.get(resource_group)
|
||||
# Change workflows and target_teams key to its endpoint name.
|
||||
if 'workflows' in resources:
|
||||
resources['workflow_job_templates'] = resources.pop('workflows')
|
||||
if 'target_teams' in resources:
|
||||
resources['teams'] = resources.pop('target_teams')
|
||||
|
||||
# Set lookup data to use
|
||||
lookup_data = {}
|
||||
if 'lookup_organization' in resources:
|
||||
lookup_data['organization'] = module.resolve_name_to_id('organizations', resources['lookup_organization'])
|
||||
resources.pop('lookup_organization')
|
||||
|
||||
# Lookup actor data
|
||||
# separate actors from resources
|
||||
actor_data = {}
|
||||
for key in ('user', 'team'):
|
||||
if key in resources:
|
||||
if key == 'user':
|
||||
lookup_data_populated = {}
|
||||
else:
|
||||
lookup_data_populated = lookup_data
|
||||
# Attempt to look up project based on the provided name or ID and lookup data
|
||||
actor_data[key] = module.get_one('{0}s'.format(key), name_or_id=resources[key], data=lookup_data_populated)
|
||||
resources.pop(key)
|
||||
|
||||
# Lookup Resources
|
||||
resource_data = {}
|
||||
for key in resources:
|
||||
for resource in resources[key]:
|
||||
# Attempt to look up project based on the provided name or ID and lookup data
|
||||
if key in resources:
|
||||
if key == 'organizations':
|
||||
lookup_data_populated = {}
|
||||
else:
|
||||
lookup_data_populated = lookup_data
|
||||
|
||||
resource_data.setdefault(key, []).append(module.get_one(key, name_or_id=resource, data=lookup_data_populated))
|
||||
|
||||
# build association agenda
|
||||
associations = {}
|
||||
for actor_type, actor in actor_data.items():
|
||||
for key in resource_data:
|
||||
for resource in resource_data[key]:
|
||||
resource_roles = resource['summary_fields']['object_roles']
|
||||
if role_field not in resource_roles:
|
||||
available_roles = ', '.join(list(resource_roles.keys()))
|
||||
module.fail_json(msg='Resource {0} has no role {1}, available roles: {2}'.format(
|
||||
resource['url'], role_field, available_roles
|
||||
), changed=False)
|
||||
role_data = resource_roles[role_field]
|
||||
endpoint = '/roles/{0}/{1}/'.format(role_data['id'], module.param_to_endpoint(actor_type))
|
||||
associations.setdefault(endpoint, [])
|
||||
associations[endpoint].append(actor['id'])
|
||||
|
||||
# perform associations
|
||||
for association_endpoint, new_association_list in associations.items():
|
||||
response = module.get_all_endpoint(association_endpoint)
|
||||
existing_associated_ids = [association['id'] for association in response['json']['results']]
|
||||
|
||||
if state == 'present':
|
||||
for an_id in list(set(new_association_list) - set(existing_associated_ids)):
|
||||
response = module.post_endpoint(association_endpoint, **{'data': {'id': int(an_id)}})
|
||||
if response['status_code'] == 204:
|
||||
module.json_output['changed'] = True
|
||||
else:
|
||||
module.fail_json(msg="Failed to grant role. {0}".format(response['json'].get('detail', response['json'].get('msg', 'unknown'))))
|
||||
else:
|
||||
for an_id in list(set(existing_associated_ids) & set(new_association_list)):
|
||||
response = module.post_endpoint(association_endpoint, **{'data': {'id': int(an_id), 'disassociate': True}})
|
||||
if response['status_code'] == 204:
|
||||
module.json_output['changed'] = True
|
||||
else:
|
||||
module.fail_json(msg="Failed to revoke role. {0}".format(response['json'].get('detail', response['json'].get('msg', 'unknown'))))
|
||||
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,239 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
|
||||
# (c) 2020, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_schedule
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
short_description: create, update, or destroy Ansible Tower schedules.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower schedules. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
rrule:
|
||||
description:
|
||||
- A value representing the schedules iCal recurrence rule.
|
||||
- See rrule plugin for help constructing this value
|
||||
required: False
|
||||
type: str
|
||||
name:
|
||||
description:
|
||||
- Name of this schedule.
|
||||
required: True
|
||||
type: str
|
||||
new_name:
|
||||
description:
|
||||
- Setting this option will change the existing name (looked up via the name field.
|
||||
required: False
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- Optional description of this schedule.
|
||||
required: False
|
||||
type: str
|
||||
extra_data:
|
||||
description:
|
||||
- Specify C(extra_vars) for the template.
|
||||
required: False
|
||||
type: dict
|
||||
default: {}
|
||||
inventory:
|
||||
description:
|
||||
- Inventory applied as a prompt, assuming job template prompts for inventory
|
||||
required: False
|
||||
type: str
|
||||
scm_branch:
|
||||
description:
|
||||
- Branch to use in job run. Project default used if blank. Only allowed if project allow_override field is set to true.
|
||||
required: False
|
||||
type: str
|
||||
job_type:
|
||||
description:
|
||||
- The job type to use for the job template.
|
||||
required: False
|
||||
type: str
|
||||
choices:
|
||||
- 'run'
|
||||
- 'check'
|
||||
job_tags:
|
||||
description:
|
||||
- Comma separated list of the tags to use for the job template.
|
||||
required: False
|
||||
type: str
|
||||
skip_tags:
|
||||
description:
|
||||
- Comma separated list of the tags to skip for the job template.
|
||||
required: False
|
||||
type: str
|
||||
limit:
|
||||
description:
|
||||
- A host pattern to further constrain the list of hosts managed or affected by the playbook
|
||||
required: False
|
||||
type: str
|
||||
diff_mode:
|
||||
description:
|
||||
- Enable diff mode for the job template.
|
||||
required: False
|
||||
type: bool
|
||||
verbosity:
|
||||
description:
|
||||
- Control the output level Ansible produces as the playbook runs. 0 - Normal, 1 - Verbose, 2 - More Verbose, 3 - Debug, 4 - Connection Debug.
|
||||
required: False
|
||||
type: int
|
||||
choices:
|
||||
- 0
|
||||
- 1
|
||||
- 2
|
||||
- 3
|
||||
- 4
|
||||
- 5
|
||||
unified_job_template:
|
||||
description:
|
||||
- Name of unified job template to schedule.
|
||||
required: False
|
||||
type: str
|
||||
enabled:
|
||||
description:
|
||||
- Enables processing of this schedule.
|
||||
required: False
|
||||
type: bool
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
choices: ["present", "absent"]
|
||||
default: "present"
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Build a schedule for Demo Job Template
|
||||
tower_schedule:
|
||||
name: "{{ sched1 }}"
|
||||
state: present
|
||||
unified_job_template: "Demo Job Template"
|
||||
rrule: "DTSTART:20191219T130551Z RRULE:FREQ=WEEKLY;INTERVAL=1;COUNT=1"
|
||||
register: result
|
||||
|
||||
- name: Build the same schedule using the rrule plugin
|
||||
tower_schedule:
|
||||
name: "{{ sched1 }}"
|
||||
state: present
|
||||
unified_job_template: "Demo Job Template"
|
||||
rrule: "{{ query('awx.awx.tower_schedule_rrule', 'week', start_date='2019-12-19 13:05:51') }}"
|
||||
register: result
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
rrule=dict(),
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
description=dict(),
|
||||
extra_data=dict(type='dict'),
|
||||
inventory=dict(),
|
||||
scm_branch=dict(),
|
||||
job_type=dict(choices=['run', 'check']),
|
||||
job_tags=dict(),
|
||||
skip_tags=dict(),
|
||||
limit=dict(),
|
||||
diff_mode=dict(type='bool'),
|
||||
verbosity=dict(type='int', choices=[0, 1, 2, 3, 4, 5]),
|
||||
unified_job_template=dict(),
|
||||
enabled=dict(type='bool'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
rrule = module.params.get('rrule')
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get("new_name")
|
||||
description = module.params.get('description')
|
||||
extra_data = module.params.get('extra_data')
|
||||
inventory = module.params.get('inventory')
|
||||
scm_branch = module.params.get('scm_branch')
|
||||
job_type = module.params.get('job_type')
|
||||
job_tags = module.params.get('job_tags')
|
||||
skip_tags = module.params.get('skip_tags')
|
||||
limit = module.params.get('limit')
|
||||
diff_mode = module.params.get('diff_mode')
|
||||
verbosity = module.params.get('verbosity')
|
||||
unified_job_template = module.params.get('unified_job_template')
|
||||
enabled = module.params.get('enabled')
|
||||
state = module.params.get('state')
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
inventory_id = None
|
||||
if inventory:
|
||||
inventory_id = module.resolve_name_to_id('inventories', inventory)
|
||||
unified_job_template_id = None
|
||||
if unified_job_template:
|
||||
unified_job_template_id = module.resolve_name_to_id('unified_job_templates', unified_job_template)
|
||||
|
||||
# Attempt to look up an existing item based on the provided data
|
||||
existing_item = module.get_one('schedules', name_or_id=name)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
new_fields = {}
|
||||
if rrule is not None:
|
||||
new_fields['rrule'] = rrule
|
||||
new_fields['name'] = new_name if new_name else (module.get_item_name(existing_item) if existing_item else name)
|
||||
if description is not None:
|
||||
new_fields['description'] = description
|
||||
if extra_data is not None:
|
||||
new_fields['extra_data'] = extra_data
|
||||
if inventory is not None:
|
||||
new_fields['inventory'] = inventory_id
|
||||
if scm_branch is not None:
|
||||
new_fields['scm_branch'] = scm_branch
|
||||
if job_type is not None:
|
||||
new_fields['job_type'] = job_type
|
||||
if job_tags is not None:
|
||||
new_fields['job_tags'] = job_tags
|
||||
if skip_tags is not None:
|
||||
new_fields['skip_tags'] = skip_tags
|
||||
if limit is not None:
|
||||
new_fields['limit'] = limit
|
||||
if diff_mode is not None:
|
||||
new_fields['diff_mode'] = diff_mode
|
||||
if verbosity is not None:
|
||||
new_fields['verbosity'] = verbosity
|
||||
if unified_job_template is not None:
|
||||
new_fields['unified_job_template'] = unified_job_template_id
|
||||
if enabled is not None:
|
||||
new_fields['enabled'] = enabled
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(existing_item)
|
||||
elif state == 'present':
|
||||
# If the state was present and we can let the module build or update the existing item, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
existing_item, new_fields,
|
||||
endpoint='schedules', item_type='schedule',
|
||||
associations={
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['deprecated'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_send
|
||||
deprecated:
|
||||
removed_in: "14.0.0"
|
||||
why: Deprecated in favor of upcoming C(_import) module.
|
||||
alternative: Once published, use M(tower_import) instead.
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
short_description: Send assets to Ansible Tower.
|
||||
description:
|
||||
- Send assets to Ansible Tower. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
assets:
|
||||
description:
|
||||
- The assets to import.
|
||||
- This can be the output of tower_receive or loaded from a file
|
||||
type: str
|
||||
files:
|
||||
description:
|
||||
- List of files to import.
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
prevent:
|
||||
description:
|
||||
- A list of asset types to prevent import for
|
||||
default: []
|
||||
type: list
|
||||
elements: str
|
||||
password_management:
|
||||
description:
|
||||
- The password management option to use.
|
||||
- The prompt option is not supported.
|
||||
default: 'default'
|
||||
choices: ["default", "random"]
|
||||
type: str
|
||||
|
||||
notes:
|
||||
- One of assets or files needs to be passed in
|
||||
|
||||
requirements:
|
||||
- "ansible-tower-cli >= 3.3.0"
|
||||
- six.moves.StringIO
|
||||
- sys
|
||||
|
||||
extends_documentation_fragment: awx.awx.auth_legacy
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Import all tower assets
|
||||
tower_send:
|
||||
assets: "{{ export_output.assets }}"
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
output:
|
||||
description: The import messages
|
||||
returned: success, fail
|
||||
type: list
|
||||
sample: [ 'Message 1', 'Message 2' ]
|
||||
'''
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
from ansible.module_utils.six.moves import StringIO
|
||||
from ..module_utils.tower_legacy import TowerLegacyModule, tower_auth_config, HAS_TOWER_CLI
|
||||
|
||||
from tempfile import mkstemp
|
||||
|
||||
try:
|
||||
from tower_cli.cli.transfer.send import Sender
|
||||
from tower_cli.utils.exceptions import TowerCLIError
|
||||
|
||||
from tower_cli.conf import settings
|
||||
TOWER_CLI_HAS_EXPORT = True
|
||||
except ImportError:
|
||||
TOWER_CLI_HAS_EXPORT = False
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = dict(
|
||||
assets=dict(),
|
||||
files=dict(default=[], type='list', elements='str'),
|
||||
prevent=dict(default=[], type='list', elements='str'),
|
||||
password_management=dict(default='default', choices=['default', 'random']),
|
||||
)
|
||||
|
||||
module = TowerLegacyModule(argument_spec=argument_spec, supports_check_mode=False)
|
||||
|
||||
module.deprecate(msg="This module is deprecated and will be replaced by the AWX CLI import command", version="awx.awx:14.0.0")
|
||||
|
||||
if not HAS_TOWER_CLI:
|
||||
module.fail_json(msg='ansible-tower-cli required for this module')
|
||||
|
||||
if not TOWER_CLI_HAS_EXPORT:
|
||||
module.fail_json(msg='ansible-tower-cli version does not support export')
|
||||
|
||||
assets = module.params.get('assets')
|
||||
prevent = module.params.get('prevent')
|
||||
password_management = module.params.get('password_management')
|
||||
files = module.params.get('files')
|
||||
|
||||
result = dict(
|
||||
changed=False,
|
||||
msg='',
|
||||
output='',
|
||||
)
|
||||
|
||||
if not assets and not files:
|
||||
result['msg'] = "Assets or files must be specified"
|
||||
module.fail_json(**result)
|
||||
|
||||
path = None
|
||||
if assets:
|
||||
# We got assets so we need to dump this out to a temp file and append that to files
|
||||
handle, path = mkstemp(prefix='', suffix='', dir='')
|
||||
with open(path, 'w') as f:
|
||||
f.write(assets)
|
||||
files.append(path)
|
||||
|
||||
tower_auth = tower_auth_config(module)
|
||||
failed = False
|
||||
with settings.runtime_values(**tower_auth):
|
||||
try:
|
||||
sender = Sender(no_color=False)
|
||||
old_stdout = sys.stdout
|
||||
sys.stdout = captured_stdout = StringIO()
|
||||
try:
|
||||
sender.send(files, prevent, password_management)
|
||||
except TypeError:
|
||||
# Newer versions of TowerCLI require 4 parameters
|
||||
sender.send(files, prevent, [], password_management)
|
||||
|
||||
if sender.error_messages > 0:
|
||||
failed = True
|
||||
result['msg'] = "Transfer Failed with %d errors" % sender.error_messages
|
||||
if sender.changed_messages > 0:
|
||||
result['changed'] = True
|
||||
except TowerCLIError as e:
|
||||
result['msg'] = e.message
|
||||
failed = True
|
||||
finally:
|
||||
if path is not None:
|
||||
os.remove(path)
|
||||
result['output'] = captured_stdout.getvalue().split("\n")
|
||||
sys.stdout = old_stdout
|
||||
|
||||
# Return stdout so that module returns will work
|
||||
if failed:
|
||||
module.fail_json(**result)
|
||||
else:
|
||||
module.exit_json(**result)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,187 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2018, Nikhil Jain <nikjain@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_settings
|
||||
author: "Nikhil Jain (@jainnikhil30)"
|
||||
short_description: Modify Ansible Tower settings.
|
||||
description:
|
||||
- Modify Ansible Tower settings. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name of setting to modify
|
||||
type: str
|
||||
value:
|
||||
description:
|
||||
- Value to be modified for given setting.
|
||||
- If given a non-string type, will make best effort to cast it to type API expects.
|
||||
- For better control over types, use the C(settings) param instead.
|
||||
type: str
|
||||
settings:
|
||||
description:
|
||||
- A data structure to be sent into the settings endpoint
|
||||
type: dict
|
||||
requirements:
|
||||
- pyyaml
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Set the value of AWX_PROOT_BASE_PATH
|
||||
tower_settings:
|
||||
name: AWX_PROOT_BASE_PATH
|
||||
value: "/tmp"
|
||||
register: testing_settings
|
||||
|
||||
- name: Set the value of AWX_PROOT_SHOW_PATHS
|
||||
tower_settings:
|
||||
name: "AWX_PROOT_SHOW_PATHS"
|
||||
value: "'/var/lib/awx/projects/', '/tmp'"
|
||||
register: testing_settings
|
||||
|
||||
- name: Set the LDAP Auth Bind Password
|
||||
tower_settings:
|
||||
name: "AUTH_LDAP_BIND_PASSWORD"
|
||||
value: "Password"
|
||||
no_log: true
|
||||
|
||||
- name: Set all the LDAP Auth Bind Params
|
||||
tower_settings:
|
||||
settings:
|
||||
AUTH_LDAP_BIND_PASSWORD: "password"
|
||||
AUTH_LDAP_USER_ATTR_MAP:
|
||||
email: "mail"
|
||||
first_name: "givenName"
|
||||
last_name: "surname"
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
try:
|
||||
import yaml
|
||||
HAS_YAML = True
|
||||
except ImportError:
|
||||
HAS_YAML = False
|
||||
|
||||
|
||||
def coerce_type(module, value):
|
||||
# If our value is already None we can just return directly
|
||||
if value is None:
|
||||
return value
|
||||
|
||||
yaml_ish = bool((
|
||||
value.startswith('{') and value.endswith('}')
|
||||
) or (
|
||||
value.startswith('[') and value.endswith(']'))
|
||||
)
|
||||
if yaml_ish:
|
||||
if not HAS_YAML:
|
||||
module.fail_json(msg="yaml is not installed, try 'pip install pyyaml'")
|
||||
return yaml.safe_load(value)
|
||||
elif value.lower in ('true', 'false', 't', 'f'):
|
||||
return {'t': True, 'f': False}[value[0].lower()]
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
pass
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(),
|
||||
value=dict(),
|
||||
settings=dict(type='dict'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(
|
||||
argument_spec=argument_spec,
|
||||
required_one_of=[['name', 'settings']],
|
||||
mutually_exclusive=[['name', 'settings']],
|
||||
required_if=[['name', 'present', ['value']]]
|
||||
)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
value = module.params.get('value')
|
||||
new_settings = module.params.get('settings')
|
||||
|
||||
# If we were given a name/value pair we will just make settings out of that and proceed normally
|
||||
if new_settings is None:
|
||||
new_value = coerce_type(module, value)
|
||||
|
||||
new_settings = {name: new_value}
|
||||
|
||||
# Load the existing settings
|
||||
existing_settings = module.get_endpoint('settings/all')['json']
|
||||
|
||||
# Begin a json response
|
||||
json_output = {'changed': False, 'old_values': {}, 'new_values': {}}
|
||||
|
||||
# Check any of the settings to see if anything needs to be updated
|
||||
needs_update = False
|
||||
for a_setting in new_settings:
|
||||
if a_setting not in existing_settings or existing_settings[a_setting] != new_settings[a_setting]:
|
||||
# At least one thing is different so we need to patch
|
||||
needs_update = True
|
||||
json_output['old_values'][a_setting] = existing_settings[a_setting]
|
||||
json_output['new_values'][a_setting] = new_settings[a_setting]
|
||||
|
||||
if module._diff:
|
||||
json_output['diff'] = {
|
||||
'before': json_output['old_values'],
|
||||
'after': json_output['new_values']
|
||||
}
|
||||
|
||||
# If nothing needs an update we can simply exit with the response (as not changed)
|
||||
if not needs_update:
|
||||
module.exit_json(**json_output)
|
||||
|
||||
if module.check_mode and module._diff:
|
||||
json_output['changed'] = True
|
||||
module.exit_json(**json_output)
|
||||
|
||||
# Make the call to update the settings
|
||||
response = module.patch_endpoint('settings/all', **{'data': new_settings})
|
||||
|
||||
if response['status_code'] == 200:
|
||||
# Set the changed response to True
|
||||
json_output['changed'] = True
|
||||
|
||||
# To deal with the old style values we need to return 'value' in the response
|
||||
new_values = {}
|
||||
for a_setting in new_settings:
|
||||
new_values[a_setting] = response['json'][a_setting]
|
||||
|
||||
# If we were using a name we will just add a value of a string, otherwise we will return an array in values
|
||||
if name is not None:
|
||||
json_output['value'] = new_values[name]
|
||||
else:
|
||||
json_output['values'] = new_values
|
||||
|
||||
module.exit_json(**json_output)
|
||||
elif 'json' in response and '__all__' in response['json']:
|
||||
module.fail_json(msg=response['json']['__all__'])
|
||||
else:
|
||||
module.fail_json(**{'msg': "Unable to update settings, see response", 'response': response})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_team
|
||||
author: "Wayne Witzel III (@wwitzel3)"
|
||||
short_description: create, update, or destroy Ansible Tower team.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower teams. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name to use for the team.
|
||||
required: True
|
||||
type: str
|
||||
new_name:
|
||||
description:
|
||||
- To use when changing a team's name.
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- The description to use for the team.
|
||||
type: str
|
||||
organization:
|
||||
description:
|
||||
- Organization the team should be made a member of.
|
||||
required: True
|
||||
type: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
choices: ["present", "absent"]
|
||||
default: "present"
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create tower team
|
||||
tower_team:
|
||||
name: Team Name
|
||||
description: Team Description
|
||||
organization: test-org
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
description=dict(),
|
||||
organization=dict(required=True),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get('new_name')
|
||||
description = module.params.get('description')
|
||||
organization = module.params.get('organization')
|
||||
state = module.params.get('state')
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
org_id = module.resolve_name_to_id('organizations', organization)
|
||||
|
||||
# Attempt to look up team based on the provided name and org ID
|
||||
team = module.get_one('teams', name_or_id=name, **{
|
||||
'data': {
|
||||
'organization': org_id
|
||||
}
|
||||
})
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(team)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
team_fields = {
|
||||
'name': new_name if new_name else (module.get_item_name(team) if team else name),
|
||||
'organization': org_id
|
||||
}
|
||||
if description is not None:
|
||||
team_fields['description'] = description
|
||||
|
||||
# If the state was present and we can let the module build or update the existing team, this will return on its own
|
||||
module.create_or_update_if_needed(team, team_fields, endpoint='teams', item_type='team')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,201 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
|
||||
# (c) 2020, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_token
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
version_added: "2.3"
|
||||
short_description: create, update, or destroy Ansible Tower tokens.
|
||||
description:
|
||||
- Create or destroy Ansible Tower tokens. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
- In addition, the module sets an Ansible fact which can be passed into other
|
||||
tower_* modules as the parameter tower_oauthtoken. See examples for usage.
|
||||
- Because of the sensitive nature of tokens, the created token value is only available once
|
||||
through the Ansible fact. (See RETURN for details)
|
||||
- Due to the nature of tokens in Tower this module is not idempotent. A second will
|
||||
with the same parameters will create a new token.
|
||||
- If you are creating a temporary token for use with modules you should delete the token
|
||||
when you are done with it. See the example for how to do it.
|
||||
options:
|
||||
description:
|
||||
description:
|
||||
- Optional description of this access token.
|
||||
required: False
|
||||
type: str
|
||||
default: ''
|
||||
application:
|
||||
description:
|
||||
- The application tied to this token.
|
||||
required: False
|
||||
type: str
|
||||
scope:
|
||||
description:
|
||||
- Allowed scopes, further restricts user's permissions. Must be a simple space-separated string with allowed scopes ['read', 'write'].
|
||||
required: False
|
||||
type: str
|
||||
default: 'write'
|
||||
choices: ["read", "write"]
|
||||
existing_token:
|
||||
description: The data structure produced from tower_token in create mode to be used with state absent.
|
||||
type: dict
|
||||
existing_token_id:
|
||||
description: A token ID (number) which can be used to delete an arbitrary token with state absent.
|
||||
type: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
choices: ["present", "absent"]
|
||||
default: "present"
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- block:
|
||||
- name: Create a new token using an existing token
|
||||
tower_token:
|
||||
description: '{{ token_description }}'
|
||||
scope: "write"
|
||||
state: present
|
||||
tower_oauthtoken: "{{ my_existing_token }}"
|
||||
|
||||
- name: Delete this token
|
||||
tower_token:
|
||||
existing_token: "{{ tower_token }}"
|
||||
state: absent
|
||||
|
||||
- name: Create a new token using username/password
|
||||
tower_token:
|
||||
description: '{{ token_description }}'
|
||||
scope: "write"
|
||||
state: present
|
||||
tower_username: "{{ my_username }}"
|
||||
tower_password: "{{ my_password }}"
|
||||
|
||||
- name: Use our new token to make another call
|
||||
tower_job_list:
|
||||
tower_oauthtoken: "{{ tower_token }}"
|
||||
|
||||
always:
|
||||
- name: Delete our Token with the token we created
|
||||
tower_token:
|
||||
existing_token: "{{ tower_token }}"
|
||||
state: absent
|
||||
when: tower_token is defined
|
||||
|
||||
- name: Delete a token by its id
|
||||
tower_token:
|
||||
existing_token_id: 4
|
||||
state: absent
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
tower_token:
|
||||
type: dict
|
||||
description: An Ansible Fact variable representing a Tower token object which can be used for auth in subsequent modules. See examples for usage.
|
||||
contains:
|
||||
token:
|
||||
description: The token that was generated. This token can never be accessed again, make sure this value is noted before it is lost.
|
||||
type: str
|
||||
id:
|
||||
description: The numeric ID of the token created
|
||||
type: str
|
||||
returned: on successful create
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def return_token(module, last_response):
|
||||
# A token is special because you can never get the actual token ID back from the API.
|
||||
# So the default module return would give you an ID but then the token would forever be masked on you.
|
||||
# This method will return the entire token object we got back so that a user has access to the token
|
||||
|
||||
module.json_output['ansible_facts'] = {
|
||||
'tower_token': last_response,
|
||||
}
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
description=dict(),
|
||||
application=dict(),
|
||||
scope=dict(choices=['read', 'write'], default='write'),
|
||||
existing_token=dict(type='dict'),
|
||||
existing_token_id=dict(),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(
|
||||
argument_spec=argument_spec,
|
||||
mutually_exclusive=[
|
||||
('existing_token', 'existing_token_id'),
|
||||
],
|
||||
# If we are state absent make sure one of existing_token or existing_token_id are present
|
||||
required_if=[
|
||||
['state', 'absent', ('existing_token', 'existing_token_id'), True, ],
|
||||
],
|
||||
)
|
||||
|
||||
# Extract our parameters
|
||||
description = module.params.get('description')
|
||||
application = module.params.get('application')
|
||||
scope = module.params.get('scope')
|
||||
existing_token = module.params.get('existing_token')
|
||||
existing_token_id = module.params.get('existing_token_id')
|
||||
state = module.params.get('state')
|
||||
|
||||
if state == 'absent':
|
||||
if not existing_token:
|
||||
existing_token = module.get_one('tokens', **{
|
||||
'data': {
|
||||
'id': existing_token_id,
|
||||
}
|
||||
})
|
||||
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(existing_token)
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
application_id = None
|
||||
if application:
|
||||
application_id = module.resolve_name_to_id('applications', application)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
new_fields = {}
|
||||
if description is not None:
|
||||
new_fields['description'] = description
|
||||
if application is not None:
|
||||
new_fields['application'] = application_id
|
||||
if scope is not None:
|
||||
new_fields['scope'] = scope
|
||||
|
||||
# If the state was present and we can let the module build or update the existing item, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
None, new_fields,
|
||||
endpoint='tokens', item_type='token',
|
||||
associations={
|
||||
},
|
||||
on_create=return_token,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# (c) 2020, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_user
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
short_description: create, update, or destroy Ansible Tower users.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower users. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
username:
|
||||
description:
|
||||
- Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.
|
||||
required: True
|
||||
type: str
|
||||
first_name:
|
||||
description:
|
||||
- First name of the user.
|
||||
type: str
|
||||
last_name:
|
||||
description:
|
||||
- Last name of the user.
|
||||
type: str
|
||||
email:
|
||||
description:
|
||||
- Email address of the user.
|
||||
type: str
|
||||
is_superuser:
|
||||
description:
|
||||
- Designates that this user has all permissions without explicitly assigning them.
|
||||
type: bool
|
||||
default: False
|
||||
aliases: ['superuser']
|
||||
is_system_auditor:
|
||||
description:
|
||||
- User is a system wide auditor.
|
||||
type: bool
|
||||
default: False
|
||||
aliases: ['auditor']
|
||||
password:
|
||||
description:
|
||||
- Write-only field used to change the password.
|
||||
type: str
|
||||
update_secrets:
|
||||
description:
|
||||
- C(true) will always change password if user specifies password, even if API gives $encrypted$ for password.
|
||||
- C(false) will only set the password if other values change too.
|
||||
type: bool
|
||||
default: true
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
choices: ["present", "absent"]
|
||||
default: "present"
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Add tower user
|
||||
tower_user:
|
||||
username: jdoe
|
||||
password: foobarbaz
|
||||
email: jdoe@example.org
|
||||
first_name: John
|
||||
last_name: Doe
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Add tower user as a system administrator
|
||||
tower_user:
|
||||
username: jdoe
|
||||
password: foobarbaz
|
||||
email: jdoe@example.org
|
||||
superuser: yes
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Add tower user as a system auditor
|
||||
tower_user:
|
||||
username: jdoe
|
||||
password: foobarbaz
|
||||
email: jdoe@example.org
|
||||
auditor: yes
|
||||
state: present
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
|
||||
- name: Delete tower user
|
||||
tower_user:
|
||||
username: jdoe
|
||||
email: jdoe@example.org
|
||||
state: absent
|
||||
tower_config_file: "~/tower_cli.cfg"
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
username=dict(required=True),
|
||||
first_name=dict(),
|
||||
last_name=dict(),
|
||||
email=dict(),
|
||||
is_superuser=dict(type='bool', default=False, aliases=['superuser']),
|
||||
is_system_auditor=dict(type='bool', default=False, aliases=['auditor']),
|
||||
password=dict(no_log=True),
|
||||
update_secrets=dict(type='bool', default=True, no_log=False),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
username = module.params.get('username')
|
||||
first_name = module.params.get('first_name')
|
||||
last_name = module.params.get('last_name')
|
||||
email = module.params.get('email')
|
||||
is_superuser = module.params.get('is_superuser')
|
||||
is_system_auditor = module.params.get('is_system_auditor')
|
||||
password = module.params.get('password')
|
||||
state = module.params.get('state')
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
|
||||
# Attempt to look up an existing item based on the provided data
|
||||
existing_item = module.get_one('users', name_or_id=username)
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(existing_item)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
new_fields = {}
|
||||
if username:
|
||||
new_fields['username'] = module.get_item_name(existing_item) if existing_item else username
|
||||
if first_name:
|
||||
new_fields['first_name'] = first_name
|
||||
if last_name:
|
||||
new_fields['last_name'] = last_name
|
||||
if email:
|
||||
new_fields['email'] = email
|
||||
if is_superuser:
|
||||
new_fields['is_superuser'] = is_superuser
|
||||
if is_system_auditor:
|
||||
new_fields['is_system_auditor'] = is_system_auditor
|
||||
if password:
|
||||
new_fields['password'] = password
|
||||
|
||||
# If the state was present and we can let the module build or update the existing item, this will return on its own
|
||||
module.create_or_update_if_needed(existing_item, new_fields, endpoint='users', item_type='user')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,301 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
|
||||
# (c) 2020, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_workflow_job_template
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
short_description: create, update, or destroy Ansible Tower workflow job templates.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower workflow job templates.
|
||||
- Replaces the deprecated tower_workflow_template module.
|
||||
- Use the tower_workflow_job_template_node after this to build the workflow's graph.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- Name of this workflow job template.
|
||||
required: True
|
||||
type: str
|
||||
new_name:
|
||||
description:
|
||||
- Setting this option will change the existing name.
|
||||
type: str
|
||||
description:
|
||||
description:
|
||||
- Optional description of this workflow job template.
|
||||
type: str
|
||||
extra_vars:
|
||||
description:
|
||||
- Variables which will be made available to jobs ran inside the workflow.
|
||||
type: dict
|
||||
organization:
|
||||
description:
|
||||
- Organization the workflow job template exists in.
|
||||
- Used to help lookup the object, cannot be modified using this module.
|
||||
- If not provided, will lookup by name only, which does not work with duplicates.
|
||||
type: str
|
||||
allow_simultaneous:
|
||||
description:
|
||||
- Allow simultaneous runs of the workflow job template.
|
||||
type: bool
|
||||
ask_variables_on_launch:
|
||||
description:
|
||||
- Prompt user for C(extra_vars) on launch.
|
||||
type: bool
|
||||
inventory:
|
||||
description:
|
||||
- Inventory applied as a prompt, assuming job template prompts for inventory
|
||||
type: str
|
||||
limit:
|
||||
description:
|
||||
- Limit applied as a prompt, assuming job template prompts for limit
|
||||
type: str
|
||||
scm_branch:
|
||||
description:
|
||||
- SCM branch applied as a prompt, assuming job template prompts for SCM branch
|
||||
type: str
|
||||
ask_inventory_on_launch:
|
||||
description:
|
||||
- Prompt user for inventory on launch of this workflow job template
|
||||
type: bool
|
||||
ask_scm_branch_on_launch:
|
||||
description:
|
||||
- Prompt user for SCM branch on launch of this workflow job template
|
||||
type: bool
|
||||
ask_limit_on_launch:
|
||||
description:
|
||||
- Prompt user for limit on launch of this workflow job template
|
||||
type: bool
|
||||
webhook_service:
|
||||
description:
|
||||
- Service that webhook requests will be accepted from
|
||||
type: str
|
||||
choices:
|
||||
- github
|
||||
- gitlab
|
||||
webhook_credential:
|
||||
description:
|
||||
- Personal Access Token for posting back the status to the service API
|
||||
type: str
|
||||
survey_enabled:
|
||||
description:
|
||||
- Setting that variable will prompt the user for job type on the
|
||||
workflow launch.
|
||||
type: bool
|
||||
survey_spec:
|
||||
description:
|
||||
- The definition of the survey associated to the workflow.
|
||||
type: dict
|
||||
aliases:
|
||||
- survey
|
||||
labels:
|
||||
description:
|
||||
- The labels applied to this job template
|
||||
type: list
|
||||
elements: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
choices:
|
||||
- present
|
||||
- absent
|
||||
default: "present"
|
||||
type: str
|
||||
notification_templates_started:
|
||||
description:
|
||||
- list of notifications to send on start
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_success:
|
||||
description:
|
||||
- list of notifications to send on success
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_error:
|
||||
description:
|
||||
- list of notifications to send on error
|
||||
type: list
|
||||
elements: str
|
||||
notification_templates_approvals:
|
||||
description:
|
||||
- list of notifications to send on start
|
||||
type: list
|
||||
elements: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create a workflow job template
|
||||
tower_workflow_job_template:
|
||||
name: example-workflow
|
||||
description: created by Ansible Playbook
|
||||
organization: Default
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
import json
|
||||
|
||||
|
||||
def update_survey(module, last_request):
|
||||
spec_endpoint = last_request.get('related', {}).get('survey_spec')
|
||||
if module.params.get('survey_spec') == {}:
|
||||
response = module.delete_endpoint(spec_endpoint)
|
||||
if response['status_code'] != 200:
|
||||
# Not sure how to make this actually return a non 200 to test what to dump in the respinse
|
||||
module.fail_json(msg="Failed to delete survey: {0}".format(response['json']))
|
||||
else:
|
||||
response = module.post_endpoint(spec_endpoint, **{'data': module.params.get('survey_spec')})
|
||||
if response['status_code'] != 200:
|
||||
module.fail_json(msg="Failed to update survey: {0}".format(response['json']['error']))
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
new_name=dict(),
|
||||
description=dict(),
|
||||
extra_vars=dict(type='dict'),
|
||||
organization=dict(),
|
||||
survey_spec=dict(type='dict', aliases=['survey']),
|
||||
survey_enabled=dict(type='bool'),
|
||||
allow_simultaneous=dict(type='bool'),
|
||||
ask_variables_on_launch=dict(type='bool'),
|
||||
inventory=dict(),
|
||||
limit=dict(),
|
||||
scm_branch=dict(),
|
||||
ask_inventory_on_launch=dict(type='bool'),
|
||||
ask_scm_branch_on_launch=dict(type='bool'),
|
||||
ask_limit_on_launch=dict(type='bool'),
|
||||
webhook_service=dict(choices=['github', 'gitlab']),
|
||||
webhook_credential=dict(),
|
||||
labels=dict(type="list", elements='str'),
|
||||
notification_templates_started=dict(type="list", elements='str'),
|
||||
notification_templates_success=dict(type="list", elements='str'),
|
||||
notification_templates_error=dict(type="list", elements='str'),
|
||||
notification_templates_approvals=dict(type="list", elements='str'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
new_name = module.params.get("new_name")
|
||||
state = module.params.get('state')
|
||||
|
||||
new_fields = {}
|
||||
search_fields = {}
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
organization = module.params.get('organization')
|
||||
if organization:
|
||||
organization_id = module.resolve_name_to_id('organizations', organization)
|
||||
search_fields['organization'] = new_fields['organization'] = organization_id
|
||||
|
||||
# Attempt to look up an existing item based on the provided data
|
||||
existing_item = module.get_one('workflow_job_templates', name_or_id=name, **{'data': search_fields})
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(existing_item)
|
||||
|
||||
inventory = module.params.get('inventory')
|
||||
if inventory:
|
||||
new_fields['inventory'] = module.resolve_name_to_id('inventories', inventory)
|
||||
|
||||
webhook_credential = module.params.get('webhook_credential')
|
||||
if webhook_credential:
|
||||
new_fields['webhook_credential'] = module.resolve_name_to_id('webhook_credential', webhook_credential)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
new_fields['name'] = new_name if new_name else (module.get_item_name(existing_item) if existing_item else name)
|
||||
for field_name in (
|
||||
'description', 'survey_enabled', 'allow_simultaneous',
|
||||
'limit', 'scm_branch', 'extra_vars',
|
||||
'ask_inventory_on_launch', 'ask_scm_branch_on_launch', 'ask_limit_on_launch', 'ask_variables_on_launch',
|
||||
'webhook_service',):
|
||||
field_val = module.params.get(field_name)
|
||||
if field_val:
|
||||
new_fields[field_name] = field_val
|
||||
|
||||
if 'extra_vars' in new_fields:
|
||||
new_fields['extra_vars'] = json.dumps(new_fields['extra_vars'])
|
||||
|
||||
association_fields = {}
|
||||
|
||||
notifications_start = module.params.get('notification_templates_started')
|
||||
if notifications_start is not None:
|
||||
association_fields['notification_templates_started'] = []
|
||||
for item in notifications_start:
|
||||
association_fields['notification_templates_started'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_success = module.params.get('notification_templates_success')
|
||||
if notifications_success is not None:
|
||||
association_fields['notification_templates_success'] = []
|
||||
for item in notifications_success:
|
||||
association_fields['notification_templates_success'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_error = module.params.get('notification_templates_error')
|
||||
if notifications_error is not None:
|
||||
association_fields['notification_templates_error'] = []
|
||||
for item in notifications_error:
|
||||
association_fields['notification_templates_error'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
notifications_approval = module.params.get('notification_templates_approvals')
|
||||
if notifications_approval is not None:
|
||||
association_fields['notification_templates_approvals'] = []
|
||||
for item in notifications_approval:
|
||||
association_fields['notification_templates_approvals'].append(module.resolve_name_to_id('notification_templates', item))
|
||||
|
||||
labels = module.params.get('labels')
|
||||
if labels is not None:
|
||||
association_fields['labels'] = []
|
||||
for item in labels:
|
||||
association_fields['labels'].append(module.resolve_name_to_id('labels', item))
|
||||
# Code to use once Issue #7567 is resolved
|
||||
# search_fields = {'name': item}
|
||||
# if organization:
|
||||
# search_fields['organization'] = organization_id
|
||||
# label_id = module.get_one('labels', **{'data': search_fields})
|
||||
# association_fields['labels'].append(label_id)
|
||||
|
||||
on_change = None
|
||||
new_spec = module.params.get('survey_spec')
|
||||
if new_spec:
|
||||
existing_spec = None
|
||||
if existing_item:
|
||||
spec_endpoint = existing_item.get('related', {}).get('survey_spec')
|
||||
existing_spec = module.get_endpoint(spec_endpoint)
|
||||
if new_spec != existing_spec:
|
||||
module.json_output['changed'] = True
|
||||
if existing_item and module.has_encrypted_values(existing_spec):
|
||||
module._encrypted_changed_warning('survey_spec', existing_item, warning=True)
|
||||
on_change = update_survey
|
||||
|
||||
# If the state was present and we can let the module build or update the existing item, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
existing_item, new_fields,
|
||||
endpoint='workflow_job_templates', item_type='workflow_job_template',
|
||||
associations=association_fields,
|
||||
on_create=on_change, on_update=on_change
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,337 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
|
||||
# (c) 2020, John Westcott IV <john.westcott.iv@redhat.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_workflow_job_template_node
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
short_description: create, update, or destroy Ansible Tower workflow job template nodes.
|
||||
description:
|
||||
- Create, update, or destroy Ansible Tower workflow job template nodes.
|
||||
- Use this to build a graph for a workflow, which dictates what the workflow runs.
|
||||
- Replaces the deprecated tower_workflow_template module schema command.
|
||||
- You can create nodes first, and link them afterwards, and not worry about ordering.
|
||||
For failsafe referencing of a node, specify identifier, WFJT, and organization.
|
||||
With those specified, you can choose to modify or not modify any other parameter.
|
||||
options:
|
||||
extra_data:
|
||||
description:
|
||||
- Variables to apply at launch time.
|
||||
- Will only be accepted if job template prompts for vars or has a survey asking for those vars.
|
||||
type: dict
|
||||
default: {}
|
||||
inventory:
|
||||
description:
|
||||
- Inventory applied as a prompt, if job template prompts for inventory
|
||||
type: str
|
||||
scm_branch:
|
||||
description:
|
||||
- SCM branch applied as a prompt, if job template prompts for SCM branch
|
||||
type: str
|
||||
job_type:
|
||||
description:
|
||||
- Job type applied as a prompt, if job template prompts for job type
|
||||
type: str
|
||||
choices:
|
||||
- 'run'
|
||||
- 'check'
|
||||
job_tags:
|
||||
description:
|
||||
- Job tags applied as a prompt, if job template prompts for job tags
|
||||
type: str
|
||||
skip_tags:
|
||||
description:
|
||||
- Tags to skip, applied as a prompt, if job tempalte prompts for job tags
|
||||
type: str
|
||||
limit:
|
||||
description:
|
||||
- Limit to act on, applied as a prompt, if job template prompts for limit
|
||||
type: str
|
||||
diff_mode:
|
||||
description:
|
||||
- Run diff mode, applied as a prompt, if job template prompts for diff mode
|
||||
type: bool
|
||||
verbosity:
|
||||
description:
|
||||
- Verbosity applied as a prompt, if job template prompts for verbosity
|
||||
type: str
|
||||
choices:
|
||||
- '0'
|
||||
- '1'
|
||||
- '2'
|
||||
- '3'
|
||||
- '4'
|
||||
- '5'
|
||||
workflow_job_template:
|
||||
description:
|
||||
- The workflow job template the node exists in.
|
||||
- Used for looking up the node, cannot be modified after creation.
|
||||
required: True
|
||||
type: str
|
||||
aliases:
|
||||
- workflow
|
||||
organization:
|
||||
description:
|
||||
- The organization of the workflow job template the node exists in.
|
||||
- Used for looking up the workflow, not a direct model field.
|
||||
type: str
|
||||
unified_job_template:
|
||||
description:
|
||||
- Name of unified job template to run in the workflow.
|
||||
- Can be a job template, project, inventory source, etc.
|
||||
- Omit if creating an approval node.
|
||||
- This parameter is mutually exclusive with C(approval_node).
|
||||
type: str
|
||||
approval_node:
|
||||
description:
|
||||
- A dictionary of Name, description, and timeout values for the approval node.
|
||||
- This parameter is mutually exclusive with C(unified_job_template).
|
||||
type: dict
|
||||
suboptions:
|
||||
name:
|
||||
description:
|
||||
- Name of this workflow approval template.
|
||||
type: str
|
||||
required: True
|
||||
description:
|
||||
description:
|
||||
- Optional description of this workflow approval template.
|
||||
type: str
|
||||
timeout:
|
||||
description:
|
||||
- The amount of time (in seconds) before the approval node expires and fails.
|
||||
type: int
|
||||
all_parents_must_converge:
|
||||
description:
|
||||
- If enabled then the node will only run if all of the parent nodes have met the criteria to reach this node
|
||||
type: bool
|
||||
identifier:
|
||||
description:
|
||||
- An identifier for this node that is unique within its workflow.
|
||||
- It is copied to workflow job nodes corresponding to this node.
|
||||
required: True
|
||||
type: str
|
||||
always_nodes:
|
||||
description:
|
||||
- Nodes that will run after this node completes.
|
||||
- List of node identifiers.
|
||||
type: list
|
||||
elements: str
|
||||
success_nodes:
|
||||
description:
|
||||
- Nodes that will run after this node on success.
|
||||
- List of node identifiers.
|
||||
type: list
|
||||
elements: str
|
||||
failure_nodes:
|
||||
description:
|
||||
- Nodes that will run after this node on failure.
|
||||
- List of node identifiers.
|
||||
type: list
|
||||
elements: str
|
||||
credentials:
|
||||
description:
|
||||
- Credentials to be applied to job as launch-time prompts.
|
||||
- List of credential names.
|
||||
- Uniqueness is not handled rigorously.
|
||||
type: list
|
||||
elements: str
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
choices: ["present", "absent"]
|
||||
default: "present"
|
||||
type: str
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Create a node, follows tower_workflow_job_template example
|
||||
tower_workflow_job_template_node:
|
||||
identifier: my-first-node
|
||||
workflow: example-workflow
|
||||
unified_job_template: jt-for-node-use
|
||||
organization: Default # organization of workflow job template
|
||||
extra_data:
|
||||
foo_key: bar_value
|
||||
|
||||
- name: Create parent node for prior node
|
||||
tower_workflow_job_template_node:
|
||||
identifier: my-root-node
|
||||
workflow: example-workflow
|
||||
unified_job_template: jt-for-node-use
|
||||
organization: Default
|
||||
success_nodes:
|
||||
- my-first-node
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
identifier=dict(required=True),
|
||||
workflow_job_template=dict(required=True, aliases=['workflow']),
|
||||
organization=dict(),
|
||||
extra_data=dict(type='dict'),
|
||||
inventory=dict(),
|
||||
scm_branch=dict(),
|
||||
job_type=dict(choices=['run', 'check']),
|
||||
job_tags=dict(),
|
||||
skip_tags=dict(),
|
||||
limit=dict(),
|
||||
diff_mode=dict(type='bool'),
|
||||
verbosity=dict(choices=['0', '1', '2', '3', '4', '5']),
|
||||
unified_job_template=dict(),
|
||||
approval_node=dict(type='dict'),
|
||||
all_parents_must_converge=dict(type='bool'),
|
||||
success_nodes=dict(type='list', elements='str'),
|
||||
always_nodes=dict(type='list', elements='str'),
|
||||
failure_nodes=dict(type='list', elements='str'),
|
||||
credentials=dict(type='list', elements='str'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
mutually_exclusive = [("unified_job_template", "approval_node")]
|
||||
required_if = [
|
||||
['state', 'absent', ['identifier']],
|
||||
['state', 'present', ['identifier']],
|
||||
['state', 'present', ['unified_job_template', 'approval_node', 'success_nodes', 'always_nodes', 'failure_nodes'], 'true'],
|
||||
]
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(
|
||||
argument_spec=argument_spec,
|
||||
mutually_exclusive=mutually_exclusive,
|
||||
required_if=required_if,
|
||||
)
|
||||
|
||||
# Extract our parameters
|
||||
identifier = module.params.get('identifier')
|
||||
state = module.params.get('state')
|
||||
approval_node = module.params.get('approval_node')
|
||||
new_fields = {}
|
||||
search_fields = {'identifier': identifier}
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
workflow_job_template = module.params.get('workflow_job_template')
|
||||
workflow_job_template_id = None
|
||||
if workflow_job_template:
|
||||
wfjt_search_fields = {}
|
||||
organization = module.params.get('organization')
|
||||
if organization:
|
||||
organization_id = module.resolve_name_to_id('organizations', organization)
|
||||
wfjt_search_fields['organization'] = organization_id
|
||||
wfjt_data = module.get_one('workflow_job_templates', name_or_id=workflow_job_template, **{
|
||||
'data': wfjt_search_fields
|
||||
})
|
||||
if wfjt_data is None:
|
||||
module.fail_json(msg="The workflow {0} in organization {1} was not found on the Tower server".format(
|
||||
workflow_job_template, organization
|
||||
))
|
||||
workflow_job_template_id = wfjt_data['id']
|
||||
search_fields['workflow_job_template'] = new_fields['workflow_job_template'] = workflow_job_template_id
|
||||
|
||||
# Attempt to look up an existing item based on the provided data
|
||||
existing_item = module.get_one('workflow_job_template_nodes', **{'data': search_fields})
|
||||
|
||||
if state == 'absent':
|
||||
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
|
||||
module.delete_if_needed(existing_item)
|
||||
|
||||
unified_job_template = module.params.get('unified_job_template')
|
||||
if unified_job_template:
|
||||
new_fields['unified_job_template'] = module.resolve_name_to_id('unified_job_templates', unified_job_template)
|
||||
|
||||
inventory = module.params.get('inventory')
|
||||
if inventory:
|
||||
new_fields['inventory'] = module.resolve_name_to_id('inventories', inventory)
|
||||
|
||||
# Create the data that gets sent for create and update
|
||||
for field_name in (
|
||||
'identifier', 'extra_data', 'scm_branch', 'job_type', 'job_tags', 'skip_tags',
|
||||
'limit', 'diff_mode', 'verbosity', 'all_parents_must_converge',):
|
||||
field_val = module.params.get(field_name)
|
||||
if field_val:
|
||||
new_fields[field_name] = field_val
|
||||
|
||||
association_fields = {}
|
||||
for association in ('always_nodes', 'success_nodes', 'failure_nodes', 'credentials'):
|
||||
name_list = module.params.get(association)
|
||||
if name_list is None:
|
||||
continue
|
||||
id_list = []
|
||||
for sub_name in name_list:
|
||||
if association == 'credentials':
|
||||
endpoint = 'credentials'
|
||||
lookup_data = {'name': sub_name}
|
||||
else:
|
||||
endpoint = 'workflow_job_template_nodes'
|
||||
lookup_data = {'identifier': sub_name}
|
||||
if workflow_job_template_id:
|
||||
lookup_data['workflow_job_template'] = workflow_job_template_id
|
||||
sub_obj = module.get_one(endpoint, **{'data': lookup_data})
|
||||
if sub_obj is None:
|
||||
module.fail_json(msg='Could not find {0} entry with name {1}'.format(association, sub_name))
|
||||
id_list.append(sub_obj['id'])
|
||||
if id_list:
|
||||
association_fields[association] = id_list
|
||||
|
||||
# In the case of a new object, the utils need to know it is a node
|
||||
new_fields['type'] = 'workflow_job_template_node'
|
||||
|
||||
# If the state was present and we can let the module build or update the existing item, this will return on its own
|
||||
module.create_or_update_if_needed(
|
||||
existing_item, new_fields,
|
||||
endpoint='workflow_job_template_nodes', item_type='workflow_job_template_node', auto_exit=not approval_node,
|
||||
associations=association_fields
|
||||
)
|
||||
|
||||
# Create approval node unified template or update existing
|
||||
if approval_node:
|
||||
# Set Approval Fields
|
||||
new_fields = {}
|
||||
|
||||
# Extract Parameters
|
||||
if approval_node.get('name') is None:
|
||||
module.fail_json(msg="Approval node name is required to create approval node.")
|
||||
if approval_node.get('name') is not None:
|
||||
new_fields['name'] = approval_node['name']
|
||||
if approval_node.get('description') is not None:
|
||||
new_fields['description'] = approval_node['description']
|
||||
if approval_node.get('timeout') is not None:
|
||||
new_fields['timeout'] = approval_node['timeout']
|
||||
|
||||
# Find created workflow node ID
|
||||
search_fields = {'identifier': identifier}
|
||||
search_fields['workflow_job_template'] = workflow_job_template_id
|
||||
workflow_job_template_node = module.get_one('workflow_job_template_nodes', **{'data': search_fields})
|
||||
workflow_job_template_node_id = workflow_job_template_node['id']
|
||||
module.json_output['workflow_node_id'] = workflow_job_template_node_id
|
||||
existing_item = None
|
||||
# Due to not able to lookup workflow_approval_templates, find the existing item in another place
|
||||
if workflow_job_template_node['related'].get('unified_job_template') is not None:
|
||||
existing_item = module.get_endpoint(workflow_job_template_node['related']['unified_job_template'])['json']
|
||||
approval_endpoint = 'workflow_job_template_nodes/{0}/create_approval_template/'.format(workflow_job_template_node_id)
|
||||
module.create_or_update_if_needed(
|
||||
existing_item, new_fields,
|
||||
endpoint=approval_endpoint, item_type='workflow_job_template_approval_node',
|
||||
associations=association_fields
|
||||
)
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
||||
'status': ['preview'],
|
||||
'supported_by': 'community'}
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_workflow_launch
|
||||
author: "John Westcott IV (@john-westcott-iv)"
|
||||
short_description: Run a workflow in Ansible Tower
|
||||
description:
|
||||
- Launch an Ansible Tower workflows. See
|
||||
U(https://www.ansible.com/tower) for an overview.
|
||||
options:
|
||||
name:
|
||||
description:
|
||||
- The name of the workflow template to run.
|
||||
required: True
|
||||
type: str
|
||||
aliases:
|
||||
- workflow_template
|
||||
organization:
|
||||
description:
|
||||
- Organization the workflow job template exists in.
|
||||
- Used to help lookup the object, cannot be modified using this module.
|
||||
- If not provided, will lookup by name only, which does not work with duplicates.
|
||||
type: str
|
||||
inventory:
|
||||
description:
|
||||
- Inventory to use for the job ran with this workflow, only used if prompt for inventory is set.
|
||||
type: str
|
||||
limit:
|
||||
description:
|
||||
- Limit to use for the I(job_template).
|
||||
type: str
|
||||
scm_branch:
|
||||
description:
|
||||
- A specific branch of the SCM project to run the template on.
|
||||
- This is only applicable if your project allows for branch override.
|
||||
type: str
|
||||
extra_vars:
|
||||
description:
|
||||
- Any extra vars required to launch the job.
|
||||
type: dict
|
||||
wait:
|
||||
description:
|
||||
- Wait for the workflow to complete.
|
||||
default: True
|
||||
type: bool
|
||||
interval:
|
||||
description:
|
||||
- The interval to request an update from Tower.
|
||||
required: False
|
||||
default: 1
|
||||
type: float
|
||||
timeout:
|
||||
description:
|
||||
- If waiting for the workflow to complete this will abort after this
|
||||
amount of seconds
|
||||
type: int
|
||||
extends_documentation_fragment: awx.awx.auth
|
||||
'''
|
||||
|
||||
RETURN = '''
|
||||
job_info:
|
||||
description: dictionary containing information about the workflow executed
|
||||
returned: If workflow launched
|
||||
type: dict
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- name: Launch a workflow with a timeout of 10 seconds
|
||||
tower_workflow_launch:
|
||||
workflow_template: "Test Workflow"
|
||||
timeout: 10
|
||||
|
||||
- name: Launch a Workflow with extra_vars without waiting
|
||||
tower_workflow_launch:
|
||||
workflow_template: "Test workflow"
|
||||
extra_vars:
|
||||
var1: My First Variable
|
||||
var2: My Second Variable
|
||||
wait: False
|
||||
'''
|
||||
|
||||
from ..module_utils.tower_api import TowerAPIModule
|
||||
import json
|
||||
|
||||
|
||||
def main():
|
||||
# Any additional arguments that are not fields of the item can be added here
|
||||
argument_spec = dict(
|
||||
name=dict(required=True, aliases=['workflow_template']),
|
||||
organization=dict(),
|
||||
inventory=dict(),
|
||||
limit=dict(),
|
||||
scm_branch=dict(),
|
||||
extra_vars=dict(type='dict'),
|
||||
wait=dict(required=False, default=True, type='bool'),
|
||||
interval=dict(required=False, default=1.0, type='float'),
|
||||
timeout=dict(required=False, default=None, type='int'),
|
||||
)
|
||||
|
||||
# Create a module for ourselves
|
||||
module = TowerAPIModule(argument_spec=argument_spec)
|
||||
|
||||
optional_args = {}
|
||||
# Extract our parameters
|
||||
name = module.params.get('name')
|
||||
organization = module.params.get('organization')
|
||||
inventory = module.params.get('inventory')
|
||||
optional_args['limit'] = module.params.get('limit')
|
||||
wait = module.params.get('wait')
|
||||
interval = module.params.get('interval')
|
||||
timeout = module.params.get('timeout')
|
||||
|
||||
# Special treatment of extra_vars parameter
|
||||
extra_vars = module.params.get('extra_vars')
|
||||
if extra_vars is not None:
|
||||
optional_args['extra_vars'] = json.dumps(extra_vars)
|
||||
|
||||
# Create a datastructure to pass into our job launch
|
||||
post_data = {}
|
||||
for key in optional_args.keys():
|
||||
if optional_args[key]:
|
||||
post_data[key] = optional_args[key]
|
||||
|
||||
# Attempt to look up the related items the user specified (these will fail the module if not found)
|
||||
if inventory:
|
||||
post_data['inventory'] = module.resolve_name_to_id('inventories', inventory)
|
||||
|
||||
# Attempt to look up job_template based on the provided name
|
||||
lookup_data = {}
|
||||
if organization:
|
||||
lookup_data['organization'] = module.resolve_name_to_id('organizations', organization)
|
||||
workflow_job_template = module.get_one('workflow_job_templates', name_or_id=name, data=lookup_data)
|
||||
|
||||
if workflow_job_template is None:
|
||||
module.fail_json(msg="Unable to find workflow job template")
|
||||
|
||||
# The API will allow you to submit values to a jb launch that are not prompt on launch.
|
||||
# Therefore, we will test to see if anything is set which is not prompt on launch and fail.
|
||||
check_vars_to_prompts = {
|
||||
'inventory': 'ask_inventory_on_launch',
|
||||
'limit': 'ask_limit_on_launch',
|
||||
'scm_branch': 'ask_scm_branch_on_launch',
|
||||
}
|
||||
|
||||
param_errors = []
|
||||
for variable_name in check_vars_to_prompts:
|
||||
if variable_name in post_data and not workflow_job_template[check_vars_to_prompts[variable_name]]:
|
||||
param_errors.append("The field {0} was specified but the workflow job template does not allow for it to be overridden".format(variable_name))
|
||||
# Check if Either ask_variables_on_launch, or survey_enabled is enabled for use of extra vars.
|
||||
if module.params.get('extra_vars') and not (workflow_job_template['ask_variables_on_launch'] or workflow_job_template['survey_enabled']):
|
||||
param_errors.append("The field extra_vars was specified but the workflow job template does not allow for it to be overridden")
|
||||
if len(param_errors) > 0:
|
||||
module.fail_json(msg="Parameters specified which can not be passed into workflow job template, see errors for details", errors=param_errors)
|
||||
|
||||
# Launch the job
|
||||
result = module.post_endpoint(workflow_job_template['related']['launch'], data=post_data)
|
||||
|
||||
if result['status_code'] != 201:
|
||||
module.fail_json(msg="Failed to launch workflow, see response for details", response=result)
|
||||
|
||||
module.json_output['changed'] = True
|
||||
module.json_output['id'] = result['json']['id']
|
||||
module.json_output['status'] = result['json']['status']
|
||||
# This is for backwards compatability
|
||||
module.json_output['job_info'] = {'id': result['json']['id']}
|
||||
|
||||
if not wait:
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
# Invoke wait function
|
||||
module.wait_on_url(
|
||||
url=result['json']['url'],
|
||||
object_name=name,
|
||||
object_type='Workflow Job',
|
||||
timeout=timeout, interval=interval
|
||||
)
|
||||
|
||||
module.exit_json(**module.json_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,230 @@
|
||||
#!/usr/bin/python
|
||||
# coding: utf-8 -*-
|
||||
|
||||
# Copyright: (c) 2018, Adrien Fleury <fleu42@gmail.com>
|
||||
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
|
||||
from __future__ import absolute_import, division, print_function
|
||||
__metaclass__ = type
|
||||
|
||||
|
||||
ANSIBLE_METADATA = {'status': ['deprecated'],
|
||||
'supported_by': 'community',
|
||||
'metadata_version': '1.1'}
|
||||
|
||||
|
||||
DOCUMENTATION = '''
|
||||
---
|
||||
module: tower_workflow_template
|
||||
deprecated:
|
||||
removed_in: "14.0.0"
|
||||
why: Deprecated in favor of C(_workflow_job_template) and C(_workflow_job_template_node) modules.
|
||||
alternative: Use M(tower_workflow_job_template) and M(_workflow_job_template_node) instead.
|
||||
author: "Adrien Fleury (@fleu42)"
|
||||
short_description: create, update, or destroy Ansible Tower workflow template.
|
||||
description:
|
||||
- A tower-cli based module for CRUD actions on workflow job templates.
|
||||
- Enables use of the old schema functionality.
|
||||
- Not updated for new features, convert to the modules for
|
||||
workflow_job_template and workflow_job_template node instead.
|
||||
options:
|
||||
allow_simultaneous:
|
||||
description:
|
||||
- If enabled, simultaneous runs of this job template will be allowed.
|
||||
type: bool
|
||||
ask_extra_vars:
|
||||
description:
|
||||
- Prompt user for (extra_vars) on launch.
|
||||
type: bool
|
||||
ask_inventory:
|
||||
description:
|
||||
- Prompt user for inventory on launch.
|
||||
type: bool
|
||||
description:
|
||||
description:
|
||||
- The description to use for the workflow.
|
||||
type: str
|
||||
extra_vars:
|
||||
description:
|
||||
- Extra variables used by Ansible in YAML or key=value format.
|
||||
type: dict
|
||||
inventory:
|
||||
description:
|
||||
- Name of the inventory to use for the job template.
|
||||
type: str
|
||||
name:
|
||||
description:
|
||||
- The name to use for the workflow.
|
||||
required: True
|
||||
type: str
|
||||
organization:
|
||||
description:
|
||||
- The organization the workflow is linked to.
|
||||
type: str
|
||||
schema:
|
||||
description:
|
||||
- >
|
||||
The schema is a JSON- or YAML-formatted string defining the
|
||||
hierarchy structure that connects the nodes. Refer to Tower
|
||||
documentation for more information.
|
||||
type: list
|
||||
elements: dict
|
||||
survey_enabled:
|
||||
description:
|
||||
- Setting that variable will prompt the user for job type on the
|
||||
workflow launch.
|
||||
type: bool
|
||||
survey:
|
||||
description:
|
||||
- The definition of the survey associated to the workflow.
|
||||
type: dict
|
||||
state:
|
||||
description:
|
||||
- Desired state of the resource.
|
||||
default: "present"
|
||||
choices: ["present", "absent"]
|
||||
type: str
|
||||
|
||||
requirements:
|
||||
- ansible-tower-cli >= 3.0.2
|
||||
|
||||
extends_documentation_fragment: awx.awx.auth_legacy
|
||||
'''
|
||||
|
||||
|
||||
EXAMPLES = '''
|
||||
- tower_workflow_template:
|
||||
name: Workflow Template
|
||||
description: My very first Workflow Template
|
||||
organization: My optional Organization
|
||||
schema: "{{ lookup('file', 'my_workflow.json') }}"
|
||||
|
||||
- tower_workflow_template:
|
||||
name: Workflow Template
|
||||
state: absent
|
||||
'''
|
||||
|
||||
|
||||
RETURN = ''' # '''
|
||||
|
||||
|
||||
from ..module_utils.tower_legacy import (
|
||||
TowerLegacyModule,
|
||||
tower_auth_config,
|
||||
tower_check_mode
|
||||
)
|
||||
|
||||
import json
|
||||
|
||||
try:
|
||||
import tower_cli
|
||||
import tower_cli.exceptions as exc
|
||||
from tower_cli.conf import settings
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
argument_spec = dict(
|
||||
name=dict(required=True),
|
||||
description=dict(),
|
||||
extra_vars=dict(type='dict'),
|
||||
organization=dict(),
|
||||
allow_simultaneous=dict(type='bool'),
|
||||
schema=dict(type='list', elements='dict'),
|
||||
survey=dict(type='dict'),
|
||||
survey_enabled=dict(type='bool'),
|
||||
inventory=dict(),
|
||||
ask_inventory=dict(type='bool'),
|
||||
ask_extra_vars=dict(type='bool'),
|
||||
state=dict(choices=['present', 'absent'], default='present'),
|
||||
)
|
||||
|
||||
module = TowerLegacyModule(
|
||||
argument_spec=argument_spec,
|
||||
supports_check_mode=False
|
||||
)
|
||||
|
||||
module.deprecate(msg=(
|
||||
"This module is replaced by the combination of tower_workflow_job_template and "
|
||||
"tower_workflow_job_template_node. This uses the old tower-cli and wll be "
|
||||
"removed in 2022."
|
||||
), version='awx.awx:14.0.0')
|
||||
|
||||
name = module.params.get('name')
|
||||
state = module.params.get('state')
|
||||
|
||||
schema = None
|
||||
if module.params.get('schema'):
|
||||
schema = module.params.get('schema')
|
||||
|
||||
if schema and state == 'absent':
|
||||
module.fail_json(
|
||||
msg='Setting schema when state is absent is not allowed',
|
||||
changed=False
|
||||
)
|
||||
|
||||
json_output = {'workflow_template': name, 'state': state}
|
||||
|
||||
tower_auth = tower_auth_config(module)
|
||||
with settings.runtime_values(**tower_auth):
|
||||
tower_check_mode(module)
|
||||
wfjt_res = tower_cli.get_resource('workflow')
|
||||
params = {}
|
||||
params['name'] = name
|
||||
|
||||
if module.params.get('description'):
|
||||
params['description'] = module.params.get('description')
|
||||
|
||||
if module.params.get('organization'):
|
||||
organization_res = tower_cli.get_resource('organization')
|
||||
try:
|
||||
organization = organization_res.get(
|
||||
name=module.params.get('organization'))
|
||||
params['organization'] = organization['id']
|
||||
except exc.NotFound as excinfo:
|
||||
module.fail_json(
|
||||
msg='Failed to update organization source,'
|
||||
'organization not found: {0}'.format(excinfo),
|
||||
changed=False
|
||||
)
|
||||
|
||||
if module.params.get('survey'):
|
||||
params['survey_spec'] = module.params.get('survey')
|
||||
|
||||
if module.params.get('ask_extra_vars'):
|
||||
params['ask_variables_on_launch'] = module.params.get('ask_extra_vars')
|
||||
|
||||
if module.params.get('ask_inventory'):
|
||||
params['ask_inventory_on_launch'] = module.params.get('ask_inventory')
|
||||
|
||||
for key in ('allow_simultaneous', 'inventory',
|
||||
'survey_enabled', 'description'):
|
||||
if module.params.get(key):
|
||||
params[key] = module.params.get(key)
|
||||
|
||||
# Special treatment for tower-cli extra_vars
|
||||
extra_vars = module.params.get('extra_vars')
|
||||
if extra_vars:
|
||||
params['extra_vars'] = [json.dumps(extra_vars)]
|
||||
|
||||
try:
|
||||
if state == 'present':
|
||||
params['create_on_missing'] = True
|
||||
result = wfjt_res.modify(**params)
|
||||
json_output['id'] = result['id']
|
||||
if schema:
|
||||
wfjt_res.schema(result['id'], json.dumps(schema))
|
||||
elif state == 'absent':
|
||||
params['fail_on_missing'] = False
|
||||
result = wfjt_res.delete(**params)
|
||||
except (exc.ConnectionError, exc.BadRequest, exc.AuthError) as excinfo:
|
||||
module.fail_json(msg='Failed to update workflow template: \
|
||||
{0}'.format(excinfo), changed=False)
|
||||
|
||||
json_output['changed'] = result['changed']
|
||||
module.exit_json(**json_output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user