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) print(data_to_print)
return successful return successful
def find_assets(self, attributes={}, operation='AND'): def find_assets(self, attributes=None, operation='AND'):
""" Obtains Collins assets matching the provided attributes. """ """ Obtains Collins assets matching the provided attributes. """
attributes = {} if attributes is None else attributes
# Formats asset search query to locate assets matching attributes, using # Formats asset search query to locate assets matching attributes, using
# the CQL search feature as described here: # the CQL search feature as described here:

@ -53,7 +53,9 @@ class ProxmoxVM(dict):
class ProxmoxVMList(list): class ProxmoxVMList(list):
def __init__(self, data=[]): def __init__(self, data=None):
data = [] if data is None else data
for item in data: for item in data:
self.append(ProxmoxVM(item)) 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) 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, 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=dict()): become_method=None, become_user=None, become_password=None, environment=None):
""" """
Used to insert chunks of code into modules before transfer rather than Used to insert chunks of code into modules before transfer rather than
doing regular python imports. This allows for more efficient transfer in 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. 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: with open(module_path, 'rb') as f:
# read in the module source # read in the module source

@ -76,7 +76,9 @@ def check_args(module, warnings):
module.params[key] = ARGS_DEFAULT_VALUE[key] 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 = 'show run-config commands '
cmd += ' '.join(flags) cmd += ' '.join(flags)
cmd = cmd.strip() cmd = cmd.strip()

@ -66,7 +66,9 @@ def check_args(module, warnings):
module.params[key] = ARGS_DEFAULT_VALUE[key] 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 = 'show running-config '
cmd += ' '.join(flags) cmd += ' '.join(flags)
cmd = cmd.strip() cmd = cmd.strip()

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

@ -40,7 +40,9 @@ from ansible.module_utils.ec2 import camel_dict_to_snake_dict
class DirectConnectError(Exception): 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.msg = msg
self.last_traceback = last_traceback self.last_traceback = last_traceback
self.response = camel_dict_to_snake_dict(response) self.response = camel_dict_to_snake_dict(response)

@ -473,7 +473,7 @@ class AzureRMModuleBase(object):
return None 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. 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. :param enum_modules: List of module names to build enum dependencies from.
:return: serialized result :return: serialized result
''' '''
enum_modules = [] if enum_modules is None else enum_modules
dependencies = dict() dependencies = dict()
if enum_modules: if enum_modules:
for module_name in enum_modules: for module_name in enum_modules:

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

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

@ -68,7 +68,9 @@ def check_args(module, warnings):
'removed in a future version' % key) '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 = 'show running-config '
cmd += ' '.join(flags) cmd += ' '.join(flags)
cmd = cmd.strip() cmd = cmd.strip()

@ -67,7 +67,9 @@ def check_args(module, warnings):
'removed in a future version' % key) '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 = 'show running-config '
cmd += ' '.join(flags) cmd += ' '.join(flags)
cmd = cmd.strip() cmd = cmd.strip()

@ -68,7 +68,9 @@ def check_args(module, warnings):
'removed in a future version' % key) '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 = 'show running-config '
cmd += ' '.join(flags) cmd += ' '.join(flags)
cmd = cmd.strip() cmd = cmd.strip()

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

@ -295,7 +295,7 @@ def gcp_connect(module, provider, get_driver, user_agent_product, user_agent_ver
return gcp 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. 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': ...} params dict {'service_account_email': '...', 'credentials_file': '...', 'project_id': ...}
:rtype: ``tuple`` :rtype: ``tuple``
""" """
scopes = [] if scopes is None else scopes
if not HAS_GOOGLE_AUTH: if not HAS_GOOGLE_AUTH:
module.fail_json(msg='Please install google-auth.') module.fail_json(msg='Please install google-auth.')
@ -348,7 +350,7 @@ def get_google_cloud_credentials(module, scopes=[]):
return (None, None) 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. 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': ...} params dict {'service_account_email': '...', 'credentials_file': '...', 'project_id': ...}
:rtype: ``tuple`` :rtype: ``tuple``
""" """
scopes = [] if scopes is None else scopes
if not HAS_GOOGLE_API_LIB: if not HAS_GOOGLE_API_LIB:
module.fail_json(msg="Please install google-api-python-client library") module.fail_json(msg="Please install google-api-python-client library")
if not scopes: if not scopes:

@ -77,7 +77,9 @@ def get_defaults_flag(module):
return ['full'] 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 = 'show running-config '
cmd += ' '.join(flags) cmd += ' '.join(flags)
cmd = cmd.strip() 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) 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 = 'show running-config '
cmd += ' '.join(flags) cmd += ' '.join(flags)
cmd = cmd.strip() cmd = cmd.strip()

@ -39,7 +39,11 @@ from ansible.module_utils._text import to_native
class ConfigProxy(object): 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 # Actual config object from nitro sdk
self.actual = actual self.actual = actual

@ -91,7 +91,9 @@ class Entity(object):
* default - default value * 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._attributes = attrs or {}
self._module = module self._module = module

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

@ -67,7 +67,7 @@ def transform_list_to_dict(list_):
return ret 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: 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. if its values are null.
:return: list: Lists merged. :return: list: Lists merged.
""" """
ignore_when_null = [] if ignore_when_null is None else ignore_when_null
if not original_list: if not original_list:
return updated_list return updated_list

@ -1,7 +1,9 @@
_DEVICE_CONFIGS = {} _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 = 'show running-config '
cmd += ' '.join(flags) cmd += ' '.join(flags)
cmd = cmd.strip() 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) 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 = 'admin display-config '
cmd += ' '.join(flags) cmd += ' '.join(flags)
cmd = cmd.strip() cmd = cmd.strip()

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

@ -450,7 +450,9 @@ class Ec2Metadata(object):
data = None data = None
return to_text(data) 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 = {} new_fields = {}
for key, value in fields.items(): for key, value in fields.items():
split_fields = key[len(uri):].split('/') split_fields = key[len(uri):].split('/')

@ -1014,7 +1014,9 @@ class ElbManager(object):
self._delete_policy(self.elb.name, policy) self._delete_policy(self.elb.name, policy)
self._create_policy(policy_param, policy_meth, 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: for listener_port in listeners_dict:
if listeners_dict[listener_port].startswith('HTTP'): if listeners_dict[listener_port].startswith('HTTP'):
self.elb_conn.set_lb_policies_of_listener(self.elb.name, listener_port, policy) 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, '') 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. 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. :return: List of strings from list_managed_instances response.
:rtype: ``list`` :rtype: ``list``
""" """
filter_list = ['NONE'] if filter_list is None else filter_list
return [x[field] for x in mig.list_managed_instances() return [x[field] for x in mig.list_managed_instances()
if x['currentAction'] in filter_list] if x['currentAction'] in filter_list]

@ -363,7 +363,9 @@ class LXDContainerManagement(object):
self._change_state('unfreeze') self._change_state('unfreeze')
self.actions.append('unfreez') 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() resp_json = self._get_container_state_json()
network = resp_json['metadata']['network'] or {} network = resp_json['metadata']['network'] or {}
network = dict((k, v) for k, v in network.items() if k not in ignore_devices) 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 return server.image
def create(module, names=[], flavor=None, image=None, meta={}, key_name=None, def create(module, names=None, flavor=None, image=None, meta=None, key_name=None,
files={}, wait=True, wait_timeout=300, disk_config=None, files=None, wait=True, wait_timeout=300, disk_config=None,
group=None, nics=[], extra_create_args={}, user_data=None, group=None, nics=None, extra_create_args=None, user_data=None,
config_drive=False, existing=[], block_device_mapping_v2=[]): 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 cs = pyrax.cloudservers
changed = False changed = False
@ -392,7 +400,10 @@ def create(module, names=[], flavor=None, image=None, meta={}, key_name=None,
module.exit_json(**results) 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 cs = pyrax.cloudservers
changed = False 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, def cloudservers(module, state=None, name=None, flavor=None, image=None,
meta={}, key_name=None, files={}, wait=True, wait_timeout=300, meta=None, key_name=None, files=None, wait=True, wait_timeout=300,
disk_config=None, count=1, group=None, instance_ids=[], disk_config=None, count=1, group=None, instance_ids=None,
exact_count=False, networks=[], count_offset=0, exact_count=False, networks=None, count_offset=0,
auto_increment=False, extra_create_args={}, user_data=None, auto_increment=False, extra_create_args=None, user_data=None,
config_drive=False, boot_from_volume=False, config_drive=False, boot_from_volume=False,
boot_volume=None, boot_volume_size=None, boot_volume=None, boot_volume_size=None,
boot_volume_terminate=False): 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 cs = pyrax.cloudservers
cnw = pyrax.cloud_networks cnw = pyrax.cloud_networks
if not cnw: 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 from ansible.module_utils.six import string_types
def rax_asg(module, cooldown=300, disk_config=None, files={}, flavor=None, def rax_asg(module, cooldown=300, disk_config=None, files=None, flavor=None,
image=None, key_name=None, loadbalancers=[], meta={}, image=None, key_name=None, loadbalancers=None, meta=None,
min_entities=0, max_entities=0, name=None, networks=[], min_entities=0, max_entities=0, name=None, networks=None,
server_name=None, state='present', user_data=None, server_name=None, state='present', user_data=None,
config_drive=False, wait=True, wait_timeout=300): 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 changed = False
au = pyrax.autoscale au = pyrax.autoscale

@ -208,7 +208,9 @@ class NamedResource(object):
class OC(object): class OC(object):
def __init__(self, module, token, host, port, 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.apis = apis
self.version = 'v1' self.version = 'v1'
self.token = token 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) 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""" """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] return [child_to_element(module, child, type) for child in children]

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

@ -121,7 +121,9 @@ class netscaler(object):
def __init__(self, module): def __init__(self, module):
self.module = 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 request_url = self._nsc_protocol + '://' + self._nsc_host + self._nitro_base_url + api_endpoint
data_json = urlencode(data_json) data_json = urlencode(data_json)

@ -148,9 +148,10 @@ from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native 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): nick="ansible", color='none', passwd=False, timeout=30, use_ssl=False, part=True, style=None):
'''send message to IRC''' '''send message to IRC'''
nick_to = [] if nick_to is None else nick_to
colornumbers = { colornumbers = {
'white': "00", 'white': "00",

@ -203,7 +203,9 @@ class LocalSocketThread(Thread):
server = None server = None
terminated = False 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') self.server = kwargs.get('server')
Thread.__init__(self, group, target, name, args, kwargs, Verbose) Thread.__init__(self, group, target, name, args, kwargs, Verbose)
@ -281,7 +283,9 @@ class LocalSocketThread(Thread):
class ThreadWithReturnValue(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) Thread.__init__(self, group, target, name, args, kwargs, Verbose)
self._return = None self._return = None

@ -407,13 +407,15 @@ class ACMEAccount(object):
return result, info 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 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 and False if it already existed (e.g. it was not newly
created) created)
https://tools.ietf.org/html/draft-ietf-acme-acme-02#section-6.3 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: if self.uri is not None:
return True return True

@ -95,8 +95,9 @@ class ModuleArgsParser:
Args may also be munged for certain shell command parameters. Args may also be munged for certain shell command parameters.
""" """
# FIXME: mutable default arg def __init__(self, task_ds=None):
def __init__(self, task_ds=dict()): 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) 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 self._task_ds = task_ds
@ -129,11 +130,13 @@ class ModuleArgsParser:
return (action, args) 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. 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 # final args are the ones we'll eventually return, so first update
# them with any additional args specified, which have lower priority # them with any additional args specified, which have lower priority
# than those which may be parsed/normalized next # than those which may be parsed/normalized next

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

@ -301,7 +301,9 @@ class Role(Base, Become, Conditional, Taggable):
def get_parents(self): def get_parents(self):
return self._parents 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() default_vars = dict()
for dep in self.get_all_dependencies(): for dep in self.get_all_dependencies():
default_vars = combine_vars(default_vars, dep.get_default_vars()) 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) default_vars = combine_vars(default_vars, self._default_vars)
return 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() inherited_vars = dict()
if dep_chain: if dep_chain:
@ -319,7 +323,9 @@ class Role(Base, Become, Conditional, Taggable):
inherited_vars = combine_vars(inherited_vars, parent._role_vars) inherited_vars = combine_vars(inherited_vars, parent._role_vars)
return inherited_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 = {} params = {}
if dep_chain: if dep_chain:
for parent in dep_chain: for parent in dep_chain:
@ -327,7 +333,9 @@ class Role(Base, Become, Conditional, Taggable):
params = combine_vars(params, self._role_params) params = combine_vars(params, self._role_params)
return 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) all_vars = self.get_inherited_vars(dep_chain)
for dep in self.get_all_dependencies(): 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) 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. Builds the environment string to be used when executing the remote task.
''' '''

@ -322,7 +322,9 @@ class Connection(ConnectionBase):
self.shell_id = None self.shell_id = None
self._connect() 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 = { payload = {
'module_entry': to_text(base64.b64encode(to_bytes(cmd))), 'module_entry': to_text(base64.b64encode(to_bytes(cmd))),
'powershell_modules': {}, 'powershell_modules': {},

@ -42,7 +42,8 @@ class PluginLoader:
The first match is used. 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.class_name = class_name
self.base_class = required_base_class self.base_class = required_base_class

@ -220,7 +220,9 @@ class Templar:
The main class for templating, with the main entry-point of template(). 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._loader = loader
self._filters = None self._filters = None
self._tests = None self._tests = None
@ -390,12 +392,13 @@ class Templar:
self._cached_result = {} self._cached_result = {}
def template(self, variable, convert_bare=False, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None, 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 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}}') set to True, the given data will be wrapped as a jinja2 variable ('{{foo}}')
before being sent through the template engine. 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. # Don't template unsafe variables, just return them.
if hasattr(variable, '__UNSAFE__'): 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 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: This is intended for allowing things like:
with_items: a_list_variable with_items: a_list_variable
@ -38,6 +38,7 @@ def safe_eval(expr, locals={}, include_exceptions=False):
Based on: Based on:
http://stackoverflow.com/questions/12523516/using-ast-and-whitelists-to-make-pythons-eval-safe 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 # define certain JSON types
# eg. JSON booleans are unknown to python eval() # eg. JSON booleans are unknown to python eval()

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

@ -28,7 +28,8 @@ from ansible.module_utils._text import to_bytes
class DictDataLoader(DataLoader): 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 assert type(file_mapping) == dict
super(DictDataLoader, self).__init__() super(DictDataLoader, self).__init__()

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

@ -84,7 +84,11 @@ def setup_mod_conn(placeboify, params):
return m, conn 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, return {'customer_gateway_id': cgw,
'static_only': True, 'static_only': True,
'vpn_gateway_id': vgw, 'vpn_gateway_id': vgw,

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

Loading…
Cancel
Save