本文整理汇总了Python中tower_cli.get_resource函数的典型用法代码示例。如果您正苦于以下问题:Python get_resource函数的具体用法?Python get_resource怎么用?Python get_resource使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_resource函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: extract_inventory_relations
def extract_inventory_relations(asset, relation_type):
# Get the API options for the relation
post_options = get_api_options(relation_type)
# Get all of the hosts
try:
relations = tower_cli.get_resource(relation_type).list(all_pages=True, **{'inventory': asset['id']})
except TowerCLIError as e:
raise TowerCLIError("Unable to get {} for {} : {}".format(relation_type, asset['id'], e))
return_relations = []
# If there are no results return an empty array
if 'results' not in relations:
return return_relations
name_to_id_map = {}
for relation in relations['results']:
# if this relation is controlled by an inventory source we can skip it
if 'has_inventory_sources' in relation and relation['has_inventory_sources']:
continue
name_to_id_map[relation['name']] = relation['id']
new_relation = {}
map_node_to_post_options(post_options, relation, new_relation)
if relation_type == 'inventory_source':
# If this is an inventory source we also need to resolve the source_project
if 'source_project' in relation and relation['source_project']:
try:
project = tower_cli.get_resource('project').get(relation['source_project'])
except TowerCLIError as e:
raise TowerCLIError("Unable to get project {} for {} : {}".format(
relation['source_project'], relation_type, e
))
new_relation['source_project'] = project['name']
if 'source_script' in relation and relation['source_script']:
try:
script = tower_cli.get_resource('inventory_script').get(relation['source_script'])
except TowerCLIError as e:
raise TowerCLIError("Unable to get inventory script {} for {} : {}".format(
relation['source_script'], relation_type, e
))
new_relation['source_script'] = script['name']
if 'credential' in relation and relation['credential']:
try:
credential = tower_cli.get_resource('credential').get(relation['credential'])
except TowerCLIError as e:
raise TowerCLIError("Unable to get inventory credential {} for {} : {}".format(
relation['credential'], relation_type, e
))
new_relation['credential'] = credential['name']
# Now get the schedules for this source
if 'related' in relation and 'schedules' in relation['related']:
schedule_data = extract_schedules(relation)
new_relation['schedules'] = schedule_data['items']
del new_relation['inventory']
return_relations.append(new_relation)
return {'items': return_relations, 'existing_name_to_id_map': name_to_id_map}
示例2: main
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(required=True),
description=dict(),
inventory=dict(required=True),
enabled=dict(type='bool', default=True),
variables=dict(),
tower_host=dict(),
tower_username=dict(),
tower_password=dict(no_log=True),
tower_verify_ssl=dict(type='bool', default=True),
tower_config_file=dict(type='path'),
state=dict(choices=['present', 'absent'], default='present'),
),
supports_check_mode=True
)
if not HAS_TOWER_CLI:
module.fail_json(msg='ansible-tower-cli required for this module')
name = module.params.get('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')
if variables:
if variables.startswith('@'):
filename = os.path.expanduser(variables[1:])
variables = module.contents_from_file(filename)
json_output = {'host': name, 'state': state}
tower_auth = tower_auth_config(module)
with settings.runtime_values(**tower_auth):
tower_check_mode(module)
host = tower_cli.get_resource('host')
try:
inv_res = tower_cli.get_resource('inventory')
inv = inv_res.get(name=inventory)
if state == 'present':
result = host.modify(name=name, inventory=inv['id'], enabled=enabled,
variables=variables, description=description, create_on_missing=True)
json_output['id'] = result['id']
elif state == 'absent':
result = host.delete(name=name, inventory=inv['id'])
except (exc.NotFound) as excinfo:
module.fail_json(msg='Failed to update host, inventory not found: {0}'.format(excinfo), changed=False)
except (exc.ConnectionError, exc.BadRequest) as excinfo:
module.fail_json(msg='Failed to update host: {0}'.format(excinfo), changed=False)
json_output['changed'] = result['changed']
module.exit_json(**json_output)
示例3: main
def main():
argument_spec = tower_argument_spec()
argument_spec.update(dict(
job_template=dict(required=True),
job_type=dict(choices=['run', 'check', 'scan']),
inventory=dict(),
credential=dict(),
limit=dict(),
tags=dict(type='list'),
extra_vars=dict(type='list'),
))
module = AnsibleModule(
argument_spec,
supports_check_mode=True
)
if not HAS_TOWER_CLI:
module.fail_json(msg='ansible-tower-cli required for this module')
json_output = {}
tags = module.params.get('tags')
tower_auth = tower_auth_config(module)
with settings.runtime_values(**tower_auth):
tower_check_mode(module)
try:
params = module.params.copy()
if isinstance(tags, list):
params['tags'] = ','.join(tags)
job = tower_cli.get_resource('job')
lookup_fields = ('job_template', 'inventory', 'credential')
for field in lookup_fields:
try:
name = params.pop(field)
result = tower_cli.get_resource(field).get(name=name)
params[field] = result['id']
except exc.NotFound as excinfo:
module.fail_json(msg='Unable to launch job, {0}/{1} was not found: {2}'.format(field, name, excinfo), changed=False)
result = job.launch(no_input=True, **params)
json_output['id'] = result['id']
json_output['status'] = result['status']
except (exc.ConnectionError, exc.BadRequest) as excinfo:
module.fail_json(msg='Unable to launch job: {0}'.format(excinfo), changed=False)
json_output['changed'] = result['changed']
module.exit_json(**json_output)
示例4: main
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(required=True),
description=dict(),
organization=dict(required=True),
tower_host=dict(),
tower_username=dict(),
tower_password=dict(no_log=True),
tower_verify_ssl=dict(type='bool', default=True),
tower_config_file=dict(type='path'),
state=dict(choices=['present', 'absent'], default='present'),
),
supports_check_mode=True
)
if not HAS_TOWER_CLI:
module.fail_json(msg='ansible-tower-cli required for this module')
name = module.params.get('name')
description = module.params.get('description')
organization = module.params.get('organization')
state = module.params.get('state')
json_output = {'team': name, 'state': state}
tower_auth = tower_auth_config(module)
with settings.runtime_values(**tower_auth):
tower_check_mode(module)
team = tower_cli.get_resource('team')
try:
org_res = tower_cli.get_resource('organization')
org = org_res.get(name=organization)
if state == 'present':
result = team.modify(name=name, organization=org['id'],
description=description, create_on_missing=True)
json_output['id'] = result['id']
elif state == 'absent':
result = team.delete(name=name, organization=org['id'])
except (exc.NotFound) as excinfo:
module.fail_json(msg='Failed to update team, organization not found: {0}'.format(excinfo), changed=False)
except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo:
module.fail_json(msg='Failed to update team: {0}'.format(excinfo), changed=False)
json_output['changed'] = result['changed']
module.exit_json(**json_output)
示例5: main
def main():
argument_spec = tower_argument_spec()
argument_spec.update(dict(
name=dict(required=True),
description=dict(),
state=dict(choices=['present', 'absent'], default='present'),
))
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
if not HAS_TOWER_CLI:
module.fail_json(msg='ansible-tower-cli required for this module')
name = module.params.get('name')
description = module.params.get('description')
state = module.params.get('state')
json_output = {'organization': name, 'state': state}
tower_auth = tower_auth_config(module)
with settings.runtime_values(**tower_auth):
tower_check_mode(module)
organization = tower_cli.get_resource('organization')
try:
if state == 'present':
result = organization.modify(name=name, description=description, create_on_missing=True)
json_output['id'] = result['id']
elif state == 'absent':
result = organization.delete(name=name)
except (exc.ConnectionError, exc.BadRequest) as excinfo:
module.fail_json(msg='Failed to update the organization: {0}'.format(excinfo), changed=False)
json_output['changed'] = result['changed']
module.exit_json(**json_output)
示例6: create
def create(self, organization=None, monitor=False, timeout=None,
*args, **kwargs):
"""Create a new item of resource, with or w/o org.
This would be a shared class with user, but it needs the ability
to monitor if the flag is set.
"""
backup_endpoint = self.endpoint
if organization:
debug.log("using alternative endpoint specific to organization",
header='details')
# Get the organization from Tower, will lookup name if needed
org_resource = get_resource('organization')
org_data = org_resource.get(organization)
org_pk = org_data['id']
self.endpoint = '/organizations/%s%s' % (org_pk, backup_endpoint)
answer = super(Resource, self).create(*args, **kwargs)
self.endpoint = backup_endpoint
# if the monitor flag is set, wait for the SCM to update
if monitor:
project_id = answer['id']
return self.monitor(project_id, timeout=timeout)
return answer
示例7: create
def create(self, organization=None, monitor=False, timeout=None,
fail_on_found=False, force_on_exists=False,
**kwargs):
"""Create a new item of resource, with or w/o org.
This would be a shared class with user, but it needs the ability
to monitor if the flag is set.
"""
# First, run the create method, ignoring the organization given
answer = super(Resource, self).write(
create_on_missing=True,
fail_on_found=fail_on_found, force_on_exists=force_on_exists,
**kwargs
)
project_id = answer['id']
# If an organization is given, associate it here
if organization:
# Get the organization from Tower, will lookup name if needed
org_resource = get_resource('organization')
org_data = org_resource.get(organization)
org_pk = org_data['id']
debug.log("associating the project with its organization",
header='details', nl=1)
org_resource._assoc('projects', org_pk, project_id)
# if the monitor flag is set, wait for the SCM to update
if monitor:
return self.monitor(project_id, timeout=timeout)
return answer
示例8: update_resources
def update_resources(module, p):
'''update_resources attempts to fetch any of the resources given
by name using their unique field (identity)
'''
params = p.copy()
for key in p:
if key.startswith('tower_'):
params.pop(key)
params.pop('state', None)
identity_map = {
'user': 'username',
'team': 'name',
'target_team': 'name',
'inventory': 'name',
'job_template': 'name',
'credential': 'name',
'organization': 'name',
'project': 'name',
}
for k, v in identity_map.items():
try:
if params[k]:
key = 'team' if k == 'target_team' else k
result = tower_cli.get_resource(key).get(**{v: params[k]})
params[k] = result['id']
except (exc.NotFound) as excinfo:
module.fail_json(msg='Failed to update role, {0} not found: {1}'.format(k, excinfo), changed=False)
return params
示例9: modify
def modify(self, pk=None, credential=None, source=None, **kwargs):
"""Modify a group and, if necessary, the inventory source within
the group.
"""
# First, modify the group.
answer = super(Resource, self).modify(pk=pk, **kwargs)
# If the group already exists and we aren't supposed to make changes,
# then we're done.
if not kwargs.pop('force_on_exists', True) and not answer['changed']:
return answer
# Get the inventory source ID ("isid").
# Inventory sources are not created directly; rather, one was created
# automatically when the group was created.
isid = self._get_inventory_source_id(answer)
# We now have our inventory source ID; modify it according to the
# provided parameters.
#
# Note: Any fields that were part of the group modification need
# to be expunged from kwargs before making this call.
isrc = get_resource('inventory_source')
for field in self.fields:
kwargs.pop(field.name, None)
return isrc.modify(isid, credential=credential, source=source,
force_on_exists=True, **kwargs)
示例10: test_create_without_special_fields
def test_create_without_special_fields(self):
"""Establish that a create without user, team, or credential works"""
with mock.patch(
'tower_cli.models.base.Resource.create') as mock_create:
cred_res = tower_cli.get_resource('credential')
cred_res.create(name="foobar")
mock_create.assert_called_once_with(name="foobar")
示例11: convert
def convert(self, value, param, ctx):
"""Return the appropriate interger value. If a non-integer is
provided, attempt a name-based lookup and return the primary key.
"""
resource = tower_cli.get_resource(self.resource_name)
# Ensure that None is passed through without trying to
# do anything.
if value is None:
return None
# If we were already given an integer, do nothing.
# This ensures that the convert method is idempotent.
if isinstance(value, int):
return value
# Do we have a string that contains only digits?
# If so, then convert it to an integer and return it.
if re.match(r'^[\d]+$', value):
return int(value)
# Okay, we have a string. Try to do a name-based lookup on the
# resource, and return back the ID that we get from that.
#
# This has the chance of erroring out, which is fine.
try:
debug.log('The %s field is given as a name; '
'looking it up.' % param.name, header='details')
rel = resource.get(**{resource.unique_criterion: value})
except exc.TowerCLIError as ex:
raise exc.RelatedError('Could not get %s. %s' %
(self.resource_name, str(ex)))
# Done! Return the ID.
return rel['id']
示例12: __init__
def __init__(self, data, wfjt, include_id=False):
ujt_attrs = list(JOB_TYPES.values())
FK_FIELDS = ujt_attrs + ['inventory', 'credential']
node_attrs = {}
attr_names = NODE_STANDARD_FIELDS + ujt_attrs
if include_id:
attr_names.append('id')
for fd in attr_names:
if fd not in data:
continue
if fd in FK_FIELDS and not isinstance(data[fd], int):
# Node's template was given by name, do lookup
ujt_res = get_resource(fd)
ujt_data = ujt_res.get(name=data[fd])
node_attrs[fd] = ujt_data['id']
else:
node_attrs[fd] = data[fd]
node_attrs['workflow_job_template'] = wfjt
for ujt_name in ujt_attrs:
if ujt_name not in node_attrs:
continue
if 'unified_job_template' not in node_attrs:
node_attrs['unified_job_template'] = node_attrs.pop(ujt_name)
else:
raise BadRequest(
'You should not provide more than one of the attributes'
' job_template, project and inventory_source.'
)
self.unified_job_template = node_attrs.get('unified_job_template', None)
self.node_attrs = node_attrs
for rel in ['success_nodes', 'failure_nodes', 'always_nodes']:
setattr(
self, rel,
[TreeNode(x, wfjt, include_id=include_id) for x in data.get(rel, data.get(rel[: -6], []))]
)
示例13: test_create_with_special_fields_new_functional
def test_create_with_special_fields_new_functional(self):
"""Establish that the correct GET data is used with the new
method for creating credentials."""
with client.test_mode as t:
t.register_json('/credentials/', {'actions': {'POST': {'organization': 'information'}}},
method='OPTIONS')
t.register_json('/credentials/', {'count': 0, 'results': [], 'next': None, 'previous': None},
method='GET')
t.register_json('/credentials/', {'count': 0, 'results': [], 'next': None, 'previous': None},
method='GET')
t.register_json('/credentials/', {'id': 42}, method='POST')
cred_res = tower_cli.get_resource('credential')
cred_res.create(name="foobar", user=1, credential_type=1)
self.assertTrue(cred_res.fields[2].no_lookup)
self.assertTrue(cred_res.fields[3].no_lookup)
# Verify request data is correct
self.assertEqual(len(t.requests), 2)
self.assertEqual(t.requests[0].method, 'GET')
self.assertEqual(t.requests[1].method, 'POST')
self.assertIn('name=foobar', t.requests[0].url)
# Make sure special fields not used for GET
self.assertTrue('user' not in t.requests[0].url)
# Make sure special files are used in actual POST
self.assertIn('user', t.requests[1].body)
示例14: create
def create(self, credential=None, source=None, **kwargs):
"""Create a group and, if necessary, modify the inventory source within
the group.
"""
# First, create the group.
answer = super(Resource, self).create(**kwargs)
# If the group already exists and we aren't supposed to make changes,
# then we're done.
if not kwargs.pop('force_on_exists', False) and not answer['changed']:
return answer
# Sanity check: A group was created, but do we need to do anything
# with the inventory source at all? If no credential or source
# was specified, then we'd just be updating the inventory source
# with an effective no-op.
if not credential and source in ('manual', None):
return answer
# Get the inventory source ID ("isid").
# Inventory sources are not created directly; rather, one was created
# automatically when the group was created.
isid = self._get_inventory_source_id(answer)
# We now have our inventory source ID; modify it according to the
# provided parameters.
isrc = get_resource('inventory_source')
return isrc.modify(isid, credential=credential, source=source,
force_on_exists=True, **kwargs)
示例15: main
def main():
argument_spec = tower_argument_spec()
argument_spec.update(dict(
job_id=dict(type='int', required=True),
fail_if_not_running=dict(type='bool', default=False),
))
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
)
if not HAS_TOWER_CLI:
module.fail_json(msg='ansible-tower-cli required for this module')
job_id = module.params.get('job_id')
json_output = {}
tower_auth = tower_auth_config(module)
with settings.runtime_values(**tower_auth):
tower_check_mode(module)
job = tower_cli.get_resource('job')
params = module.params.copy()
try:
result = job.cancel(job_id, **params)
json_output['id'] = job_id
except (exc.ConnectionError, exc.BadRequest, exc.TowerCLIError) as excinfo:
module.fail_json(msg='Unable to cancel job_id/{0}: {1}'.format(job_id, excinfo), changed=False)
json_output['changed'] = result['changed']
json_output['status'] = result['status']
module.exit_json(**json_output)