Fix dangerous default args. (#29839)

pull/29953/head
Matt Clay 7 years ago committed by GitHub
parent 5caa47feb9
commit 68aeaa58a8

@ -169,8 +169,9 @@ class CollinsInventory(object):
print(data_to_print)
return successful
def find_assets(self, attributes={}, operation='AND'):
def find_assets(self, attributes=None, operation='AND'):
""" Obtains Collins assets matching the provided attributes. """
attributes = {} if attributes is None else attributes
# Formats asset search query to locate assets matching attributes, using
# the CQL search feature as described here:

@ -53,7 +53,9 @@ class ProxmoxVM(dict):
class ProxmoxVMList(list):
def __init__(self, data=[]):
def __init__(self, data=None):
data = [] if data is None else data
for item in data:
self.append(ProxmoxVM(item))

@ -836,8 +836,8 @@ def _find_module_utils(module_name, b_module_data, module_path, module_args, tas
return (b_module_data, module_style, shebang)
def modify_module(module_name, module_path, module_args, task_vars=dict(), module_compression='ZIP_STORED', async_timeout=0, become=False,
become_method=None, become_user=None, become_password=None, environment=dict()):
def modify_module(module_name, module_path, module_args, task_vars=None, module_compression='ZIP_STORED', async_timeout=0, become=False,
become_method=None, become_user=None, become_password=None, environment=None):
"""
Used to insert chunks of code into modules before transfer rather than
doing regular python imports. This allows for more efficient transfer in
@ -858,6 +858,9 @@ def modify_module(module_name, module_path, module_args, task_vars=dict(), modul
properties not available here.
"""
task_vars = {} if task_vars is None else task_vars
environment = {} if environment is None else environment
with open(module_path, 'rb') as f:
# read in the module source

@ -76,7 +76,9 @@ def check_args(module, warnings):
module.params[key] = ARGS_DEFAULT_VALUE[key]
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
cmd = 'show run-config commands '
cmd += ' '.join(flags)
cmd = cmd.strip()

@ -66,7 +66,9 @@ def check_args(module, warnings):
module.params[key] = ARGS_DEFAULT_VALUE[key]
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()

@ -117,7 +117,9 @@ def run_commands(module, commands, check_rc=True):
return responses
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
passwords = module.params['passwords']
if passwords:
cmd = 'more system:running-config'

@ -40,7 +40,9 @@ from ansible.module_utils.ec2 import camel_dict_to_snake_dict
class DirectConnectError(Exception):
def __init__(self, msg, last_traceback=None, response={}):
def __init__(self, msg, last_traceback=None, response=None):
response = {} if response is None else response
self.msg = msg
self.last_traceback = last_traceback
self.response = camel_dict_to_snake_dict(response)

@ -473,7 +473,7 @@ class AzureRMModuleBase(object):
return None
def serialize_obj(self, obj, class_name, enum_modules=[]):
def serialize_obj(self, obj, class_name, enum_modules=None):
'''
Return a JSON representation of an Azure object.
@ -482,6 +482,8 @@ class AzureRMModuleBase(object):
:param enum_modules: List of module names to build enum dependencies from.
:return: serialized result
'''
enum_modules = [] if enum_modules is None else enum_modules
dependencies = dict()
if enum_modules:
for module_name in enum_modules:

@ -2156,7 +2156,7 @@ class AnsibleModule(object):
# and we don't want to break modules unnecessarily
return None
def get_bin_path(self, arg, required=False, opt_dirs=[]):
def get_bin_path(self, arg, required=False, opt_dirs=None):
'''
find system executable in PATH.
Optional arguments:
@ -2164,6 +2164,8 @@ class AnsibleModule(object):
- opt_dirs: optional list of directories to search in addition to PATH
if found return full path; otherwise return None
'''
opt_dirs = [] if opt_dirs is None else opt_dirs
sbin_paths = ['/sbin', '/usr/sbin', '/usr/local/sbin']
paths = []
for d in opt_dirs:

@ -120,9 +120,11 @@ class Cli:
return exec_command(self._module, command)
def get_config(self, flags=[]):
def get_config(self, flags=None):
"""Retrieves the current config from the device or cache
"""
flags = [] if flags is None else flags
cmd = 'display current-configuration '
cmd += ' '.join(flags)
cmd = cmd.strip()
@ -227,7 +229,9 @@ def to_command(module, commands):
return commands
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
conn = get_connection(module)
return conn.get_config(flags)

@ -68,7 +68,9 @@ def check_args(module, warnings):
'removed in a future version' % key)
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()

@ -67,7 +67,9 @@ def check_args(module, warnings):
'removed in a future version' % key)
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()

@ -68,7 +68,9 @@ def check_args(module, warnings):
'removed in a future version' % key)
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()

@ -136,9 +136,11 @@ class Cli:
out = to_text(out, errors='surrogate_then_replace')
return out.endswith('#')
def get_config(self, flags=[]):
def get_config(self, flags=None):
"""Retrieves the current config from the device or cache
"""
flags = [] if flags is None else flags
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()
@ -363,9 +365,11 @@ class Eapi:
return responses
def get_config(self, flags=[]):
def get_config(self, flags=None):
"""Retrieves the current config from the device or cache
"""
flags = [] if flags is None else flags
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()
@ -457,7 +461,9 @@ def to_command(module, commands):
return transform(to_list(commands))
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = None if flags is None else flags
conn = get_connection(module)
return conn.get_config(flags)

@ -295,7 +295,7 @@ def gcp_connect(module, provider, get_driver, user_agent_product, user_agent_ver
return gcp
def get_google_cloud_credentials(module, scopes=[]):
def get_google_cloud_credentials(module, scopes=None):
"""
Get credentials object for use with Google Cloud client.
@ -324,6 +324,8 @@ def get_google_cloud_credentials(module, scopes=[]):
params dict {'service_account_email': '...', 'credentials_file': '...', 'project_id': ...}
:rtype: ``tuple``
"""
scopes = [] if scopes is None else scopes
if not HAS_GOOGLE_AUTH:
module.fail_json(msg='Please install google-auth.')
@ -348,7 +350,7 @@ def get_google_cloud_credentials(module, scopes=[]):
return (None, None)
def get_google_api_auth(module, scopes=[], user_agent_product='ansible-python-api', user_agent_version='NA'):
def get_google_api_auth(module, scopes=None, user_agent_product='ansible-python-api', user_agent_version='NA'):
"""
Authentication for use with google-python-api-client.
@ -384,6 +386,8 @@ def get_google_api_auth(module, scopes=[], user_agent_product='ansible-python-ap
params dict {'service_account_email': '...', 'credentials_file': '...', 'project_id': ...}
:rtype: ``tuple``
"""
scopes = [] if scopes is None else scopes
if not HAS_GOOGLE_API_LIB:
module.fail_json(msg="Please install google-api-python-client library")
if not scopes:

@ -77,7 +77,9 @@ def get_defaults_flag(module):
return ['full']
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()

@ -61,7 +61,9 @@ def check_args(module, warnings):
warnings.append('argument %s has been deprecated and will be removed in a future version' % key)
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()

@ -39,7 +39,11 @@ from ansible.module_utils._text import to_native
class ConfigProxy(object):
def __init__(self, actual, client, attribute_values_dict, readwrite_attrs, transforms={}, readonly_attrs=[], immutable_attrs=[], json_encodes=[]):
def __init__(self, actual, client, attribute_values_dict, readwrite_attrs, transforms=None, readonly_attrs=None, immutable_attrs=None, json_encodes=None):
transforms = {} if transforms is None else transforms
readonly_attrs = [] if readonly_attrs is None else readonly_attrs
immutable_attrs = [] if immutable_attrs is None else immutable_attrs
json_encodes = [] if json_encodes is None else json_encodes
# Actual config object from nitro sdk
self.actual = actual

@ -91,7 +91,9 @@ class Entity(object):
* default - default value
"""
def __init__(self, module, attrs=None, args=[], keys=None, from_argspec=False):
def __init__(self, module, attrs=None, args=None, keys=None, from_argspec=False):
args = [] if args is None else args
self._attributes = attrs or {}
self._module = module

@ -116,9 +116,11 @@ class Cli:
command = self._module.jsonify(command)
return exec_command(self._module, command)
def get_config(self, flags=[]):
def get_config(self, flags=None):
"""Retrieves the current config from the device or cache
"""
flags = [] if flags is None else []
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()
@ -299,9 +301,11 @@ class Nxapi:
return result
def get_config(self, flags=[]):
def get_config(self, flags=None):
"""Retrieves the current config from the device or cache
"""
flags = [] if flags is None else flags
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()
@ -385,7 +389,9 @@ def to_command(module, commands):
return commands
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
conn = get_connection(module)
return conn.get_config(flags)

@ -67,7 +67,7 @@ def transform_list_to_dict(list_):
return ret
def merge_list_by_key(original_list, updated_list, key, ignore_when_null=[]):
def merge_list_by_key(original_list, updated_list, key, ignore_when_null=None):
"""
Merge two lists by the key. It basically:
@ -84,6 +84,8 @@ def merge_list_by_key(original_list, updated_list, key, ignore_when_null=[]):
if its values are null.
:return: list: Lists merged.
"""
ignore_when_null = [] if ignore_when_null is None else ignore_when_null
if not original_list:
return updated_list

@ -1,7 +1,9 @@
_DEVICE_CONFIGS = {}
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
cmd = 'show running-config '
cmd += ' '.join(flags)
cmd = cmd.strip()

@ -58,7 +58,9 @@ def check_args(module, warnings):
warnings.append('argument %s has been deprecated and will be removed in a future version' % key)
def get_config(module, flags=[]):
def get_config(module, flags=None):
flags = [] if flags is None else flags
cmd = 'admin display-config '
cmd += ' '.join(flags)
cmd = cmd.strip()

@ -670,10 +670,12 @@ class SSLValidationHandler(urllib_request.BaseHandler):
to_add_path = None
return (tmp_path, to_add_path, paths_checked)
def validate_proxy_response(self, response, valid_codes=[200]):
def validate_proxy_response(self, response, valid_codes=None):
'''
make sure we get back a valid code from the proxy
'''
valid_codes = [200] if valid_codes is None else valid_codes
try:
(http_version, resp_code, msg) = re.match(r'(HTTP/\d\.\d) (\d\d\d) (.*)', response).groups()
if int(resp_code) not in valid_codes:

@ -450,7 +450,9 @@ class Ec2Metadata(object):
data = None
return to_text(data)
def _mangle_fields(self, fields, uri, filter_patterns=['public-keys-0']):
def _mangle_fields(self, fields, uri, filter_patterns=None):
filter_patterns = ['public-keys-0'] if filter_patterns is None else filter_patterns
new_fields = {}
for key, value in fields.items():
split_fields = key[len(uri):].split('/')

@ -1014,7 +1014,9 @@ class ElbManager(object):
self._delete_policy(self.elb.name, policy)
self._create_policy(policy_param, policy_meth, policy)
def _set_listener_policy(self, listeners_dict, policy=[]):
def _set_listener_policy(self, listeners_dict, policy=None):
policy = [] if policy is None else policy
for listener_port in listeners_dict:
if listeners_dict[listener_port].startswith('HTTP'):
self.elb_conn.set_lb_policies_of_listener(self.elb.name, listener_port, policy)

@ -395,7 +395,7 @@ def _validate_named_port_params(params):
return (True, '')
def _get_instance_list(mig, field='name', filter_list=['NONE']):
def _get_instance_list(mig, field='name', filter_list=None):
"""
Helper to grab field from instances response.
@ -414,6 +414,8 @@ def _get_instance_list(mig, field='name', filter_list=['NONE']):
:return: List of strings from list_managed_instances response.
:rtype: ``list``
"""
filter_list = ['NONE'] if filter_list is None else filter_list
return [x[field] for x in mig.list_managed_instances()
if x['currentAction'] in filter_list]

@ -363,7 +363,9 @@ class LXDContainerManagement(object):
self._change_state('unfreeze')
self.actions.append('unfreez')
def _container_ipv4_addresses(self, ignore_devices=['lo']):
def _container_ipv4_addresses(self, ignore_devices=None):
ignore_devices = ['lo'] if ignore_devices is None else ignore_devices
resp_json = self._get_container_state_json()
network = resp_json['metadata']['network'] or {}
network = dict((k, v) for k, v in network.items() if k not in ignore_devices) or {}

@ -282,10 +282,18 @@ def rax_find_server_image(module, server, image, boot_volume):
return server.image
def create(module, names=[], flavor=None, image=None, meta={}, key_name=None,
files={}, wait=True, wait_timeout=300, disk_config=None,
group=None, nics=[], extra_create_args={}, user_data=None,
config_drive=False, existing=[], block_device_mapping_v2=[]):
def create(module, names=None, flavor=None, image=None, meta=None, key_name=None,
files=None, wait=True, wait_timeout=300, disk_config=None,
group=None, nics=None, extra_create_args=None, user_data=None,
config_drive=False, existing=None, block_device_mapping_v2=None):
names = [] if names is None else names
meta = {} if meta is None else meta
files = {} if files is None else files
nics = [] if nics is None else nics
extra_create_args = {} if extra_create_args is None else extra_create_args
existing = [] if existing is None else existing
block_device_mapping_v2 = [] if block_device_mapping_v2 is None else block_device_mapping_v2
cs = pyrax.cloudservers
changed = False
@ -392,7 +400,10 @@ def create(module, names=[], flavor=None, image=None, meta={}, key_name=None,
module.exit_json(**results)
def delete(module, instance_ids=[], wait=True, wait_timeout=300, kept=[]):
def delete(module, instance_ids=None, wait=True, wait_timeout=300, kept=None):
instance_ids = [] if instance_ids is None else instance_ids
kept = [] if kept is None else kept
cs = pyrax.cloudservers
changed = False
@ -469,13 +480,19 @@ def delete(module, instance_ids=[], wait=True, wait_timeout=300, kept=[]):
def cloudservers(module, state=None, name=None, flavor=None, image=None,
meta={}, key_name=None, files={}, wait=True, wait_timeout=300,
disk_config=None, count=1, group=None, instance_ids=[],
exact_count=False, networks=[], count_offset=0,
auto_increment=False, extra_create_args={}, user_data=None,
meta=None, key_name=None, files=None, wait=True, wait_timeout=300,
disk_config=None, count=1, group=None, instance_ids=None,
exact_count=False, networks=None, count_offset=0,
auto_increment=False, extra_create_args=None, user_data=None,
config_drive=False, boot_from_volume=False,
boot_volume=None, boot_volume_size=None,
boot_volume_terminate=False):
meta = {} if meta is None else meta
files = {} if files is None else files
instance_ids = [] if instance_ids is None else instance_ids
networks = [] if networks is None else networks
extra_create_args = {} if extra_create_args is None else extra_create_args
cs = pyrax.cloudservers
cnw = pyrax.cloud_networks
if not cnw:

@ -155,11 +155,16 @@ from ansible.module_utils.rax import (rax_argument_spec, rax_find_image, rax_fin
from ansible.module_utils.six import string_types
def rax_asg(module, cooldown=300, disk_config=None, files={}, flavor=None,
image=None, key_name=None, loadbalancers=[], meta={},
min_entities=0, max_entities=0, name=None, networks=[],
def rax_asg(module, cooldown=300, disk_config=None, files=None, flavor=None,
image=None, key_name=None, loadbalancers=None, meta=None,
min_entities=0, max_entities=0, name=None, networks=None,
server_name=None, state='present', user_data=None,
config_drive=False, wait=True, wait_timeout=300):
files = {} if files is None else files
loadbalancers = [] if loadbalancers is None else loadbalancers
meta = {} if meta is None else meta
networks = [] if networks is None else networks
changed = False
au = pyrax.autoscale

@ -208,7 +208,9 @@ class NamedResource(object):
class OC(object):
def __init__(self, module, token, host, port,
apis=['api', 'oapi']):
apis=None):
apis = ['api', 'oapi'] if apis is None else apis
self.apis = apis
self.version = 'v1'
self.token = token

@ -639,8 +639,10 @@ def child_to_element(module, child, in_type):
module.fail_json(msg="Invalid child input type: %s. Type must be either xml or yaml." % in_type)
def children_to_nodes(module=None, children=[], type='yaml'):
def children_to_nodes(module=None, children=None, type='yaml'):
"""turn a str/hash/list of str&hash into a list of elements"""
children = [] if children is None else children
return [child_to_element(module, child, type) for child in children]

@ -162,12 +162,13 @@ class Infinity(object):
self,
method='get',
resource_url='',
stat_codes=[200],
stat_codes=None,
params=None,
payload_data=None):
"""
Perform the HTTPS request by using anible get/delete method
"""
stat_codes = [200] if stat_codes is None else stat_codes
request_url = str(self.base_url) + str(resource_url)
response = None
headers = {'Content-Type': 'application/json'}

@ -121,7 +121,9 @@ class netscaler(object):
def __init__(self, module):
self.module = module
def http_request(self, api_endpoint, data_json={}):
def http_request(self, api_endpoint, data_json=None):
data_josn = {} if data_json is None else data_json
request_url = self._nsc_protocol + '://' + self._nsc_host + self._nitro_base_url + api_endpoint
data_json = urlencode(data_json)

@ -148,9 +148,10 @@ from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
def send_msg(msg, server='localhost', port='6667', channel=None, nick_to=[], key=None, topic=None,
def send_msg(msg, server='localhost', port='6667', channel=None, nick_to=None, key=None, topic=None,
nick="ansible", color='none', passwd=False, timeout=30, use_ssl=False, part=True, style=None):
'''send message to IRC'''
nick_to = [] if nick_to is None else nick_to
colornumbers = {
'white': "00",

@ -203,7 +203,9 @@ class LocalSocketThread(Thread):
server = None
terminated = False
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None):
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, Verbose=None):
kwargs = {} if kwargs is None else kwargs
self.server = kwargs.get('server')
Thread.__init__(self, group, target, name, args, kwargs, Verbose)
@ -281,7 +283,9 @@ class LocalSocketThread(Thread):
class ThreadWithReturnValue(Thread):
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, Verbose=None):
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, Verbose=None):
kwargs = {} if kwargs is None else kwargs
Thread.__init__(self, group, target, name, args, kwargs, Verbose)
self._return = None

@ -407,13 +407,15 @@ class ACMEAccount(object):
return result, info
def _new_reg(self, contact=[]):
def _new_reg(self, contact=None):
'''
Registers a new ACME account. Returns True if the account was
created and False if it already existed (e.g. it was not newly
created)
https://tools.ietf.org/html/draft-ietf-acme-acme-02#section-6.3
'''
contact = [] if contact is None else contact
if self.uri is not None:
return True

@ -95,8 +95,9 @@ class ModuleArgsParser:
Args may also be munged for certain shell command parameters.
"""
# FIXME: mutable default arg
def __init__(self, task_ds=dict()):
def __init__(self, task_ds=None):
task_ds = {} if task_ds is None else task_ds
assert isinstance(task_ds, dict), "the type of 'task_ds' should be a dict, but is a %s" % type(task_ds)
self._task_ds = task_ds
@ -129,11 +130,13 @@ class ModuleArgsParser:
return (action, args)
def _normalize_parameters(self, thing, action=None, additional_args=dict()):
def _normalize_parameters(self, thing, action=None, additional_args=None):
'''
arguments can be fuzzy. Deal with all the forms.
'''
additional_args = {} if additional_args is None else additional_args
# final args are the ones we'll eventually return, so first update
# them with any additional args specified, which have lower priority
# than those which may be parsed/normalized next

@ -284,8 +284,9 @@ class Base(with_metaclass(BaseMeta, object)):
if key not in valid_attrs:
raise AnsibleParserError("'%s' is not a valid attribute for a %s" % (key, self.__class__.__name__), obj=ds)
def validate(self, all_vars=dict()):
def validate(self, all_vars=None):
''' validation that is done at parse time, not load time '''
all_vars = {} if all_vars is None else all_vars
if not self._validated:
# walk all fields in the object

@ -301,7 +301,9 @@ class Role(Base, Become, Conditional, Taggable):
def get_parents(self):
return self._parents
def get_default_vars(self, dep_chain=[]):
def get_default_vars(self, dep_chain=None):
dep_chain = [] if dep_chain is None else dep_chain
default_vars = dict()
for dep in self.get_all_dependencies():
default_vars = combine_vars(default_vars, dep.get_default_vars())
@ -311,7 +313,9 @@ class Role(Base, Become, Conditional, Taggable):
default_vars = combine_vars(default_vars, self._default_vars)
return default_vars
def get_inherited_vars(self, dep_chain=[]):
def get_inherited_vars(self, dep_chain=None):
dep_chain = [] if dep_chain is None else dep_chain
inherited_vars = dict()
if dep_chain:
@ -319,7 +323,9 @@ class Role(Base, Become, Conditional, Taggable):
inherited_vars = combine_vars(inherited_vars, parent._role_vars)
return inherited_vars
def get_role_params(self, dep_chain=[]):
def get_role_params(self, dep_chain=None):
dep_chain = [] if dep_chain is None else dep_chain
params = {}
if dep_chain:
for parent in dep_chain:
@ -327,7 +333,9 @@ class Role(Base, Become, Conditional, Taggable):
params = combine_vars(params, self._role_params)
return params
def get_vars(self, dep_chain=[], include_params=True):
def get_vars(self, dep_chain=None, include_params=True):
dep_chain = [] if dep_chain is None else dep_chain
all_vars = self.get_inherited_vars(dep_chain)
for dep in self.get_all_dependencies():

@ -166,7 +166,7 @@ class ActionBase(with_metaclass(ABCMeta, object)):
return (module_style, module_shebang, module_data, module_path)
def _compute_environment_string(self, raw_environment_out=dict()):
def _compute_environment_string(self, raw_environment_out=None):
'''
Builds the environment string to be used when executing the remote task.
'''

@ -322,7 +322,9 @@ class Connection(ConnectionBase):
self.shell_id = None
self._connect()
def _create_raw_wrapper_payload(self, cmd, environment=dict()):
def _create_raw_wrapper_payload(self, cmd, environment=None):
environment = {} if environment is None else environment
payload = {
'module_entry': to_text(base64.b64encode(to_bytes(cmd))),
'powershell_modules': {},

@ -42,7 +42,8 @@ class PluginLoader:
The first match is used.
'''
def __init__(self, class_name, package, config, subdir, aliases={}, required_base_class=None):
def __init__(self, class_name, package, config, subdir, aliases=None, required_base_class=None):
aliases = {} if aliases is None else aliases
self.class_name = class_name
self.base_class = required_base_class

@ -220,7 +220,9 @@ class Templar:
The main class for templating, with the main entry-point of template().
'''
def __init__(self, loader, shared_loader_obj=None, variables=dict()):
def __init__(self, loader, shared_loader_obj=None, variables=None):
variables = {} if variables is None else variables
self._loader = loader
self._filters = None
self._tests = None
@ -390,12 +392,13 @@ class Templar:
self._cached_result = {}
def template(self, variable, convert_bare=False, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None,
convert_data=True, static_vars=[''], cache=True, bare_deprecated=True, disable_lookups=False):
convert_data=True, static_vars=None, cache=True, bare_deprecated=True, disable_lookups=False):
'''
Templates (possibly recursively) any given data as input. If convert_bare is
set to True, the given data will be wrapped as a jinja2 variable ('{{foo}}')
before being sent through the template engine.
'''
static_vars = [''] if static_vars is None else static_vars
# Don't template unsafe variables, just return them.
if hasattr(variable, '__UNSAFE__'):

@ -27,7 +27,7 @@ from ansible.module_utils.six.moves import builtins
from ansible.plugins.loader import filter_loader, test_loader
def safe_eval(expr, locals={}, include_exceptions=False):
def safe_eval(expr, locals=None, include_exceptions=False):
'''
This is intended for allowing things like:
with_items: a_list_variable
@ -38,6 +38,7 @@ def safe_eval(expr, locals={}, include_exceptions=False):
Based on:
http://stackoverflow.com/questions/12523516/using-ast-and-whitelists-to-make-pythons-eval-safe
'''
locals = {} if locals is None else locals
# define certain JSON types
# eg. JSON booleans are unknown to python eval()

@ -17,7 +17,6 @@ broad-except
cell-var-from-loop
consider-iterating-dictionary
consider-using-enumerate
dangerous-default-value
deprecated-lambda
deprecated-method
deprecated-module

@ -28,7 +28,8 @@ from ansible.module_utils._text import to_bytes
class DictDataLoader(DataLoader):
def __init__(self, file_mapping=dict()):
def __init__(self, file_mapping=None):
file_mapping = {} if file_mapping is None else file_mapping
assert type(file_mapping) == dict
super(DictDataLoader, self).__init__()

@ -48,7 +48,9 @@ class FakeModule(object):
else:
return alt
def __init__(self, data={}):
def __init__(self, data=None):
data = {} if data is None else data
self.params = FakeModule.Params()
self.params.data = data

@ -84,7 +84,11 @@ def setup_mod_conn(placeboify, params):
return m, conn
def make_params(cgw, vgw, tags={}, filters={}, routes=[]):
def make_params(cgw, vgw, tags=None, filters=None, routes=None):
tags = {} if tags is None else tags
filters = {} if filters is None else filters
routes = [] if routes is None else routes
return {'customer_gateway_id': cgw,
'static_only': True,
'vpn_gateway_id': vgw,

@ -42,8 +42,10 @@ class TestNuageVSPKModule(TestNuageModule):
self.patches = []
def enterprises_get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False,
def enterprises_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
if 'unknown' in filter:
return []
@ -56,7 +58,9 @@ class TestNuageVSPKModule(TestNuageModule):
self.enterprises_get_mock.start()
self.patches.append(self.enterprises_get_mock)
def enterprises_get_first(self, filter=None, order_by=None, group_by=[], query_parameters=None, commit=False, async=False, callback=None):
def enterprises_get_first(self, filter=None, order_by=None, group_by=None, query_parameters=None, commit=False, async=False, callback=None):
group_by = [] if group_by is None else group_by
if filter == 'name == "test-enterprise-create"' or 'unknown' in filter:
return None
return vsdk.NUEnterprise(id='enterprise-id', name='test-enterprise')
@ -128,8 +132,10 @@ class TestNuageVSPKModule(TestNuageModule):
self.user_save_mock.start()
self.patches.append(self.user_save_mock)
def groups_get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False,
def groups_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
return []
self.groups_get_mock = patch('vspk.v5_0.fetchers.NUGroupsFetcher.get', new=groups_get)
@ -411,7 +417,10 @@ class TestNuageVSPKModule(TestNuageModule):
'state': 'present'
})
def users_get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
def users_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
return [vsdk.NUUser(id='user-id'), vsdk.NUUser(id='user-id-2')]
with self.assertRaises(AnsibleExitJson) as exc:
@ -431,7 +440,10 @@ class TestNuageVSPKModule(TestNuageModule):
'state': 'present'
})
def users_get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
def users_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
return []
with self.assertRaises(AnsibleExitJson) as exc:
@ -488,7 +500,10 @@ class TestNuageVSPKModule(TestNuageModule):
]
})
def users_get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
def users_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
return []
with self.assertRaises(AnsibleExitJson) as exc:
@ -523,7 +538,10 @@ class TestNuageVSPKModule(TestNuageModule):
]
})
def users_get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
def users_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
return []
with self.assertRaises(AnsibleExitJson) as exc:
@ -560,7 +578,10 @@ class TestNuageVSPKModule(TestNuageModule):
'state': 'absent'
})
def users_get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
def users_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
return [vsdk.NUUser(id='user-id')]
with self.assertRaises(AnsibleExitJson) as exc:
@ -636,8 +657,10 @@ class TestNuageVSPKModule(TestNuageModule):
'command': 'find'
})
def enterprises_failed_get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False,
def enterprises_failed_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
raise BambouHTTPError(MockNuageConnection(status_code='404', reason='Not Found', errors={'description': 'Entity not found'}))
with self.assertRaises(AnsibleFailJson) as exc:
@ -675,8 +698,10 @@ class TestNuageVSPKModule(TestNuageModule):
'state': 'absent'
})
def enterprises_failed_get_first(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True,
def enterprises_failed_get_first(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True,
async=False, callback=None):
group_by = [] if group_by is None else group_by
raise BambouHTTPError(MockNuageConnection(status_code='404', reason='Not Found', errors={'description': 'Entity not found'}))
with self.assertRaises(AnsibleExitJson) as exc:
@ -714,7 +739,10 @@ class TestNuageVSPKModule(TestNuageModule):
'state': 'present'
})
def users_get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
def users_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
return []
def group_assign(self, objects, nurest_object_type, async=False, callback=None, commit=True):
@ -739,7 +767,10 @@ class TestNuageVSPKModule(TestNuageModule):
'state': 'absent'
})
def users_get(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False, callback=None):
def users_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
return [vsdk.NUUser(id='user-id'), vsdk.NUUser(id='user-id-2')]
def group_assign(self, objects, nurest_object_type, async=False, callback=None, commit=True):
@ -956,8 +987,10 @@ class TestNuageVSPKModule(TestNuageModule):
'state': 'present'
})
def users_get_first(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False,
def users_get_first(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
return None
with self.assertRaises(AnsibleFailJson) as exc:
@ -1105,8 +1138,10 @@ class TestNuageVSPKModule(TestNuageModule):
]
})
def users_get_first(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, commit=True, async=False,
def users_get_first(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True, async=False,
callback=None):
group_by = [] if group_by is None else group_by
return None
with self.assertRaises(AnsibleFailJson) as exc:

Loading…
Cancel
Save