Changing how get_one returns

This commit is contained in:
John Westcott IV 2020-09-08 11:02:25 -04:00
parent 106157c600
commit 0a8db586d1
25 changed files with 76 additions and 100 deletions

View File

@ -25,6 +25,11 @@ class TowerAPIModule(TowerModule):
}
session = None
cookie_jar = CookieJar()
IDENTITY_FIELDS = {
'users': 'username',
'workflow_job_template_nodes': 'identifier',
'instances': 'hostname'
}
def __init__(self, argument_spec, direct_params=None, error_callback=None, warn_callback=None, **kwargs):
kwargs['supports_check_mode'] = True
@ -44,30 +49,20 @@ class TowerAPIModule(TowerModule):
@staticmethod
def get_name_field_from_endpoint(endpoint):
if endpoint == 'users':
return 'username'
elif endpoint == 'instances':
return 'hostname'
return 'name'
return TowerAPIModule.IDENTITY_FIELDS.get(endpoint, 'name')
@staticmethod
def get_item_name(item):
def get_item_name(self, item):
if 'name' in item:
return item['name']
elif 'username' in item:
return item['username']
elif 'identifier' in item:
return item['identifier']
elif 'hostname' in item:
return item['hostname']
elif item.get('type', None) == 'o_auth2_access_token':
# An oauth2 token has no name, instead we will use its id for any of the messages
rerurn item['id']
elif item.get('type', None) == 'credential_input_source':
# An credential_input_source has no name, instead we will use its id for any of the messages
return existing_item['id']
return 'Unknown'
for field_name in TowerAPIModule.IDENTITY_FIELDS.values():
if field_name in item:
return item[field_name]
if item.get('type', None) in ('o_auth2_access_token', 'credential_input_source'):
return item['id']
self.exit_json(msg='Cannot determine identity field for {0} object.'.format(item.get('type', 'unknown')))
def head_endpoint(self, endpoint, *args, **kwargs):
return self.make_request('HEAD', endpoint, **kwargs)
@ -141,18 +136,18 @@ class TowerAPIModule(TowerModule):
self.fail_json(msg="The endpoint did not provide count and results")
if response['json']['count'] == 0:
return None, name_or_id
return None
elif response['json']['count'] > 1:
if name_or_id:
# Since we did a name or ID search and got > 1 return something if the id matches
for asset in response['json']['results']:
if asset['id'] == name_or_id:
return asset, asset['id'][name_field]
return asset
# We got > 1 and either didn't find something by ID (which means multiple names)
# Or we weren't running with a or search and just got back too many to begin with.
self.fail_json(msg="An unexpected number of items was returned from the API ({0})".format(response['json']['count']))
return response['json']['results'][0], response['json']['results'][0][name_field]
return response['json']['results'][0]
def get_one_by_name_or_id(self, endpoint, name_or_id):
name_field = self.get_name_field_from_endpoint(endpoint)

View File

@ -370,7 +370,7 @@ def main():
if organization:
lookup_data['organization'] = org_id
credential, name = module.get_one('credentials', name_or_id=name, **{'data': lookup_data})
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
@ -396,7 +396,7 @@ def main():
# Create the data that gets sent for create and update
credential_fields = {
'name': new_name if new_name else name,
'name': new_name if new_name else (module.get_item_name(credential) if credential else name),
'credential_type': cred_type_id,
}
if has_inputs:

View File

@ -102,7 +102,7 @@ def main():
'target_credential': target_credential_id,
'input_field_name': input_field_name,
}
credential_input_source, junk = module.get_one('credential_input_sources', **{'data': lookup_data})
credential_input_source = module.get_one('credential_input_sources', **{'data': lookup_data})
if state == 'absent':
module.delete_if_needed(credential_input_source)

View File

@ -115,7 +115,6 @@ def main():
# These will be passed into the create/updates
credential_type_params = {
'name': new_name if new_name else name,
'managed_by_tower': False,
}
if kind:
@ -128,12 +127,14 @@ def main():
credential_type_params['injectors'] = module.params.get('injectors')
# Attempt to look up credential_type based on the provided name
credential_type, name = module.get_one('credential_types', name_or_id=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')

View File

@ -108,7 +108,7 @@ def main():
inventory_id = module.resolve_name_to_id('inventories', inventory)
# Attempt to look up the object based on the provided name and inventory ID
group, name = module.get_one('groups', name_or_id=name, **{
group = module.get_one('groups', name_or_id=name, **{
'data': {
'inventory': inventory_id
}
@ -120,7 +120,7 @@ def main():
# Create the data that gets sent for create and update
group_fields = {
'name': new_name if new_name else name,
'name': new_name if new_name else (module.get_item_name(group) if group else name),
'inventory': inventory_id,
}
if description is not None:
@ -135,7 +135,7 @@ def main():
continue
id_list = []
for sub_name in name_list:
sub_obj, sub_name = module.get_one(resource, name_or_id=sub_name, **{
sub_obj = module.get_one(resource, name_or_id=sub_name, **{
'data': {'inventory': inventory_id},
})
if sub_obj is None:

View File

@ -104,7 +104,7 @@ def main():
inventory_id = module.resolve_name_to_id('inventories', inventory)
# Attempt to look up host based on the provided name and inventory ID
host, name = module.get_one('hosts', name_or_id=name, **{
host = module.get_one('hosts', name_or_id=name, **{
'data': {
'inventory': inventory_id
}
@ -116,7 +116,7 @@ def main():
# Create the data that gets sent for create and update
host_fields = {
'name': new_name if new_name else name,
'name': new_name if new_name else (module.get_item_name(host) if host else name),
'inventory': inventory_id,
'enabled': enabled,
}

View File

@ -109,7 +109,7 @@ def main():
state = module.params.get('state')
# Attempt to look up an existing item based on the provided data
existing_item, name = module.get_one('instance_groups', name_or_id=name)
existing_item = module.get_one('instance_groups', name_or_id=name)
if state is 'absent':
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this
@ -127,7 +127,7 @@ def main():
# Create the data that gets sent for create and update
new_fields = {}
new_fields['name'] = new_name if new_name else name
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:

View File

@ -109,7 +109,7 @@ def main():
org_id = module.resolve_name_to_id('organizations', organization)
# Attempt to look up inventory based on the provided name and org ID
inventory, name = module.get_one('inventories', name_or_id=name, **{
inventory = module.get_one('inventories', name_or_id=name, **{
'data': {
'organization': org_id
}
@ -121,7 +121,7 @@ def main():
# Create the data that gets sent for create and update
inventory_fields = {
'name': name,
'name': module.get_item_name(inventory) if inventory else name,
'organization': org_id,
'kind': kind,
'host_filter': host_filter,

View File

@ -128,10 +128,6 @@ options:
- 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
'''
@ -144,7 +140,6 @@ EXAMPLES = '''
credential: previously-created-credential
overwrite: True
update_on_launch: True
organization: Default
source_vars:
private: false
'''
@ -173,7 +168,6 @@ def main():
enabled_value=dict(),
host_filter=dict(),
credential=dict(),
organization=dict(),
overwrite=dict(type='bool'),
overwrite_vars=dict(type='bool'),
custom_virtualenv=dict(),
@ -196,30 +190,22 @@ def main():
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')
<<<<<<< HEAD
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, **{
# Attempt to look up inventory source based on the provided name and inventory ID
inventory_id = module.resolve_name_to_id('inventories', inventory)
inventory_source = module.get_one('inventory_sources', name_or_id=name, **{
'data': {
'inventory': inventory_object['id'],
'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(inventory_source_object)
module.delete_if_needed(inventory_source)
# Attempt to look up associated field items the user specified.
association_fields = {}
@ -244,8 +230,8 @@ def main():
# 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'],
'name': new_name if new_name else (module.get_item_name(inventory_source) if inventory_source else name),
'inventory': inventory_id,
}
# Attempt to look up the related items the user specified (these will fail the module if not found)
@ -274,12 +260,12 @@ def main():
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']:
if state == 'present' and not inventory_source 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
# If the state was present we can let the module build or update the existing inventory_source, this will return on its own
module.create_or_update_if_needed(
inventory_source_object, inventory_source_fields,
inventory_source, inventory_source_fields,
endpoint='inventory_sources', item_type='inventory source',
associations=association_fields
)

View File

@ -68,7 +68,7 @@ def main():
fail_if_not_running = module.params.get('fail_if_not_running')
# Attempt to look up the job based on the provided name
job, job_name = module.get_one('jobs', **{
job = module.get_one('jobs', **{
'data': {
'id': job_id,
}

View File

@ -201,7 +201,7 @@ def main():
post_data['credentials'].append(module.resolve_name_to_id('credentials', credential))
# Attempt to look up job_template based on the provided name
job_template, name = module.get_one('job_templates', name_or_id=name)
job_template = module.get_one('job_templates', name_or_id=name)
if job_template is None:
module.fail_json(msg="Unable to find job template by name {0}".format(name))

View File

@ -419,14 +419,14 @@ def main():
search_fields['organization'] = new_fields['organization'] = organization_id
# Attempt to look up an existing item based on the provided data
existing_item, name = module.get_one('job_templates', name_or_id=name, **{'data': search_fields})
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 name
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',

View File

@ -130,7 +130,7 @@ def main():
)
# Attempt to look up job based on the provided id
job, junk = module.get_one('jobs', **{
job = module.get_one('jobs', **{
'data': {
'id': job_id,
}

View File

@ -80,7 +80,7 @@ def main():
organization_id = module.resolve_name_to_id('organizations', organization)
# Attempt to look up an existing item based on the provided data
existing_item, name = module.get_one('labels', name_or_id=name, **{
existing_item = module.get_one('labels', name_or_id=name, **{
'data': {
'organization': organization_id,
}
@ -88,7 +88,7 @@ def main():
# Create the data that gets sent for create and update
new_fields = {}
new_fields['name'] = new_name if new_name else name
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

View File

@ -380,7 +380,7 @@ def main():
organization_id = module.resolve_name_to_id('organizations', organization)
# Attempt to look up an existing item based on the provided data
existing_item, name = module.get_one('notification_templates', name_or_id=name, **{
existing_item = module.get_one('notification_templates', name_or_id=name, **{
'data': {
'organization': organization_id,
}
@ -403,7 +403,7 @@ def main():
new_fields = {}
if final_notification_configuration:
new_fields['notification_configuration'] = final_notification_configuration
new_fields['name'] = new_name if new_name else name
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:

View File

@ -117,7 +117,7 @@ def main():
state = module.params.get('state')
# Attempt to look up organization based on the provided name
organization, name = module.get_one('organizations', name_or_id=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
@ -150,7 +150,7 @@ def main():
association_fields['notification_templates_approvals'].append(module.resolve_name_to_id('notification_templates', item))
# Create the data that gets sent for create and update
org_fields = {'name': name}
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:

View File

@ -239,7 +239,7 @@ def main():
credential = module.resolve_name_to_id('credentials', credential)
# Attempt to look up project based on the provided name and org ID
project, name = module.get_one('projects', name_or_id=name, **{
project = module.get_one('projects', name_or_id=name, **{
'data': {
'organization': org_id
}
@ -272,7 +272,7 @@ def main():
# Create the data that gets sent for create and update
project_fields = {
'name': name,
'name': module.get_item_name(project) if project else name,
'scm_type': scm_type,
'scm_url': scm_url,
'scm_branch': scm_branch,

View File

@ -103,18 +103,12 @@ def main():
timeout = module.params.get('timeout')
# Attempt to look up project based on the provided name or id
if name.isdigit():
results = module.get_endpoint('projects', **{'data': {'id': name}})
if results['json']['count'] == 0:
module.fail_json(msg='Could not find Project with ID: {0}'.format(name))
project = results['json']['results'][0]
else:
lookup_data = {}
if organization:
lookup_data['organization'] = module.resolve_name_to_id('organizations', organization)
project, name = module.get_one('projects', name_or_id=name, data=lookup_data)
if project is None:
module.fail_json(msg="Unable to find project")
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'])
@ -138,7 +132,7 @@ def main():
# Invoke wait function
module.wait_on_url(
url=result['json']['url'],
object_name=name,
object_name=module.get_item_name(project),
object_type='Project Update',
timeout=timeout, interval=interval
)

View File

@ -190,13 +190,13 @@ def main():
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, name = module.get_one('schedules', name_or_id=name)
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 name
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:

View File

@ -87,7 +87,7 @@ def main():
org_id = module.resolve_name_to_id('organizations', organization)
# Attempt to look up team based on the provided name and org ID
team, name = module.get_one('teams', name_or_id=name, **{
team = module.get_one('teams', name_or_id=name, **{
'data': {
'organization': org_id
}
@ -99,7 +99,7 @@ def main():
# Create the data that gets sent for create and update
team_fields = {
'name': new_name if new_name else name,
'name': new_name if new_name else (module.get_item_name(team) if team else name),
'organization': org_id
}
if description is not None:

View File

@ -164,7 +164,7 @@ def main():
if state == 'absent':
if not existing_token:
existing_token, token_name = module.get_one('tokens', **{
existing_token = module.get_one('tokens', **{
'data': {
'id': existing_token_id,
}

View File

@ -134,7 +134,7 @@ def main():
# 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, username = module.get_one('users', name_or_id=username)
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
@ -143,7 +143,7 @@ def main():
# Create the data that gets sent for create and update
new_fields = {}
if username:
new_fields['username'] = username
new_fields['username'] = module.get_item_name(existing_item) if existing_item else name
if first_name:
new_fields['first_name'] = first_name
if last_name:

View File

@ -193,7 +193,7 @@ def main():
search_fields['organization'] = new_fields['organization'] = organization_id
# Attempt to look up an existing item based on the provided data
existing_item, name = module.get_one('workflow_job_templates', name_or_id=name, **{'data': search_fields})
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
@ -208,7 +208,7 @@ def main():
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 name
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',

View File

@ -203,7 +203,7 @@ def main():
if organization:
organization_id = module.resolve_name_to_id('organizations', organization)
wfjt_search_fields['organization'] = organization_id
wfjt_data, workflow_job_template = module.get_one('workflow_job_templates', name_or_id=workflow_job_template, **{
wfjt_data = module.get_one('workflow_job_templates', name_or_id=workflow_job_template, **{
'data': wfjt_search_fields
})
if wfjt_data is None:
@ -214,7 +214,7 @@ def main():
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, junk = module.get_one('workflow_job_template_nodes', **{'data': search_fields})
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
@ -251,7 +251,7 @@ def main():
lookup_data = {'identifier': sub_name}
if workflow_job_template_id:
lookup_data['workflow_job_template'] = workflow_job_template_id
sub_obj, junk = module.get_one(endpoint, **{'data': lookup_data})
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'])

View File

@ -141,7 +141,7 @@ def main():
lookup_data = {}
if organization:
lookup_data['organization'] = module.resolve_name_to_id('organizations', organization)
workflow_job_template, name = module.get_one('workflow_job_templates', name_or_id=name, data=lookup_data)
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")