Adding team_fields

Convert job_list and inventory modules, other changes to make sanity tests pass
This commit is contained in:
John Westcott IV
2020-01-21 14:44:19 -05:00
committed by beeankha
parent ceb6f6c47d
commit 68926dad27
9 changed files with 190 additions and 119 deletions

View File

@@ -64,6 +64,11 @@ options:
default: "present"
choices: ["present", "absent"]
type: str
tower_oauthtoken:
description:
- The Tower OAuth token to use.
required: False
type: str
extends_documentation_fragment: awx.awx.auth
'''
@@ -100,19 +105,20 @@ KIND_CHOICES = {
def main():
module = TowerModule(
argument_spec = dict(
name=dict(required=True),
description=dict(required=False),
kind=dict(required=False, choices=KIND_CHOICES.keys()),
inputs=dict(type='dict', required=False),
injectors=dict(type='dict', required=False),
state=dict(choices=['present', 'absent'], default='present'),
),
supports_check_mode=True
# Any additional arguments that are not fields of the item can be added here
argument_spec = dict(
name=dict(required=True),
description=dict(required=False),
kind=dict(required=False, choices=KIND_CHOICES.keys()),
inputs=dict(type='dict', required=False),
injectors=dict(type='dict', required=False),
state=dict(choices=['present', 'absent'], default='present'),
)
# Create a module for ourselves
module = TowerModule(argument_spec=argument_spec, supports_check_mode=True)
# Extract our parameters
name = module.params.get('name')
new_name = None
kind = module.params.get('kind')
@@ -160,5 +166,6 @@ def main():
# This will handle existing on its own
module.update_if_needed(credential_type, credental_type_params)
if __name__ == '__main__':
main()

View File

@@ -59,6 +59,11 @@ options:
default: "present"
choices: ["present", "absent"]
type: str
tower_oauthtoken:
description:
- The Tower OAuth token to use.
required: False
type: str
extends_documentation_fragment: awx.awx.auth
'''
@@ -74,30 +79,25 @@ EXAMPLES = '''
'''
from ..module_utils.ansible_tower import TowerModule, tower_auth_config, tower_check_mode
try:
import tower_cli
import tower_cli.exceptions as exc
from tower_cli.conf import settings
except ImportError:
pass
from ..module_utils.tower_api import TowerModule
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(),
description=dict(default=''),
organization=dict(required=True),
variables=dict(),
variables=dict(default=''),
kind=dict(choices=['', 'smart'], default=''),
host_filter=dict(),
state=dict(choices=['present', 'absent'], default='present'),
)
# Create a module for ourselves
module = TowerModule(argument_spec=argument_spec, supports_check_mode=True)
# Extract our parameters
name = module.params.get('name')
description = module.params.get('description')
organization = module.params.get('organization')
@@ -106,31 +106,43 @@ def main():
kind = module.params.get('kind')
host_filter = module.params.get('host_filter')
json_output = {'inventory': name, 'state': state}
# Attempt to lookup the related items the user specified (these will fail the module if not found)
org_id = module.resolve_name_to_id('organizations', organization)
tower_auth = tower_auth_config(module)
with settings.runtime_values(**tower_auth):
tower_check_mode(module)
inventory = tower_cli.get_resource('inventory')
# Attempt to lookup inventory based on the provided name and org ID
inventory = module.get_one('inventories', **{
'data': {
'name': name,
'organization': org_id
}
})
try:
org_res = tower_cli.get_resource('organization')
org = org_res.get(name=organization)
# Create data to sent to create and update
inventory_fields = {
'name': name,
'description': description,
'organization': org_id,
'variables': variables,
'kind': kind,
'host_filter': host_filter,
}
if state == 'present':
result = inventory.modify(name=name, organization=org['id'], variables=variables,
description=description, kind=kind, host_filter=host_filter,
create_on_missing=True)
json_output['id'] = result['id']
elif state == 'absent':
result = inventory.delete(name=name, organization=org['id'])
except (exc.NotFound) as excinfo:
module.fail_json(msg='Failed to update inventory, organization not found: {0}'.format(excinfo), changed=False)
except (exc.ConnectionError, exc.BadRequest, exc.AuthError) as excinfo:
module.fail_json(msg='Failed to update inventory: {0}'.format(excinfo), changed=False)
json_output['changed'] = result['changed']
module.exit_json(**json_output)
if state == 'absent' and not inventory:
# If the state was absent and we had no inventory, we can just return
module.exit_json(**module.json_output)
elif state == 'absent' and inventory:
# If the state was absent and we had a inventory, we can try to delete it, the module will handle exiting from this
module.delete_endpoint('inventories/{0}'.format(inventory['id']), item_type='inventory', item_name=name, **{})
elif state == 'present' and not inventory:
# If the state was present and we couldn't find a inventory we can build one, the module will handle exiting from this
module.post_endpoint('inventories', item_type='inventory', item_name=name, **{'data': inventory_fields})
else:
# Throw a more specific error message than what the API page provides.
if 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 had a inventory, we can see if we need to update it
# This will return on its own
module.update_if_needed(inventory, inventory_fields)
if __name__ == '__main__':

View File

@@ -41,6 +41,11 @@ options:
description:
- Query used to further filter the list of jobs. C({"foo":"bar"}) will be passed at C(?foo=bar)
type: dict
tower_oauthtoken:
description:
- The Tower OAuth token to use.
required: False
type: str
extends_documentation_fragment: awx.awx.auth
'''
@@ -81,18 +86,11 @@ results:
'''
from ..module_utils.ansible_tower import TowerModule, tower_auth_config, tower_check_mode
try:
import tower_cli
import tower_cli.exceptions as exc
from tower_cli.conf import settings
except ImportError:
pass
from ..module_utils.tower_api import TowerModule
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'),
@@ -100,31 +98,35 @@ def main():
query=dict(type='dict'),
)
# Create a module for ourselves
module = TowerModule(
argument_spec=argument_spec,
supports_check_mode=True
supports_check_mode=True,
mutually_exclusive=[
('page', 'all_pages'),
]
)
json_output = {}
# 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')
tower_auth = tower_auth_config(module)
with settings.runtime_values(**tower_auth):
tower_check_mode(module)
try:
job = tower_cli.get_resource('job')
params = {'status': status, 'page': page, 'all_pages': all_pages}
if query:
params['query'] = query.items()
json_output = job.list(**params)
except (exc.ConnectionError, exc.BadRequest, exc.AuthError) as excinfo:
module.fail_json(msg='Failed to list jobs: {0}'.format(excinfo), changed=False)
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})
module.exit_json(**json_output)
# Attempt to lookup jobs based on the status
module.exit_json(**job_list['json'])
if __name__ == '__main__':

View File

@@ -14,7 +14,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
DOCUMENTATION = '''
---
module: license
module: tower_license
author: "John Westcott IV (@john-westcott-iv)"
version_added: "2.9"
short_description: Set the license for Ansible Tower
@@ -26,6 +26,17 @@ options:
description:
- The contents of the license file
required: True
type: dict
eula_accepted:
description:
- Whether or not the EULA is accepted.
required: True
type: bool
tower_oauthtoken:
description:
- The Tower OAuth token to use.
required: False
type: str
extends_documentation_fragment: awx.awx.auth
'''
@@ -35,6 +46,7 @@ EXAMPLES = '''
- name: Set the license using a file
license:
data: "{{ lookup('file', '/tmp/my_tower.license') }}"
eula_accepted: True
'''
from ..module_utils.tower_api import TowerModule
@@ -74,4 +86,3 @@ def main():
if __name__ == '__main__':
main()

View File

@@ -51,14 +51,13 @@ options:
default: "present"
choices: ["present", "absent"]
type: str
tower_oauthtoken:
description:
- The Tower OAuth token to use.
required: False
type: str
extends_documentation_fragment: awx.awx.auth
'''
# instance_groups:
# description:
# - The name of instance groups to tie to this organization
# type: list
# default: []
# required: False
EXAMPLES = '''
@@ -88,10 +87,21 @@ def main():
description=dict(type='str', required=False),
custom_virtualenv=dict(type='str', required=False),
max_hosts=dict(type='str', required=False, default="0"),
# instance_groups=dict(type='list', required=False, default=[]),
state=dict(type='str', choices=['present', 'absent'], default='present', required=False),
)
# instance_groups=dict(type='list', required=False, default=[]),
# The above argument_spec fragment is being left in for reference since we may need
# it later when finalizing the changes.
# instance_groups:
# description:
# - The name of instance groups to tie to this organization
# default: []
# required: False
# The above docstring fragment is being left in for reference since we may need
# it later when finalizing the changes.
# Create a module for ourselves
module = TowerModule(argument_spec=argument_spec, supports_check_mode=True)
@@ -115,7 +125,7 @@ def main():
}
})
new_org_data = { 'name': name }
new_org_data = {'name': name}
if description:
new_org_data['description'] = description
if custom_virtualenv:
@@ -137,7 +147,7 @@ def main():
# If the state was absent and we had a organization, we can try to delete it, the module will handle exiting from this
module.delete_endpoint('organizations/{0}'.format(organization['id']), item_type='organization', item_name=name, **{})
elif state == 'present' and not organization:
# if the state was present and we couldn't find a organization we can build one, the module wikl handle exiting from this
# if the state was present and we couldn't find a organization we can build one, the module will handle exiting from this
module.post_endpoint('organizations', item_type='organization', item_name=name, **{
'data': new_org_data,
})
@@ -146,5 +156,6 @@ def main():
# This will return on its own
module.update_if_needed(organization, new_org_data)
if __name__ == '__main__':
main()

View File

@@ -38,6 +38,11 @@ options:
- A data structure to be sent into the settings endpoint
required: False
type: dict
tower_oauthtoken:
description:
- The Tower OAuth token to use.
required: False
type: str
extends_documentation_fragment: awx.awx.auth
'''
@@ -66,11 +71,10 @@ EXAMPLES = '''
tower_settings:
settings:
AUTH_LDAP_BIND_PASSWORD: "password"
AUTH_LDAP_USER_ATTR_MAP:
AUTH_LDAP_USER_ATTR_MAP:
email: "mail"
first_name: "givenName"
last_name: "surname"
...
'''
from ..module_utils.tower_api import TowerModule
@@ -78,20 +82,21 @@ from json import loads
from json.decoder import JSONDecodeError
import re
def main():
# Any additional arguments that are not fields of the item can be added here
argument_spec = dict(
name=dict(required=False),
value=dict(required=False),
settings=dict(required=False,type='dict'),
settings=dict(required=False, type='dict'),
)
# Create a module for ourselves
module = TowerModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_one_of=[['name','settings']],
mutually_exclusive=[['name','settings']],
required_one_of=[['name', 'settings']],
mutually_exclusive=[['name', 'settings']],
required_if=[['name', 'present', ['value']]]
)
@@ -101,22 +106,22 @@ def main():
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 == None:
if new_settings is None:
new_value = value
try:
new_value = loads(value)
except JSONDecodeError as e:
# Attempt to deal with old tower_cli array types
if ',' in value:
new_value = re.split(",\s+", new_value)
new_settings = { name: new_value }
new_value = re.split(r",\s+", new_value)
new_settings = {name: new_value}
# Load the existing settings
existing_settings = module.get_endpoint('settings/all')['json']
# Begin a json response
json_response = { 'changed': False, 'old_values': {} }
json_response = {'changed': False, 'old_values': {}}
# Check any of the settings to see if anything needs to be updated
needs_update = False
@@ -124,7 +129,7 @@ def main():
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_response['old_values'][ a_setting ] = existing_settings[a_setting]
json_response['old_values'][a_setting] = existing_settings[a_setting]
# If nothing needs an update we can simply exit with the response (as not changed)
if not needs_update:
@@ -143,7 +148,7 @@ def main():
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 != None:
if name is not None:
json_response['value'] = new_values[name]
else:
json_response['values'] = new_values
@@ -154,5 +159,6 @@ def main():
else:
module.fail_json(**{'msg': "Unable to update settings, see response", 'response': response})
if __name__ == '__main__':
main()

View File

@@ -28,6 +28,11 @@ options:
- Name to use for the team.
required: True
type: str
new_name:
description:
- To use when changing a team's name.
required: True
type: str
description:
description:
- The description to use for the team.
@@ -43,6 +48,11 @@ options:
choices: ["present", "absent"]
default: "present"
type: str
tower_oauthtoken:
description:
- The Tower OAuth token to use.
required: False
type: str
extends_documentation_fragment: awx.awx.auth
'''
@@ -91,6 +101,13 @@ def main():
}
})
# Create data to sent to create and update
team_fields = {
'name': name,
'description': description,
'organization': org_id
}
if state == 'absent' and not team:
# If the state was absent and we had no team, we can just return
module.exit_json(**module.json_output)
@@ -98,23 +115,11 @@ def main():
# If the state was absent and we had a team, we can try to delete it, the module will handle exiting from this
module.delete_endpoint('teams/{0}'.format(team['id']), item_type='team', item_name=name, **{})
elif state == 'present' and not team:
# if the state was present and we couldn't find a team we can build one, the module wikl handle exiting from this
module.post_endpoint('teams', item_type='team', item_name=name, **{
'data': {
'name': name,
'description': description,
'organization': org_id
}
})
# if the state was present and we couldn't find a team we can build one, the module will handle exiting from this
module.post_endpoint('teams', item_type='team', item_name=name, **{'data': team_fields})
else:
# If the state was present and we had a team we can see if we need to update it
# This will return on its own
team_fields = {
'name': new_name if new_name else name,
'description': description,
'organization': org_id,
}
module.update_if_needed(team, team_fields)

View File

@@ -61,7 +61,11 @@ options:
default: "present"
choices: ["present", "absent"]
type: str
tower_oauthtoken:
description:
- The Tower OAuth token to use.
required: False
type: str
extends_documentation_fragment: awx.awx.auth
'''
@@ -105,6 +109,7 @@ EXAMPLES = '''
from ..module_utils.tower_api import TowerModule
def main():
# Any additional arguments that are not fields of the item can be added here
argument_spec = dict(
@@ -147,7 +152,7 @@ def main():
# If the state was absent and we had a user, we can try to delete it, the module will handle exiting from this
module.delete_endpoint('users/{0}'.format(user['id']), item_type='user', item_name=user_fields['username'], **{})
elif state == 'present' and not user:
# if the state was present and we couldn't find a user we can build one, the module wikl handle exiting from this
# if the state was present and we couldn't find a user we can build one, the module will handle exiting from this
module.post_endpoint('users', item_type='user', item_name=user_fields['username'], **{
'data': user_fields
})
@@ -156,5 +161,6 @@ def main():
# This will return on its own
module.update_if_needed(user, user_fields)
if __name__ == '__main__':
main()