Merge pull request #8072 from john-westcott-iv/get_one_fix

Modify get_one method to allow IDs in addition to names

Reviewed-by: https://github.com/apps/softwarefactory-project-zuul
This commit is contained in:
softwarefactory-project-zuul[bot]
2020-09-08 21:30:59 +00:00
committed by GitHub
32 changed files with 243 additions and 231 deletions

View File

@@ -25,6 +25,11 @@ class TowerAPIModule(TowerModule):
} }
session = None session = None
cookie_jar = CookieJar() 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): def __init__(self, argument_spec, direct_params=None, error_callback=None, warn_callback=None, **kwargs):
kwargs['supports_check_mode'] = True kwargs['supports_check_mode'] = True
@@ -42,6 +47,30 @@ class TowerAPIModule(TowerModule):
} }
return exceptions.get(name, '{0}s'.format(name)) return exceptions.get(name, '{0}s'.format(name))
@staticmethod
def get_name_field_from_endpoint(endpoint):
return TowerAPIModule.IDENTITY_FIELDS.get(endpoint, 'name')
def get_item_name(self, item, allow_unknown=False):
if item:
if 'name' in item:
return item['name']
for field_name in TowerAPIModule.IDENTITY_FIELDS.values():
if field_name in item:
return item[field_name]
if item.get('type', None) in ('o_auth2_access_token', 'credential_input_source'):
return item['id']
if allow_unknown:
return 'unknown'
if item:
self.exit_json(msg='Cannot determine identity field for {0} object.'.format(item.get('type', 'unknown')))
else:
self.exit_json(msg='Cannot determine identity field for Undefined object.')
def head_endpoint(self, endpoint, *args, **kwargs): def head_endpoint(self, endpoint, *args, **kwargs):
return self.make_request('HEAD', endpoint, **kwargs) return self.make_request('HEAD', endpoint, **kwargs)
@@ -88,7 +117,21 @@ class TowerAPIModule(TowerModule):
response['json']['next'] = next_page response['json']['next'] = next_page
return response return response
def get_one(self, endpoint, *args, **kwargs): def get_one(self, endpoint, name_or_id=None, *args, **kwargs):
if name_or_id:
name_field = self.get_name_field_from_endpoint(endpoint)
new_args = kwargs.get('data', {}).copy()
if name_field in new_args:
self.fail_json(msg="You can't specify the field {0} in your search data if using the name_or_id field".format(name_field))
new_args['or__{0}'.format(name_field)] = name_or_id
try:
new_args['or__id'] = int(name_or_id)
except ValueError:
# If we get a value error, then we didn't have an integer so we can just pass and fall down to the fail
pass
kwargs['data'] = new_args
response = self.get_endpoint(endpoint, *args, **kwargs) response = self.get_endpoint(endpoint, *args, **kwargs)
if response['status_code'] != 200: if response['status_code'] != 200:
fail_msg = "Got a {0} response when trying to get one from {1}".format(response['status_code'], endpoint) fail_msg = "Got a {0} response when trying to get one from {1}".format(response['status_code'], endpoint)
@@ -102,16 +145,19 @@ class TowerAPIModule(TowerModule):
if response['json']['count'] == 0: if response['json']['count'] == 0:
return None return None
elif response['json']['count'] > 1: 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
# 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'])) self.fail_json(msg="An unexpected number of items was returned from the API ({0})".format(response['json']['count']))
return response['json']['results'][0] return response['json']['results'][0]
def get_one_by_name_or_id(self, endpoint, name_or_id): def get_one_by_name_or_id(self, endpoint, name_or_id):
name_field = 'name' name_field = self.get_name_field_from_endpoint(endpoint)
if endpoint == 'users':
name_field = 'username'
elif endpoint == 'instances':
name_field = 'hostname'
query_params = {'or__{0}'.format(name_field): name_or_id} query_params = {'or__{0}'.format(name_field): name_or_id}
try: try:
@@ -319,24 +365,10 @@ class TowerAPIModule(TowerModule):
item_url = existing_item['url'] item_url = existing_item['url']
item_type = existing_item['type'] item_type = existing_item['type']
item_id = existing_item['id'] item_id = existing_item['id']
item_name = self.get_item_name(existing_item, allow_unknown=True)
except KeyError as ke: except KeyError as ke:
self.fail_json(msg="Unable to process delete of item due to missing data {0}".format(ke)) self.fail_json(msg="Unable to process delete of item due to missing data {0}".format(ke))
if 'name' in existing_item:
item_name = existing_item['name']
elif 'username' in existing_item:
item_name = existing_item['username']
elif 'identifier' in existing_item:
item_name = existing_item['identifier']
elif item_type == 'o_auth2_access_token':
# An oauth2 token has no name, instead we will use its id for any of the messages
item_name = existing_item['id']
elif item_type == 'credential_input_source':
# An credential_input_source has no name, instead we will use its id for any of the messages
item_name = existing_item['id']
else:
self.fail_json(msg="Unable to process delete of {0} due to missing name".format(item_type))
response = self.delete_endpoint(item_url) response = self.delete_endpoint(item_url)
if response['status_code'] in [202, 204]: if response['status_code'] in [202, 204]:
@@ -409,12 +441,7 @@ class TowerAPIModule(TowerModule):
# We have to rely on item_type being passed in since we don't have an existing item that declares its type # We have to rely on item_type being passed in since we don't have an existing item that declares its type
# We will pull the item_name out from the new_item, if it exists # We will pull the item_name out from the new_item, if it exists
for key in ('name', 'username', 'identifier', 'hostname'): item_name = self.get_item_name(new_item, allow_unknown=True)
if key in new_item:
item_name = new_item[key]
break
else:
item_name = 'unknown'
response = self.post_endpoint(endpoint, **{'data': new_item}) response = self.post_endpoint(endpoint, **{'data': new_item})
if response['status_code'] == 201: if response['status_code'] == 201:

View File

@@ -365,13 +365,12 @@ def main():
# Attempt to look up the object based on the provided name, credential type and optional organization # Attempt to look up the object based on the provided name, credential type and optional organization
lookup_data = { lookup_data = {
'name': name,
'credential_type': cred_type_id, 'credential_type': cred_type_id,
} }
if organization: if organization:
lookup_data['organization'] = org_id lookup_data['organization'] = org_id
credential = module.get_one('credentials', **{'data': lookup_data}) credential = module.get_one('credentials', name_or_id=name, **{'data': lookup_data})
if state == 'absent': if state == 'absent':
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this # If the state was absent we can let the module delete it if needed, the module will handle exiting from this
@@ -397,7 +396,7 @@ def main():
# Create the data that gets sent for create and update # Create the data that gets sent for create and update
credential_fields = { 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, 'credential_type': cred_type_id,
} }
if has_inputs: if has_inputs:

View File

@@ -115,7 +115,6 @@ def main():
# These will be passed into the create/updates # These will be passed into the create/updates
credential_type_params = { credential_type_params = {
'name': new_name if new_name else name,
'managed_by_tower': False, 'managed_by_tower': False,
} }
if kind: if kind:
@@ -128,16 +127,14 @@ def main():
credential_type_params['injectors'] = module.params.get('injectors') credential_type_params['injectors'] = module.params.get('injectors')
# Attempt to look up credential_type based on the provided name # Attempt to look up credential_type based on the provided name
credential_type = module.get_one('credential_types', **{ credential_type = module.get_one('credential_types', name_or_id=name)
'data': {
'name': name,
}
})
if state == 'absent': if state == 'absent':
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this # 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) 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 # 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') module.create_or_update_if_needed(credential_type, credential_type_params, endpoint='credential_types', item_type='credential type')

View File

@@ -108,9 +108,8 @@ def main():
inventory_id = module.resolve_name_to_id('inventories', inventory) inventory_id = module.resolve_name_to_id('inventories', inventory)
# Attempt to look up the object based on the provided name and inventory ID # Attempt to look up the object based on the provided name and inventory ID
group = module.get_one('groups', **{ group = module.get_one('groups', name_or_id=name, **{
'data': { 'data': {
'name': name,
'inventory': inventory_id 'inventory': inventory_id
} }
}) })
@@ -121,7 +120,7 @@ def main():
# Create the data that gets sent for create and update # Create the data that gets sent for create and update
group_fields = { 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, 'inventory': inventory_id,
} }
if description is not None: if description is not None:
@@ -136,8 +135,8 @@ def main():
continue continue
id_list = [] id_list = []
for sub_name in name_list: for sub_name in name_list:
sub_obj = module.get_one(resource, **{ sub_obj = module.get_one(resource, name_or_id=sub_name, **{
'data': {'inventory': inventory_id, 'name': sub_name} 'data': {'inventory': inventory_id},
}) })
if sub_obj is None: if sub_obj is None:
module.fail_json(msg='Could not find {0} with name {1}'.format(resource, sub_name)) module.fail_json(msg='Could not find {0} with name {1}'.format(resource, sub_name))

View File

@@ -104,9 +104,8 @@ def main():
inventory_id = module.resolve_name_to_id('inventories', inventory) inventory_id = module.resolve_name_to_id('inventories', inventory)
# Attempt to look up host based on the provided name and inventory ID # Attempt to look up host based on the provided name and inventory ID
host = module.get_one('hosts', **{ host = module.get_one('hosts', name_or_id=name, **{
'data': { 'data': {
'name': name,
'inventory': inventory_id 'inventory': inventory_id
} }
}) })
@@ -117,7 +116,7 @@ def main():
# Create the data that gets sent for create and update # Create the data that gets sent for create and update
host_fields = { 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, 'inventory': inventory_id,
'enabled': enabled, 'enabled': enabled,
} }

View File

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

View File

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

View File

@@ -202,17 +202,16 @@ def main():
source_project = module.params.get('source_project') source_project = module.params.get('source_project')
state = module.params.get('state') state = module.params.get('state')
lookup_data = {'name': inventory} lookup_data = {}
if organization: if organization:
lookup_data['organization'] = module.resolve_name_to_id('organizations', organization) lookup_data['organization'] = module.resolve_name_to_id('organizations', organization)
inventory_object = module.get_one('inventories', data=lookup_data) inventory_object = module.get_one('inventories', name_or_id=inventory, data=lookup_data)
if not inventory_object: if not inventory_object:
module.fail_json(msg='The specified inventory, {0}, was not found.'.format(lookup_data)) module.fail_json(msg='The specified inventory, {0}, was not found.'.format(lookup_data))
inventory_source_object = module.get_one('inventory_sources', **{ inventory_source_object = module.get_one('inventory_sources', name_or_id=name, **{
'data': { 'data': {
'name': name,
'inventory': inventory_object['id'], 'inventory': inventory_object['id'],
} }
}) })

View File

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

View File

@@ -409,7 +409,7 @@ def main():
credentials.append(credential) credentials.append(credential)
new_fields = {} new_fields = {}
search_fields = {'name': name} search_fields = {}
# Attempt to look up the related items the user specified (these will fail the module if not found) # Attempt to look up the related items the user specified (these will fail the module if not found)
organization_id = None organization_id = None
@@ -419,14 +419,14 @@ def main():
search_fields['organization'] = new_fields['organization'] = organization_id search_fields['organization'] = new_fields['organization'] = organization_id
# Attempt to look up an existing item based on the provided data # Attempt to look up an existing item based on the provided data
existing_item = module.get_one('job_templates', **{'data': search_fields}) existing_item = module.get_one('job_templates', name_or_id=name, **{'data': search_fields})
if state == 'absent': if state == 'absent':
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this # 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) module.delete_if_needed(existing_item)
# Create the data that gets sent for create and update # 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 ( for field_name in (
'description', 'job_type', 'playbook', 'scm_branch', 'forks', 'limit', 'verbosity', 'description', 'job_type', 'playbook', 'scm_branch', 'forks', 'limit', 'verbosity',
'job_tags', 'force_handlers', 'skip_tags', 'start_at_task', 'timeout', 'use_fact_cache', 'job_tags', 'force_handlers', 'skip_tags', 'start_at_task', 'timeout', 'use_fact_cache',
@@ -453,9 +453,8 @@ def main():
new_fields['inventory'] = module.resolve_name_to_id('inventories', inventory) new_fields['inventory'] = module.resolve_name_to_id('inventories', inventory)
if project is not None: if project is not None:
if organization_id is not None: if organization_id is not None:
project_data = module.get_one('projects', **{ project_data = module.get_one('projects', name_or_id=project, **{
'data': { 'data': {
'name': project,
'organization': organization_id, 'organization': organization_id,
} }
}) })

View File

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

View File

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

View File

@@ -117,11 +117,7 @@ def main():
state = module.params.get('state') state = module.params.get('state')
# Attempt to look up organization based on the provided name # Attempt to look up organization based on the provided name
organization = module.get_one('organizations', **{ organization = module.get_one('organizations', name_or_id=name)
'data': {
'name': name,
}
})
if state == 'absent': if state == 'absent':
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this # If the state was absent we can let the module delete it if needed, the module will handle exiting from this
@@ -154,7 +150,7 @@ def main():
association_fields['notification_templates_approvals'].append(module.resolve_name_to_id('notification_templates', item)) association_fields['notification_templates_approvals'].append(module.resolve_name_to_id('notification_templates', item))
# Create the data that gets sent for create and update # 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: if description is not None:
org_fields['description'] = description org_fields['description'] = description
if custom_virtualenv is not None: if custom_virtualenv is not None:

View File

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

View File

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

View File

@@ -190,17 +190,13 @@ def main():
unified_job_template_id = module.resolve_name_to_id('unified_job_templates', 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 # Attempt to look up an existing item based on the provided data
existing_item = module.get_one('schedules', **{ existing_item = module.get_one('schedules', name_or_id=name)
'data': {
'name': name,
}
})
# Create the data that gets sent for create and update # Create the data that gets sent for create and update
new_fields = {} new_fields = {}
if rrule is not None: if rrule is not None:
new_fields['rrule'] = rrule 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: if description is not None:
new_fields['description'] = description new_fields['description'] = description
if extra_data is not None: if extra_data is not None:

View File

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

View File

@@ -134,11 +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 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 # Attempt to look up an existing item based on the provided data
existing_item = module.get_one('users', **{ existing_item = module.get_one('users', name_or_id=username)
'data': {
'username': username,
}
})
if state == 'absent': if state == 'absent':
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this # If the state was absent we can let the module delete it if needed, the module will handle exiting from this
@@ -147,7 +143,7 @@ def main():
# Create the data that gets sent for create and update # Create the data that gets sent for create and update
new_fields = {} new_fields = {}
if username: if username:
new_fields['username'] = username new_fields['username'] = module.get_item_name(existing_item) if existing_item else username
if first_name: if first_name:
new_fields['first_name'] = first_name new_fields['first_name'] = first_name
if last_name: if last_name:

View File

@@ -184,7 +184,7 @@ def main():
state = module.params.get('state') state = module.params.get('state')
new_fields = {} new_fields = {}
search_fields = {'name': name} search_fields = {}
# Attempt to look up the related items the user specified (these will fail the module if not found) # Attempt to look up the related items the user specified (these will fail the module if not found)
organization = module.params.get('organization') organization = module.params.get('organization')
@@ -193,7 +193,7 @@ def main():
search_fields['organization'] = new_fields['organization'] = organization_id search_fields['organization'] = new_fields['organization'] = organization_id
# Attempt to look up an existing item based on the provided data # Attempt to look up an existing item based on the provided data
existing_item = module.get_one('workflow_job_templates', **{'data': search_fields}) existing_item = module.get_one('workflow_job_templates', name_or_id=name, **{'data': search_fields})
if state == 'absent': if state == 'absent':
# If the state was absent we can let the module delete it if needed, the module will handle exiting from this # 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) new_fields['webhook_credential'] = module.resolve_name_to_id('webhook_credential', webhook_credential)
# Create the data that gets sent for create and update # 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 ( for field_name in (
'description', 'survey_enabled', 'allow_simultaneous', 'description', 'survey_enabled', 'allow_simultaneous',
'limit', 'scm_branch', 'extra_vars', 'limit', 'scm_branch', 'extra_vars',

View File

@@ -198,12 +198,14 @@ def main():
workflow_job_template = module.params.get('workflow_job_template') workflow_job_template = module.params.get('workflow_job_template')
workflow_job_template_id = None workflow_job_template_id = None
if workflow_job_template: if workflow_job_template:
wfjt_search_fields = {'name': workflow_job_template} wfjt_search_fields = {}
organization = module.params.get('organization') organization = module.params.get('organization')
if organization: if organization:
organization_id = module.resolve_name_to_id('organizations', organization) organization_id = module.resolve_name_to_id('organizations', organization)
wfjt_search_fields['organization'] = organization_id wfjt_search_fields['organization'] = organization_id
wfjt_data = module.get_one('workflow_job_templates', **{'data': wfjt_search_fields}) wfjt_data = module.get_one('workflow_job_templates', name_or_id=workflow_job_template, **{
'data': wfjt_search_fields
})
if wfjt_data is None: if wfjt_data is None:
module.fail_json(msg="The workflow {0} in organization {1} was not found on the Tower server".format( 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, organization

View File

@@ -138,10 +138,10 @@ def main():
post_data['inventory'] = module.resolve_name_to_id('inventories', inventory) post_data['inventory'] = module.resolve_name_to_id('inventories', inventory)
# Attempt to look up job_template based on the provided name # Attempt to look up job_template based on the provided name
lookup_data = {'name': name} lookup_data = {}
if organization: if organization:
lookup_data['organization'] = module.resolve_name_to_id('organizations', organization) lookup_data['organization'] = module.resolve_name_to_id('organizations', organization)
workflow_job_template = module.get_one('workflow_job_templates', 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: if workflow_job_template is None:
module.fail_json(msg="Unable to find workflow job template") module.fail_json(msg="Unable to find workflow job template")

View File

@@ -82,9 +82,9 @@
that: that:
- "result is changed" - "result is changed"
- name: Re-create the Org-specific credential (new school) - name: Re-create the Org-specific credential (new school) with an ID
tower_credential: tower_credential:
name: "{{ ssh_cred_name1 }}" name: "{{ result.id }}"
organization: Default organization: Default
credential_type: 'Machine' credential_type: 'Machine'
state: present state: present

View File

@@ -1,105 +1,113 @@
--- ---
- name: Generate a random string for test
set_fact:
test_id: "{{ lookup('password', '/dev/null chars=ascii_letters length=16') }}"
when: test_id is not defined
- name: Generate names - name: Generate names
set_fact: set_fact:
src_cred_name: src_cred src_cred_name: "AWX-Collection-tests-tower_credential_input_source-src_cred-{{ test_id }}"
target_cred_name: target_cred target_cred_name: "AWX-Collection-tests-tower_credential_input_source-target_cred-{{ test_id }}"
- name: Add Tower credential Lookup - block:
tower_credential: - name: Add Tower credential Lookup
description: Credential for Testing Source tower_credential:
name: "{{ src_cred_name }}" description: Credential for Testing Source
credential_type: CyberArk AIM Central Credential Provider Lookup name: "{{ src_cred_name }}"
inputs: credential_type: CyberArk AIM Central Credential Provider Lookup
url: "https://cyberark.example.com" inputs:
app_id: "My-App-ID" url: "https://cyberark.example.com"
organization: Default app_id: "My-App-ID"
register: result organization: Default
register: src_cred_result
- assert: - assert:
that: that:
- "result is changed" - "src_cred_result is changed"
- name: Add Tower credential Target - name: Add Tower credential Target
tower_credential: tower_credential:
description: Credential for Testing Target description: Credential for Testing Target
name: "{{ target_cred_name }}" name: "{{ target_cred_name }}"
credential_type: Machine credential_type: Machine
inputs: inputs:
username: user username: user
organization: Default organization: Default
register: result register: target_cred_result
- assert: - assert:
that: that:
- "result is changed" - "target_cred_result is changed"
- name: Add credential Input Source - name: Add credential Input Source
tower_credential_input_source: tower_credential_input_source:
input_field_name: password input_field_name: password
target_credential: "{{ target_cred_name }}" target_credential: "{{ target_cred_result.id }}"
source_credential: "{{ src_cred_name }}" source_credential: "{{ src_cred_result.id }}"
metadata: metadata:
object_query: "Safe=MY_SAFE;Object=AWX-user" object_query: "Safe=MY_SAFE;Object=AWX-user"
object_query_format: "Exact" object_query_format: "Exact"
state: present state: present
register: result
- assert: - assert:
that: that:
- "result is changed" - "result is changed"
- name: Add Second Tower credential Lookup - name: Add Second Tower credential Lookup
tower_credential: tower_credential:
description: Credential for Testing Source Change description: Credential for Testing Source Change
name: "{{ src_cred_name }}-2" name: "{{ src_cred_name }}-2"
credential_type: CyberArk AIM Central Credential Provider Lookup credential_type: CyberArk AIM Central Credential Provider Lookup
inputs: inputs:
url: "https://cyberark-prod.example.com" url: "https://cyberark-prod.example.com"
app_id: "My-App-ID" app_id: "My-App-ID"
organization: Default organization: Default
register: result register: result
- name: Change credential Input Source - name: Change credential Input Source
tower_credential_input_source: tower_credential_input_source:
input_field_name: password input_field_name: password
target_credential: "{{ target_cred_name }}" target_credential: "{{ target_cred_name }}"
source_credential: "{{ src_cred_name }}-2" source_credential: "{{ src_cred_name }}-2"
state: present state: present
- assert: - assert:
that: that:
- "result is changed" - "result is changed"
- name: Remove a Tower credential source always:
tower_credential_input_source: - name: Remove a Tower credential source
input_field_name: password tower_credential_input_source:
target_credential: "{{ target_cred_name }}" input_field_name: password
state: absent target_credential: "{{ target_cred_name }}"
register: result state: absent
register: result
- assert: - assert:
that: that:
- "result is changed" - "result is changed"
- name: Remove Tower credential Lookup - name: Remove Tower credential Lookup
tower_credential: tower_credential:
name: "{{ src_cred_name }}" name: "{{ src_cred_name }}"
organization: Default organization: Default
credential_type: CyberArk AIM Central Credential Provider Lookup credential_type: CyberArk AIM Central Credential Provider Lookup
state: absent state: absent
register: result register: result
- name: Remove Alt Tower credential Lookup - name: Remove Alt Tower credential Lookup
tower_credential: tower_credential:
name: "{{ src_cred_name }}-2" name: "{{ src_cred_name }}-2"
organization: Default organization: Default
credential_type: CyberArk AIM Central Credential Provider Lookup credential_type: CyberArk AIM Central Credential Provider Lookup
state: absent state: absent
register: result register: result
- name: Remove Tower credential - name: Remove Tower credential
tower_credential: tower_credential:
name: "{{ target_cred_name }}" name: "{{ target_cred_name }}"
organization: Default organization: Default
credential_type: Machine credential_type: Machine
state: absent state: absent
register: result register: result

View File

@@ -18,7 +18,7 @@
- name: Remove a Tower credential type - name: Remove a Tower credential type
tower_credential_type: tower_credential_type:
name: "{{ cred_type_name }}" name: "{{ result.id }}"
state: absent state: absent
register: result register: result

View File

@@ -14,11 +14,12 @@
name: "{{ inv_name }}" name: "{{ inv_name }}"
organization: Default organization: Default
state: present state: present
register: result
- name: Create a Group - name: Create a Group
tower_group: tower_group:
name: "{{ group_name1 }}" name: "{{ group_name1 }}"
inventory: "{{ inv_name }}" inventory: "{{ result.id }}"
state: present state: present
variables: variables:
foo: bar foo: bar
@@ -30,7 +31,7 @@
- name: Delete a Group - name: Delete a Group
tower_group: tower_group:
name: "{{ group_name1 }}" name: "{{ result.id }}"
inventory: "{{ inv_name }}" inventory: "{{ inv_name }}"
state: absent state: absent
register: result register: result

View File

@@ -9,11 +9,12 @@
name: "{{ inv_name }}" name: "{{ inv_name }}"
organization: Default organization: Default
state: present state: present
register: result
- name: Create a Host - name: Create a Host
tower_host: tower_host:
name: "{{ host_name }}" name: "{{ host_name }}"
inventory: "{{ inv_name }}" inventory: "{{ result.id }}"
state: present state: present
variables: variables:
foo: bar foo: bar
@@ -25,7 +26,7 @@
- name: Delete a Host - name: Delete a Host
tower_host: tower_host:
name: "{{ host_name }}" name: "{{ result.id }}"
inventory: "{{ inv_name }}" inventory: "{{ inv_name }}"
state: absent state: absent
register: result register: result

View File

@@ -19,11 +19,11 @@
host: "https://openshift.org" host: "https://openshift.org"
bearer_token: "asdf1234" bearer_token: "asdf1234"
verify_ssl: false verify_ssl: false
register: result register: cred_result
- assert: - assert:
that: that:
- "result is changed" - "cred_result is changed"
- name: Create an Instance Group - name: Create an Instance Group
tower_instance_group: tower_instance_group:
@@ -37,10 +37,22 @@
that: that:
- "result is changed" - "result is changed"
- name: Update an Instance Group
tower_instance_group:
name: "{{ result.id }}"
policy_instance_percentage: 34
policy_instance_minimum: 24
state: present
register: result
- assert:
that:
- "result is changed"
- name: Create a container group - name: Create a container group
tower_instance_group: tower_instance_group:
name: "{{ group_name2 }}" name: "{{ group_name2 }}"
credential: "{{ cred_name1 }}" credential: "{{ cred_result.id }}"
register: result register: result
- assert: - assert:

View File

@@ -29,7 +29,7 @@
tower_inventory: tower_inventory:
name: "{{ inv_name1 }}" name: "{{ inv_name1 }}"
organization: Default organization: Default
insights_credential: "{{ cred_name1 }}" insights_credential: "{{ result.id }}"
state: present state: present
register: result register: result
@@ -39,7 +39,7 @@
- name: Test Inventory module idempotency - name: Test Inventory module idempotency
tower_inventory: tower_inventory:
name: "{{ inv_name1 }}" name: "{{ result.id }}"
organization: Default organization: Default
insights_credential: "{{ cred_name1 }}" insights_credential: "{{ cred_name1 }}"
state: present state: present

View File

@@ -16,6 +16,7 @@
host: https://example.org:5000 host: https://example.org:5000
password: passw0rd password: passw0rd
domain: test domain: test
register: credential_result
- name: Add a Tower inventory - name: Add a Tower inventory
tower_inventory: tower_inventory:
@@ -28,7 +29,7 @@
name: "{{ openstack_inv_source }}" name: "{{ openstack_inv_source }}"
description: Source for Test inventory description: Source for Test inventory
inventory: "{{ openstack_inv }}" inventory: "{{ openstack_inv }}"
credential: "{{ openstack_cred }}" credential: "{{ credential_result.id }}"
overwrite: true overwrite: true
update_on_launch: true update_on_launch: true
source_vars: source_vars:
@@ -42,7 +43,7 @@
- name: Delete the inventory source with an invalid cred, source_project, sourece_script specified - name: Delete the inventory source with an invalid cred, source_project, sourece_script specified
tower_inventory_source: tower_inventory_source:
name: "{{ openstack_inv_source }}" name: "{{ result.id }}"
inventory: "{{ openstack_inv }}" inventory: "{{ openstack_inv }}"
credential: "Does Not Exit" credential: "Does Not Exit"
source_project: "Does Not Exist" source_project: "Does Not Exist"

View File

@@ -22,14 +22,14 @@
state: present state: present
scm_type: git scm_type: git
scm_url: https://github.com/ansible/ansible-tower-samples.git scm_url: https://github.com/ansible/ansible-tower-samples.git
register: proj_result
register: result
- name: Create Credential1 - name: Create Credential1
tower_credential: tower_credential:
name: "{{ cred1 }}" name: "{{ cred1 }}"
organization: Default organization: Default
kind: tower kind: tower
register: cred1_result
- name: Create Credential2 - name: Create Credential2
tower_credential: tower_credential:
@@ -84,19 +84,19 @@
credentials: ["{{ cred1 }}", "{{ cred2 }}"] credentials: ["{{ cred1 }}", "{{ cred2 }}"]
job_type: run job_type: run
state: present state: present
register: result register: jt1_result
- assert: - assert:
that: that:
- "result is changed" - "jt1_result is changed"
- name: Add a credential to this JT - name: Add a credential to this JT
tower_job_template: tower_job_template:
name: "{{ jt1 }}" name: "{{ jt1 }}"
project: "{{ proj1 }}" project: "{{ proj_result.id }}"
playbook: hello_world.yml playbook: hello_world.yml
credentials: credentials:
- "{{ cred1 }}" - "{{ cred1_result.id }}"
register: result register: result
- assert: - assert:
@@ -105,7 +105,7 @@
- name: Try to add the same credential to this JT - name: Try to add the same credential to this JT
tower_job_template: tower_job_template:
name: "{{ jt1 }}" name: "{{ jt1_result.id }}"
project: "{{ proj1 }}" project: "{{ proj1 }}"
playbook: hello_world.yml playbook: hello_world.yml
credentials: credentials:

View File

@@ -15,9 +15,9 @@
that: that:
- "result is changed" - "result is changed"
- name: Change a User - name: Change a User by ID
tower_user: tower_user:
username: "{{ username }}" username: "{{ result.id }}"
last_name: User last_name: User
email: joe@example.org email: joe@example.org
state: present state: present

View File

@@ -175,9 +175,8 @@ def main():
{% endfor %} {% endfor %}
# Attempt to look up an existing item based on the provided data # Attempt to look up an existing item based on the provided data
existing_item = module.get_one('{{ item_type }}', **{ existing_item = module.get_one('{{ item_type }}', name_or_id={{ name_option }}, **{
'data': { 'data': {
'{{ name_option }}': {{ name_option }},
{% if 'organization' in item['json']['actions']['POST'] and item['json']['actions']['POST']['organization']['type'] == 'id' %} {% if 'organization' in item['json']['actions']['POST'] and item['json']['actions']['POST']['organization']['type'] == 'id' %}
'organization': org_id, 'organization': org_id,
{% endif %} {% endif %}
@@ -195,7 +194,7 @@ def main():
new_fields = {} new_fields = {}
{% for option in item['json']['actions']['POST'] %} {% for option in item['json']['actions']['POST'] %}
{% if option == name_option %} {% if option == name_option %}
new_fields['{{ name_option }}'] = new_{{ name_option }} if new_{{ name_option }} else {{ name_option }} new_fields['{{ name_option }}'] = new_{{ name_option }} if new_{{ name_option }} else (module.get_item_name(existing_item) if existing_item else {{ name_option }}t)
{% else %} {% else %}
if {{ option }} is not None: if {{ option }} is not None:
{% if item['json']['actions']['POST'][option]['type'] == 'id' %} {% if item['json']['actions']['POST'][option]['type'] == 'id' %}