Search is not available for this dataset
text stringlengths 75 104k |
|---|
def login(username, password, scope, client_id, client_secret, verbose):
"""
Retrieves and stores an OAuth2 personal auth token.
"""
if not supports_oauth():
raise exc.TowerCLIError(
'This version of Tower does not support OAuth2.0. Set credentials using tower-cli config.'
)
... |
def receive(organization=None, user=None, team=None, credential_type=None, credential=None,
notification_template=None, inventory_script=None, inventory=None, project=None, job_template=None,
workflow=None, all=None):
"""Export assets from Tower.
'tower receive' exports one or more asse... |
def send(source=None, prevent=None, exclude=None, secret_management='default', no_color=False):
"""Import assets into Tower.
'tower send' imports one or more assets into a Tower instance
The import can take either JSON or YAML.
Data can be sent on stdin (i.e. from tower-cli receive pipe) and/or from f... |
def empty(organization=None, user=None, team=None, credential_type=None, credential=None, notification_template=None,
inventory_script=None, inventory=None, project=None, job_template=None, workflow=None,
all=None, no_color=False):
"""Empties assets from Tower.
'tower empty' removes all ass... |
def parse_requirements(filename):
"""Parse out a list of requirements from the given requirements
requirements file.
"""
reqs = []
version_spec_in_play = None
# Iterate over each line in the requirements file.
for line in open(filename, 'r').read().strip().split('\n'):
# Sanity chec... |
def combine_files(*args):
"""returns a string of all the strings in *args combined together,
with two line breaks between them"""
file_contents = []
for filename in args:
with codecs.open(filename, mode='r', encoding='utf8') as f:
file_contents.append(f.read())
return "\n\n".join... |
def create(self, organization=None, monitor=False, wait=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 ... |
def modify(self, pk=None, create_on_missing=False, **kwargs):
"""Modify an already existing.
To edit the project's organizations, see help for organizations.
Fields in the resource's `identity` tuple can be used in lieu of a
primary key for a lookup; in such a case, only other fields a... |
def update(self, pk=None, create_on_missing=False, monitor=False,
wait=False, timeout=None, name=None, organization=None):
"""Trigger a project update job within Ansible Tower.
Only meaningful on non-manual projects.
=====API DOCS=====
Update the given project.
:... |
def status(self, pk=None, detail=False, **kwargs):
"""Print the status of the most recent update.
=====API DOCS=====
Print the status of the most recent update.
:param pk: Primary key of the resource to retrieve status from.
:type pk: int
:param detail: Flag that if set... |
def convert(self, value, param, ctx):
"""Return file content if file, else, return value as-is
"""
# Protect against corner cases of invalid inputs
if not isinstance(value, str):
return value
if isinstance(value, six.binary_type):
value = value.decode('UTF... |
def convert(self, value, param, ctx):
"""Match against the appropriate choice value using the superclass
implementation, and then return the actual choice.
"""
choice = super(MappedChoice, self).convert(value, param, ctx)
ix = self.choices.index(choice)
return self.actual... |
def convert(self, value, param, ctx):
"""Return the appropriate integer 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
... |
def _parent_filter(self, parent, relationship, **kwargs):
"""
Returns filtering parameters to limit a search to the children
of a particular node by a particular relationship.
"""
if parent is None or relationship is None:
return {}
parent_filter_kwargs = {}
... |
def associate_success_node(self, parent, child=None, **kwargs):
"""Add a node to run on success.
=====API DOCS=====
Add a node to run on success.
:param parent: Primary key of parent node to associate success node to.
:type parent: int
:param child: Primary key of child... |
def disassociate_success_node(self, parent, child):
"""Remove success node.
The resulatant 2 nodes will both become root nodes.
=====API DOCS=====
Remove success node.
:param parent: Primary key of parent node to disassociate success node from.
:type parent: int
... |
def associate_failure_node(self, parent, child=None, **kwargs):
"""Add a node to run on failure.
=====API DOCS=====
Add a node to run on failure.
:param parent: Primary key of parent node to associate failure node to.
:type parent: int
:param child: Primary key of child... |
def disassociate_failure_node(self, parent, child):
"""Remove a failure node link.
The resulatant 2 nodes will both become root nodes.
=====API DOCS=====
Remove a failure node link.
:param parent: Primary key of parent node to disassociate failure node from.
:type paren... |
def associate_always_node(self, parent, child=None, **kwargs):
"""Add a node to always run after the parent is finished.
=====API DOCS=====
Add a node to always run after the parent is finished.
:param parent: Primary key of parent node to associate always node to.
:type parent... |
def disassociate_always_node(self, parent, child):
"""Remove an always node link.
The resultant 2 nodes will both become root nodes.
=====API DOCS=====
Remove an always node link.
:param parent: Primary key of parent node to disassociate always node from.
:type parent: ... |
def obj_res(data, fail_on=['type', 'obj', 'res']):
"""
Given some CLI input data,
Returns the following and their types:
obj - the role grantee
res - the resource that the role applies to
"""
errors = []
if not data.get('type', None) and 'type' in fail_on:... |
def data_endpoint(cls, in_data, ignore=[]):
"""
Converts a set of CLI input arguments, `in_data`, into
request data and an endpoint that can be used to look
up a role or list of roles.
Also changes the format of `type` in data to what the server
expects for the role mode... |
def populate_resource_columns(item_dict):
"""Operates on item_dict
Promotes the resource_name and resource_type fields to the
top-level of the serialization so they can be printed as columns.
Also makes a copies name field to type, which is a default column."""
item_dict['type']... |
def set_display_columns(self, set_true=[], set_false=[]):
"""Add or remove columns from the output."""
for i in range(len(self.fields)):
if self.fields[i].name in set_true:
self.fields[i].display = True
elif self.fields[i].name in set_false:
self.f... |
def configure_display(self, data, kwargs=None, write=False):
"""Populates columns and sets display attribute as needed.
Operates on data."""
if settings.format != 'human':
return # This is only used for human format
if write:
obj, obj_type, res, res_type = self.o... |
def role_write(self, fail_on_found=False, disassociate=False, **kwargs):
"""Re-implementation of the parent `write` method specific to roles.
Adds a grantee (user or team) to the resource's role."""
# Get the role, using only the resource data
data, self.endpoint = self.data_endpoint(kw... |
def list(self, **kwargs):
"""Return a list of roles.
=====API DOCS=====
Retrieve a list of objects.
:param all_pages: Flag that if set, collect all pages of content from the API when returning results.
:type all_pages: bool
:param page: The page to show. Ignored if all_... |
def get(self, pk=None, **kwargs):
"""Get information about a role.
=====API DOCS=====
Retrieve one and exactly one object.
:param pk: Primary key of the resource to be read. Tower CLI will only attempt to read *that* object
if ``pk`` is provided (not ``None``).
... |
def grant(self, fail_on_found=False, **kwargs):
"""Add a user or a team to a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Add a user or a team to a r... |
def revoke(self, fail_on_found=False, **kwargs):
"""Remove a user or a team from a role. Required information:
1) Type of the role
2) Resource of the role, inventory, credential, or any other
3) A user or a team to add to the role
=====API DOCS=====
Remove a user or a te... |
def _compare_node_lists(old, new):
'''
Investigate two lists of workflow TreeNodes and categorize them.
There will be three types of nodes after categorization:
1. Nodes that only exists in the new list. These nodes will later be
created recursively.
2. Nodes that only exists in the... |
def _workflow_node_structure(node_results):
'''
Takes the list results from the API in `node_results` and
translates this data into a dictionary organized in a
human-readable heirarchial structure
'''
# Build list address translation, and create backlink lists
nod... |
def _get_schema(self, wfjt_id):
"""
Returns a dictionary that represents the node network of the
workflow job template
"""
node_res = get_resource('node')
node_results = node_res.list(workflow_job_template=wfjt_id,
all_pages=True)['res... |
def schema(self, wfjt, node_network=None):
"""
Convert YAML/JSON content into workflow node objects if
node_network param is given.
If not, print a YAML representation of the node network.
=====API DOCS=====
Convert YAML/JSON content into workflow node objects if ``node_... |
def associate_notification_template(self, workflow,
notification_template, status):
"""Associate a notification template from this workflow.
=====API DOCS=====
Associate a notification template from this workflow job template.
:param workflow: Th... |
def disassociate_notification_template(self, workflow,
notification_template, status):
"""Disassociate a notification template from this workflow.
=====API DOCS=====
Disassociate a notification template from this workflow job template.
:param ... |
def create(self, fail_on_found=False, force_on_exists=False, **kwargs):
"""Create a group.
=====API DOCS=====
Create a group.
:param parent: Primary key or name of the group which will be the parent of created group.
:type parent: str
:param fail_on_found: Flag that if ... |
def list(self, root=False, **kwargs):
"""Return a list of groups.
=====API DOCS=====
Retrieve a list of groups.
:param root: Flag that if set, only root groups of a specific inventory will be listed.
:type root: bool
:param parent: Primary key or name of the group whose... |
def associate(self, group, parent, **kwargs):
"""Associate this group with the specified group.
=====API DOCS=====
Associate this group with the specified group.
:param group: Primary key or name of the child group to associate.
:type group: str
:param parent: Primary k... |
def disassociate(self, group, parent, **kwargs):
"""Disassociate this group from the specified group.
=====API DOCS=====
Disassociate this group with the specified group.
:param group: Primary key or name of the child group to disassociate.
:type group: str
:param paren... |
def parse_kv(var_string):
"""Similar to the Ansible function of the same name, parses file
with a key=value pattern and stores information in a dictionary,
but not as fully featured as the corresponding Ansible code."""
return_dict = {}
# Output updates dictionaries, so return empty one if no vals ... |
def string_to_dict(var_string, allow_kv=True, require_dict=True):
"""Returns a dictionary given a string with yaml or json syntax.
If data is not present in a key: value format, then it return
an empty dictionary.
Attempts processing string by 3 different methods in order:
1. as JSON 2. as... |
def process_extra_vars(extra_vars_list, force_json=True):
"""Returns a string that is valid JSON or YAML and contains all the
variables in every extra_vars_opt inside of extra_vars_list.
Args:
parse_kv (bool): whether to allow key=value syntax.
force_json (bool): if True, always output json.
... |
def ordered_dump(data, Dumper=yaml.Dumper, **kws):
"""Expand PyYAML's built-in dumper to support parsing OrderedDict. Return
a string as parse result of the original data structure, which includes
OrderedDict.
Args:
data: the data structure to be dumped(parsed) which is supposed to
cont... |
def get_prefix(self, include_version=True):
"""Return the appropriate URL prefix to prepend to requests,
based on the host provided in settings.
"""
host = settings.host
if '://' not in host:
host = 'https://%s' % host.strip('/')
elif host.startswith('http://'... |
def request(self, method, url, *args, **kwargs):
"""Make a request to the Ansible Tower API, and return the
response.
"""
# If the URL has the api/vX at the front strip it off
# This is common to have if you are extracting a URL from an existing object.
# For example, an... |
def _separate(self, kwargs):
"""Remove None-valued and configuration-related keyworded arguments
"""
self._pop_none(kwargs)
result = {}
for field in Resource.config_fields:
if field in kwargs:
result[field] = kwargs.pop(field)
if field ... |
def _configuration(self, kwargs, config_item):
"""Combine configuration-related keyworded arguments into
notification_configuration.
"""
if 'notification_configuration' not in config_item:
if 'notification_type' not in kwargs:
return
nc = kwargs['n... |
def create(self, fail_on_found=False, force_on_exists=False, **kwargs):
"""Create a notification template.
All required configuration-related fields (required according to
notification_type) must be provided.
There are two types of notification template creation: isolatedly
cre... |
def modify(self, pk=None, create_on_missing=False, **kwargs):
"""Modify an existing notification template.
Not all required configuration-related fields (required according to
notification_type) should be provided.
Fields in the resource's `identity` tuple can be used in lieu of a
... |
def delete(self, pk=None, fail_on_missing=False, **kwargs):
"""Remove the given notification template.
Note here configuration-related fields like
'notification_configuration' and 'channels' will not be
used even provided.
If `fail_on_missing` is True, then the object's not bei... |
def list(self, all_pages=False, **kwargs):
"""Return a list of notification templates.
Note here configuration-related fields like
'notification_configuration' and 'channels' will not be
used even provided.
If one or more filters are provided through keyword arguments,
... |
def get(self, pk=None, **kwargs):
"""Return one and exactly one notification template.
Note here configuration-related fields like
'notification_configuration' and 'channels' will not be
used even provided.
Lookups may be through a primary key, specified as a positional
... |
def config_from_environment():
"""Read tower-cli config values from the environment if present, being
careful not to override config values that were explicitly passed in.
"""
kwargs = {}
for k in CONFIG_OPTIONS:
env = 'TOWER_' + k.upper()
v = os.getenv(env, None)
if v is not... |
def with_global_options(method):
"""Apply the global options that we desire on every method within
tower-cli to the given click command.
"""
# Create global options for the Tower host, username, and password.
#
# These are runtime options that will override the configuration file
# settings.... |
def pop_option(function, name):
"""
Used to remove an option applied by the @click.option decorator.
This is useful for when you want to subclass a decorated resource command
and *don't* want all of the options provided by the parent class'
implementation.
"""
for option in getattr(function... |
def _read(self, fp, fpname):
"""Read the configuration from the given file.
If the file lacks any section header, add a [general] section
header that encompasses the whole thing.
"""
# Attempt to read the file using the superclass implementation.
#
# Check the pe... |
def set_or_reset_runtime_param(self, key, value):
"""Maintains the context of the runtime settings for invoking
a command.
This should be called by a click.option callback, and only
called once for each setting for each command invocation.
If the setting exists, it follows that... |
def runtime_values(self, **kwargs):
"""
=====API DOCS=====
Context manager that temporarily override runtime level configurations.
:param kwargs: Keyword arguments specifying runtime configuration settings.
:type kwargs: arbitrary keyword arguments
:returns: N/A
... |
def launch(self, job_template=None, monitor=False, wait=False,
timeout=None, no_input=True, extra_vars=None, **kwargs):
"""Launch a new job based on a job template.
Creates a new job in Ansible Tower, immediately starts it, and
returns back an ID in order for its status to be mon... |
def launch(self, monitor=False, wait=False, timeout=None, **kwargs):
"""Launch a new ad-hoc command.
Runs a user-defined command from Ansible Tower, immediately starts it,
and returns back an ID in order for its status to be monitored.
=====API DOCS=====
Launch a new ad-hoc com... |
def _auto_help_text(self, help_text):
"""Given a method with a docstring, convert the docstring
to more CLI appropriate wording, and also disambiguate the
word "object" on the base class docstrings.
"""
# Delete API docs if there are any.
api_doc_delimiter = '=====API DOC... |
def _echo_method(self, method):
"""Given a method, return a method that runs the internal
method and echos the result.
"""
@functools.wraps(method)
def func(*args, **kwargs):
# Echo warning if this method is deprecated.
if getattr(method, 'deprecated', Fal... |
def _format_yaml(self, payload):
"""Convert the payload into a YAML string with proper
indentation and return it.
"""
return parser.ordered_dump(payload, Dumper=yaml.SafeDumper,
default_flow_style=False) |
def _format_id(self, payload):
"""Echos only the id"""
if 'id' in payload:
return str(payload['id'])
if 'results' in payload:
return ' '.join([six.text_type(item['id']) for item in payload['results']])
raise MultipleRelatedError('Could not serialize output with id... |
def _format_human(self, payload):
"""Convert the payload into an ASCII table suitable for
printing on screen and return it.
"""
page = None
total_pages = None
# What are the columns we will show?
columns = [field.name for field in self.resource.fields
... |
def get_command(self, ctx, name):
"""Retrieve the appropriate method from the Resource,
decorate it as a click command, and return that method.
"""
# Sanity check: Does a method exist corresponding to this
# command? If not, None is returned for click to raise
# exception... |
def update(self, inventory_source, monitor=False, wait=False,
timeout=None, **kwargs):
"""Update the given inventory source.
=====API DOCS=====
Update the given inventory source.
:param inventory_source: Primary key or name of the inventory source to be updated.
... |
def list(self, group=None, host_filter=None, **kwargs):
"""Return a list of hosts.
=====API DOCS=====
Retrieve a list of hosts.
:param group: Primary key or name of the group whose hosts will be listed.
:type group: str
:param all_pages: Flag that if set, collect all pa... |
def list_facts(self, pk=None, **kwargs):
"""Return a JSON object of all available facts of the given host.
Note global option --format is not available here, as the output would always be JSON-formatted.
=====API DOCS=====
List all available facts of the given host.
:param pk:... |
def format_command_subsection(self, ctx, formatter, commands, header):
"""Writes help text for a sub-section of commands,
specifically to be reused for resource commands
and system/configuration commands.
"""
rows = []
for subcommand in commands:
cmd = self.ge... |
def format_commands(self, ctx, formatter):
"""Extra format methods for multi methods that adds all the commands
after the options.
"""
self.format_command_subsection(
ctx, formatter, self.list_misc_commands(), 'Commands'
)
self.format_command_subsection(
... |
def list_commands(self, ctx):
"""Return a list of commands present in the commands and resources
folders, but not subcommands.
"""
commands = set(self.list_resource_commands())
commands.union(set(self.list_misc_commands()))
return sorted(commands) |
def list_resource_commands(self):
"""Returns a list of multi-commands for each resource type.
"""
resource_path = os.path.abspath(os.path.join(
os.path.dirname(__file__),
os.pardir,
'resources'
))
answer = set([])
for _, name, _ in pkgu... |
def list_misc_commands(self):
"""Returns a list of global commands, realted to CLI
configuration or system management in general.
"""
answer = set([])
for cmd_name in misc.__all__:
answer.add(cmd_name)
return sorted(answer) |
def get_command(self, ctx, name):
"""Given a command identified by its name, import the appropriate
module and return the decorated command.
Resources are automatically commands, but if both a resource and
a command are defined, the command takes precedence.
"""
# First,... |
def command(method=None, **kwargs):
"""Mark this method as a CLI command.
This will only have any meaningful effect in methods that are members of a
Resource subclass.
"""
# Create the actual decorator to be applied.
# This is done in such a way to make `@resources.command`,
# `@resources.c... |
def unified_job_template_options(method):
"""
Adds the decorators for all types of unified job templates,
and if the non-unified type is specified, converts it into the
unified_job_template kwarg.
"""
jt_dec = click.option(
'--job-template', type=types.Related('job_template'),
he... |
def new_state(self):
"""Generates a state string to be used in authorizations."""
try:
self._state = self.state()
log.debug("Generated new state %s.", self._state)
except TypeError:
self._state = self.state
log.debug("Re-using previously supplied s... |
def authorization_url(self, url, state=None, **kwargs):
"""Form an authorization URL.
:param url: Authorization endpoint url, must be HTTPS.
:param state: An optional state string for CSRF protection. If not
given it will be generated for you.
:param kwargs: Extra ... |
def fetch_token(
self,
token_url,
code=None,
authorization_response=None,
body="",
auth=None,
username=None,
password=None,
method="POST",
force_querystring=False,
timeout=None,
headers=None,
verify=True,
pro... |
def token_from_fragment(self, authorization_response):
"""Parse token from the URI fragment, used by MobileApplicationClients.
:param authorization_response: The full URL of the redirect back to you
:return: A token dict
"""
self._client.parse_request_uri_response(
a... |
def refresh_token(
self,
token_url,
refresh_token=None,
body="",
auth=None,
timeout=None,
headers=None,
verify=True,
proxies=None,
**kwargs
):
"""Fetch a new access token using a refresh token.
:param token_url: The tok... |
def request(
self,
method,
url,
data=None,
headers=None,
withhold_token=False,
client_id=None,
client_secret=None,
**kwargs
):
"""Intercept all requests and add the OAuth 2 token if present."""
if not is_secure_transport(url):
... |
def register_compliance_hook(self, hook_type, hook):
"""Register a hook for request/response tweaking.
Available hooks are:
access_token_response invoked before token parsing.
refresh_token_response invoked before refresh token parsing.
protected_request invoked befo... |
def authorized(self):
"""Boolean that indicates whether this session has an OAuth token
or not. If `self.authorized` is True, you can reasonably expect
OAuth-protected requests to the resource to succeed. If
`self.authorized` is False, you need the user to go through the OAuth
au... |
def authorization_url(self, url, request_token=None, **kwargs):
"""Create an authorization URL by appending request_token and optional
kwargs to url.
This is the second step in the OAuth 1 workflow. The user should be
redirected to this authorization URL, grant access to you, and then
... |
def fetch_request_token(self, url, realm=None, **request_kwargs):
r"""Fetch a request token.
This is the first step in the OAuth 1 workflow. A request token is
obtained by making a signed post request to url. The token is then
parsed from the application/x-www-form-urlencoded response a... |
def fetch_access_token(self, url, verifier=None, **request_kwargs):
"""Fetch an access token.
This is the final step in the OAuth 1 workflow. An access token is
obtained using all previously obtained credentials, including the
verifier from the authorization step.
Note that a p... |
def parse_authorization_response(self, url):
"""Extract parameters from the post authorization redirect response URL.
:param url: The full URL that resulted from the user being redirected
back from the OAuth provider to you, the client.
:returns: A dict of parameters extract... |
def rebuild_auth(self, prepared_request, response):
"""
When being redirected we should always strip Authorization
header, since nonce may not be reused as per OAuth spec.
"""
if "Authorization" in prepared_request.headers:
# If we get redirected to a new host, we sho... |
def get_fpath(self, cfgstr=None):
"""
Reports the filepath that the cacher will use.
It will attempt to use '{fname}_{cfgstr}{ext}' unless that is too long.
Then cfgstr will be hashed.
Example:
>>> from ubelt.util_cache import Cacher
>>> import pytest
... |
def existing_versions(self):
"""
Returns data with different cfgstr values that were previously computed
with this cacher.
Example:
>>> from ubelt.util_cache import Cacher
>>> # Ensure that some data exists
>>> known_fnames = set()
>>> cac... |
def clear(self, cfgstr=None):
"""
Removes the saved cache and metadata from disk
"""
data_fpath = self.get_fpath(cfgstr)
if self.verbose > 0:
self.log('[cacher] clear cache')
if exists(data_fpath):
if self.verbose > 0:
self.log('[ca... |
def tryload(self, cfgstr=None, on_error='raise'):
"""
Like load, but returns None if the load fails due to a cache miss.
Args:
on_error (str): How to handle non-io errors errors. Either raise,
which re-raises the exception, or clear which deletes the cache
... |
def load(self, cfgstr=None):
"""
Loads the data
Raises:
IOError - if the data is unable to be loaded. This could be due to
a cache miss or because the cache is disabled.
Example:
>>> from ubelt.util_cache import * # NOQA
>>> # Settin... |
def save(self, data, cfgstr=None):
"""
Writes data to path specified by `self.fpath(cfgstr)`.
Metadata containing information about the cache will also be appended
to an adjacent file with the `.meta` suffix.
Example:
>>> from ubelt.util_cache import * # NOQA
... |
def ensure(self, func, *args, **kwargs):
r"""
Wraps around a function. A cfgstr must be stored in the base cacher.
Args:
func (callable): function that will compute data on cache miss
*args: passed to func
**kwargs: passed to func
Example:
... |
def _get_certificate(self, cfgstr=None):
"""
Returns the stamp certificate if it exists
"""
certificate = self.cacher.tryload(cfgstr=cfgstr)
return certificate |
def _rectify_products(self, product=None):
""" puts products in a normalized format """
products = self.product if product is None else product
if products is None:
return None
if not isinstance(products, (list, tuple)):
products = [products]
return produc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.