Initial commit

This commit is contained in:
Jon Ervine
2021-03-02 20:53:43 +08:00
parent 89d3a2dfe1
commit f961b728fa
2919 changed files with 388582 additions and 0 deletions
@@ -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()