Bulk autopep8 (modules)

As agreed in 2017-12-07 Core meeting bulk fix pep8 issues

Generated using:
autopep8 1.3.3 (pycodestyle: 2.3.1)
autopep8 -r  --max-line-length 160 --in-place --ignore E305,E402,E722,E741 lib/ansible/modules

Manually fix issues that autopep8 has introduced
This commit is contained in:
John Barker
2017-12-07 16:27:06 +00:00
committed by John R Barker
parent d13d7e9404
commit c57a7f05e1
314 changed files with 3462 additions and 3383 deletions

View File

@@ -185,7 +185,7 @@ def main():
# Send the data to bigpanda
data = json.dumps(body)
headers = {'Authorization':'Bearer %s' % token, 'Content-Type':'application/json'}
headers = {'Authorization': 'Bearer %s' % token, 'Content-Type': 'application/json'}
try:
response, info = fetch_url(module, request_url, data=data, headers=headers)
if info['status'] == 200:

View File

@@ -135,7 +135,7 @@ def main():
choices=['error', 'warning', 'info', 'success']
),
aggregation_key=dict(required=False, default=None),
validate_certs = dict(default='yes', type='bool'),
validate_certs=dict(default='yes', type='bool'),
)
)

View File

@@ -103,7 +103,7 @@ class Icinga2FeatureHelper:
change_applied = True
# RC is not 0 for this already disabled feature, handle it as no change applied
elif re.search("Cannot disable feature '%s'. Target file .* does not exist"
% self.module.params["name"]):
% self.module.params["name"]):
change_applied = False
else:
self.module.fail_json(msg="Fail to disable feature. Command returns %s" % out)

View File

@@ -135,21 +135,22 @@ def post_annotation(module):
response = response.read()
module.exit_json(changed=True, annotation=response)
def main():
module = AnsibleModule(
argument_spec = dict(
user = dict(required=True),
api_key = dict(required=True),
name = dict(required=False),
title = dict(required=True),
source = dict(required=False),
description = dict(required=False),
start_time = dict(required=False, default=None, type='int'),
end_time = dict(require=False, default=None, type='int'),
links = dict(type='list')
)
argument_spec=dict(
user=dict(required=True),
api_key=dict(required=True),
name=dict(required=False),
title=dict(required=True),
source=dict(required=False),
description=dict(required=False),
start_time=dict(required=False, default=None, type='int'),
end_time=dict(require=False, default=None, type='int'),
links=dict(type='list')
)
)
post_annotation(module)

View File

@@ -85,9 +85,9 @@ def follow_log(module, le_path, logs, name=None, logtype=None):
cmd = [le_path, 'follow', log]
if name:
cmd.extend(['--name',name])
cmd.extend(['--name', name])
if logtype:
cmd.extend(['--type',logtype])
cmd.extend(['--type', logtype])
rc, out, err = module.run_command(' '.join(cmd))
if not query_log_status(module, le_path, log):
@@ -100,6 +100,7 @@ def follow_log(module, le_path, logs, name=None, logtype=None):
module.exit_json(changed=False, msg="logs(s) already followed")
def unfollow_log(module, le_path, logs):
""" Unfollows one or more logs if followed. """
@@ -125,13 +126,14 @@ def unfollow_log(module, le_path, logs):
module.exit_json(changed=False, msg="logs(s) already unfollowed")
def main():
module = AnsibleModule(
argument_spec = dict(
path = dict(required=True),
state = dict(default="present", choices=["present", "followed", "absent", "unfollowed"]),
name = dict(required=False, default=None, type='str'),
logtype = dict(required=False, default=None, type='str', aliases=['type'])
argument_spec=dict(
path=dict(required=True),
state=dict(default="present", choices=["present", "followed", "absent", "unfollowed"]),
name=dict(required=False, default=None, type='str'),
logtype=dict(required=False, default=None, type='str', aliases=['type'])
),
supports_check_mode=True
)

View File

@@ -549,7 +549,6 @@ except ImportError:
HAS_LIB_JSON = False
class LogicMonitor(object):
def __init__(self, module, **params):
@@ -667,7 +666,7 @@ class LogicMonitor(object):
for host in hosts:
if (host["hostName"] == hostname and
host["agentId"] == collector["id"]):
host["agentId"] == collector["id"]):
self.module.debug("Host match found")
return host
@@ -688,7 +687,7 @@ class LogicMonitor(object):
self.module.debug("Looking for displayname " + displayname)
self.module.debug("Making RPC call to 'getHost'")
host_json = (json.loads(self.rpc("getHost",
{"displayName": displayname})))
{"displayName": displayname})))
if host_json["status"] == 200:
self.module.debug("RPC call succeeded")
@@ -1028,18 +1027,18 @@ class Collector(LogicMonitor):
else:
self.fail(msg="Error: Unable to retrieve timezone offset")
offsetend = offsetstart + datetime.timedelta(0, int(duration)*60)
offsetend = offsetstart + datetime.timedelta(0, int(duration) * 60)
h = {"agentId": self.id,
"type": 1,
"notifyCC": True,
"year": offsetstart.year,
"month": offsetstart.month-1,
"month": offsetstart.month - 1,
"day": offsetstart.day,
"hour": offsetstart.hour,
"minute": offsetstart.minute,
"endYear": offsetend.year,
"endMonth": offsetend.month-1,
"endMonth": offsetend.month - 1,
"endDay": offsetend.day,
"endHour": offsetend.hour,
"endMinute": offsetend.minute}
@@ -1187,7 +1186,7 @@ class Host(LogicMonitor):
# Used the host information to grab the collector description
# if not provided
if (not hasattr(self.params, "collector") and
"agentDescription" in info):
"agentDescription" in info):
self.module.debug("Setting collector from host response. " +
"Collector " + info["agentDescription"])
self.params["collector"] = info["agentDescription"]
@@ -1238,8 +1237,8 @@ class Host(LogicMonitor):
if self.info:
self.module.debug("Making RPC call to 'getHostProperties'")
properties_json = (json.loads(self.rpc("getHostProperties",
{'hostId': self.info["id"],
"filterSystemProperties": True})))
{'hostId': self.info["id"],
"filterSystemProperties": True})))
if properties_json["status"] == 200:
self.module.debug("RPC call succeeded")
@@ -1411,8 +1410,8 @@ class Host(LogicMonitor):
return True
if (self.collector and
hasattr(self.collector, "id") and
hostresp["agentId"] != self.collector["id"]):
hasattr(self.collector, "id") and
hostresp["agentId"] != self.collector["id"]):
return True
self.module.debug("Comparing groups.")
@@ -1469,7 +1468,7 @@ class Host(LogicMonitor):
self.fail(
msg="Error: Unable to retrieve timezone offset")
offsetend = offsetstart + datetime.timedelta(0, int(duration)*60)
offsetend = offsetstart + datetime.timedelta(0, int(duration) * 60)
h = {"hostId": self.info["id"],
"type": 1,
@@ -1599,7 +1598,7 @@ class Host(LogicMonitor):
hgresp = json.loads(self.rpc("getHostGroup", h))
if (hgresp["status"] == 200 and
hgresp["data"]["appliesTo"] == ""):
hgresp["data"]["appliesTo"] == ""):
g.append(path[-1])
@@ -1632,7 +1631,7 @@ class Host(LogicMonitor):
for prop in propresp:
if prop["name"] not in ignore:
if ("*******" in prop["value"] and
self._verify_property(prop["name"])):
self._verify_property(prop["name"])):
p[prop["name"]] = self.properties[prop["name"]]
else:
p[prop["name"]] = prop["value"]
@@ -1641,7 +1640,7 @@ class Host(LogicMonitor):
# Iterate provided properties and compare to received properties
for prop in self.properties:
if (prop not in p or
p[prop] != self.properties[prop]):
p[prop] != self.properties[prop]):
self.module.debug("Properties mismatch")
return True
self.module.debug("Properties match")
@@ -1703,18 +1702,18 @@ class Datasource(LogicMonitor):
else:
self.fail(msg="Error: Unable to retrieve timezone offset")
offsetend = offsetstart + datetime.timedelta(0, int(duration)*60)
offsetend = offsetstart + datetime.timedelta(0, int(duration) * 60)
h = {"hostDataSourceId": self.id,
"type": 1,
"notifyCC": True,
"year": offsetstart.year,
"month": offsetstart.month-1,
"month": offsetstart.month - 1,
"day": offsetstart.day,
"hour": offsetstart.hour,
"minute": offsetstart.minute,
"endYear": offsetend.year,
"endMonth": offsetend.month-1,
"endMonth": offsetend.month - 1,
"endDay": offsetend.day,
"endHour": offsetend.hour,
"endMinute": offsetend.minute}
@@ -1905,7 +1904,7 @@ class Hostgroup(LogicMonitor):
if properties is not None and group is not None:
self.module.debug("Comparing simple group properties")
if (group["alertEnable"] != self.alertenable or
group["description"] != self.description):
group["description"] != self.description):
return True
@@ -1915,7 +1914,7 @@ class Hostgroup(LogicMonitor):
for prop in properties:
if prop["name"] not in ignore:
if ("*******" in prop["value"] and
self._verify_property(prop["name"])):
self._verify_property(prop["name"])):
p[prop["name"]] = (
self.properties[prop["name"]])
@@ -1965,17 +1964,17 @@ class Hostgroup(LogicMonitor):
self.fail(
msg="Error: Unable to retrieve timezone offset")
offsetend = offsetstart + datetime.timedelta(0, int(duration)*60)
offsetend = offsetstart + datetime.timedelta(0, int(duration) * 60)
h = {"hostGroupId": self.info["id"],
"type": 1,
"year": offsetstart.year,
"month": offsetstart.month-1,
"month": offsetstart.month - 1,
"day": offsetstart.day,
"hour": offsetstart.hour,
"minute": offsetstart.minute,
"endYear": offsetend.year,
"endMonth": offsetend.month-1,
"endMonth": offsetend.month - 1,
"endDay": offsetend.day,
"endHour": offsetend.hour,
"endMinute": offsetend.minute}
@@ -2086,8 +2085,8 @@ def selector(module):
elif module.params["target"] == "host":
# Make sure required parameter collector is specified
if ((module.params["action"] == "add" or
module.params["displayname"] is None) and
module.params["collector"] is None):
module.params["displayname"] is None) and
module.params["collector"] is None):
module.fail_json(
msg="Parameter 'collector' required.")

View File

@@ -242,7 +242,7 @@ class LogicMonitor(object):
for host in hosts:
if (host["hostName"] == hostname and
host["agentId"] == collector["id"]):
host["agentId"] == collector["id"]):
self.module.debug("Host match found")
return host
@@ -263,7 +263,7 @@ class LogicMonitor(object):
self.module.debug("Looking for displayname " + displayname)
self.module.debug("Making RPC call to 'getHost'")
host_json = (json.loads(self.rpc("getHost",
{"displayName": displayname})))
{"displayName": displayname})))
if host_json["status"] == 200:
self.module.debug("RPC call succeeded")
@@ -431,7 +431,7 @@ class Host(LogicMonitor):
# Used the host information to grab the collector description
# if not provided
if (not hasattr(self.params, "collector") and
"agentDescription" in info):
"agentDescription" in info):
self.module.debug("Setting collector from host response. " +
"Collector " + info["agentDescription"])
self.params["collector"] = info["agentDescription"]
@@ -464,8 +464,8 @@ class Host(LogicMonitor):
if self.info:
self.module.debug("Making RPC call to 'getHostProperties'")
properties_json = (json.loads(self.rpc("getHostProperties",
{'hostId': self.info["id"],
"filterSystemProperties": True})))
{'hostId': self.info["id"],
"filterSystemProperties": True})))
if properties_json["status"] == 200:
self.module.debug("RPC call succeeded")

View File

@@ -231,7 +231,7 @@ def which_cmdfile():
'/etc/icinga/icinga.cfg',
# icinga installed from source (default location)
'/usr/local/icinga/etc/icinga.cfg',
]
]
for path in locations:
if os.path.exists(path):
@@ -257,8 +257,7 @@ def main():
'command',
'servicegroup_host_downtime',
'servicegroup_service_downtime',
]
]
module = AnsibleModule(
argument_spec=dict(
@@ -271,8 +270,8 @@ def main():
cmdfile=dict(default=which_cmdfile()),
services=dict(default=None, aliases=['service']),
command=dict(required=False, default=None),
)
)
)
action = module.params['action']
host = module.params['host']
@@ -595,7 +594,6 @@ class Nagios(object):
dt_del_cmd_str = self._fmt_dt_del_str(cmd, host, svc=service, comment=comment)
self._write_command(dt_del_cmd_str)
def schedule_hostgroup_host_downtime(self, hostgroup, minutes=30):
"""
This command is used to schedule downtime for all hosts in a
@@ -934,7 +932,7 @@ class Nagios(object):
cmd = [
"DISABLE_HOST_SVC_NOTIFICATIONS",
"DISABLE_HOST_NOTIFICATIONS"
]
]
nagios_return = True
return_str_list = []
for c in cmd:
@@ -962,7 +960,7 @@ class Nagios(object):
cmd = [
"ENABLE_HOST_SVC_NOTIFICATIONS",
"ENABLE_HOST_NOTIFICATIONS"
]
]
nagios_return = True
return_str_list = []
for c in cmd:
@@ -1027,19 +1025,19 @@ class Nagios(object):
minutes=self.minutes)
elif self.action == 'delete_downtime':
if self.services=='host':
if self.services == 'host':
self.delete_host_downtime(self.host)
elif self.services=='all':
elif self.services == 'all':
self.delete_host_downtime(self.host, comment='')
else:
self.delete_host_downtime(self.host, services=self.services)
elif self.action == "servicegroup_host_downtime":
if self.servicegroup:
self.schedule_servicegroup_host_downtime(servicegroup = self.servicegroup, minutes = self.minutes)
self.schedule_servicegroup_host_downtime(servicegroup=self.servicegroup, minutes=self.minutes)
elif self.action == "servicegroup_service_downtime":
if self.servicegroup:
self.schedule_servicegroup_svc_downtime(servicegroup = self.servicegroup, minutes = self.minutes)
self.schedule_servicegroup_svc_downtime(servicegroup=self.servicegroup, minutes=self.minutes)
# toggle the host AND service alerts
elif self.action == 'silence':
@@ -1077,7 +1075,7 @@ class Nagios(object):
# wtf?
else:
self.module.fail_json(msg="unknown action specified: '%s'" % \
self.module.fail_json(msg="unknown action specified: '%s'" %
self.action)
self.module.exit_json(nagios_commands=self.command_results,

View File

@@ -86,6 +86,7 @@ from ansible.module_utils.six.moves.urllib.parse import urlencode
# Module execution.
#
def main():
module = AnsibleModule(
@@ -99,7 +100,7 @@ def main():
user=dict(required=False),
appname=dict(required=False),
environment=dict(required=False),
validate_certs = dict(default='yes', type='bool'),
validate_certs=dict(default='yes', type='bool'),
),
required_one_of=[['app_name', 'application_id']],
supports_check_mode=True
@@ -117,7 +118,7 @@ def main():
else:
module.fail_json(msg="you must set one of 'app_name' or 'application_id'")
for item in [ "changelog", "description", "revision", "user", "appname", "environment" ]:
for item in ["changelog", "description", "revision", "user", "appname", "environment"]:
if module.params[item]:
params[item] = module.params[item]

View File

@@ -112,7 +112,7 @@ options:
version_added: 1.5.1
'''
EXAMPLES='''
EXAMPLES = '''
# List ongoing maintenance windows using a user/passwd
- pagerduty:
name: companyabc
@@ -171,6 +171,7 @@ import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
def auth_header(user, passwd, token):
if token:
return "Token token=%s" % token
@@ -178,6 +179,7 @@ def auth_header(user, passwd, token):
auth = base64.encodestring('%s:%s' % (user, passwd)).replace('\n', '')
return "Basic %s" % auth
def ongoing(module, name, user, passwd, token):
url = "https://" + name + ".pagerduty.com/api/v1/maintenance_windows/ongoing"
headers = {"Authorization": auth_header(user, passwd, token)}
@@ -203,7 +205,7 @@ def create(module, name, user, passwd, token, requester_id, service, hours, minu
url = "https://" + name + ".pagerduty.com/api/v1/maintenance_windows"
headers = {
'Authorization': auth_header(user, passwd, token),
'Content-Type' : 'application/json',
'Content-Type': 'application/json',
}
request_data = {'maintenance_window': {'start_time': start, 'end_time': end, 'description': desc, 'service_ids': service}}
@@ -225,11 +227,12 @@ def create(module, name, user, passwd, token, requester_id, service, hours, minu
return False, json_out, True
def absent(module, name, user, passwd, token, requester_id, service):
url = "https://" + name + ".pagerduty.com/api/v1/maintenance_windows/" + service[0]
headers = {
'Authorization': auth_header(user, passwd, token),
'Content-Type' : 'application/json',
'Content-Type': 'application/json',
}
request_data = {}
@@ -266,7 +269,7 @@ def main():
hours=dict(default='1', required=False),
minutes=dict(default='0', required=False),
desc=dict(default='Created by Ansible', required=False),
validate_certs = dict(default='yes', type='bool'),
validate_certs=dict(default='yes', type='bool'),
)
)
@@ -280,7 +283,7 @@ def main():
minutes = module.params['minutes']
token = module.params['token']
desc = module.params['desc']
requester_id = module.params['requester_id']
requester_id = module.params['requester_id']
if not token and not (user or passwd):
module.fail_json(msg="neither user and passwd nor token specified")
@@ -290,7 +293,7 @@ def main():
module.fail_json(msg="service not specified")
(rc, out, changed) = create(module, name, user, passwd, token, requester_id, service, hours, minutes, desc)
if rc == 0:
changed=True
changed = True
if state == "ongoing":
(rc, out, changed) = ongoing(module, name, user, passwd, token)
@@ -301,7 +304,6 @@ def main():
if rc != 0:
module.fail_json(msg="failed", result=out)
module.exit_json(msg="success", result=out, changed=changed)

View File

@@ -98,7 +98,7 @@ def pause(checkid, uid, passwd, key):
check = c.get_check(checkid)
name = check.name
result = check.status
#if result != "paused": # api output buggy - accept raw exception for now
# if result != "paused": # api output buggy - accept raw exception for now
# return (True, name, result)
return (False, name, result)
@@ -110,7 +110,7 @@ def unpause(checkid, uid, passwd, key):
check = c.get_check(checkid)
name = check.name
result = check.status
#if result != "up": # api output buggy - accept raw exception for now
# if result != "up": # api output buggy - accept raw exception for now
# return (True, name, result)
return (False, name, result)

View File

@@ -281,12 +281,12 @@ def sensu_check(module, path, name, state='present', backup=False):
if module.params['custom']:
# Convert to json
custom_params = module.params['custom']
overwrited_fields = set(custom_params.keys()) & set(simple_opts + ['type','subdue','subdue_begin','subdue_end'])
overwrited_fields = set(custom_params.keys()) & set(simple_opts + ['type', 'subdue', 'subdue_begin', 'subdue_end'])
if overwrited_fields:
msg = 'You can\'t overwriting standard module parameters via "custom". You are trying overwrite: {opt}'.format(opt=list(overwrited_fields))
module.fail_json(msg=msg)
for k,v in custom_params.items():
for k, v in custom_params.items():
if k in config['checks'][name]:
if not config['checks'][name][k] == v:
changed = True
@@ -298,7 +298,7 @@ def sensu_check(module, path, name, state='present', backup=False):
simple_opts += custom_params.keys()
# Remove obsolete custom params
for opt in set(config['checks'][name].keys()) - set(simple_opts + ['type','subdue','subdue_begin','subdue_end']):
for opt in set(config['checks'][name].keys()) - set(simple_opts + ['type', 'subdue', 'subdue_begin', 'subdue_end']):
changed = True
reasons.append('`custom param {opt}\' was deleted'.format(opt=opt))
del check[opt]
@@ -345,30 +345,30 @@ def sensu_check(module, path, name, state='present', backup=False):
def main():
arg_spec = {'name': {'type': 'str', 'required': True},
'path': {'type': 'str', 'default': '/etc/sensu/conf.d/checks.json'},
'state': {'type': 'str', 'default': 'present', 'choices': ['present', 'absent']},
'backup': {'type': 'bool', 'default': 'no'},
'command': {'type': 'str'},
'handlers': {'type': 'list'},
'subscribers': {'type': 'list'},
'interval': {'type': 'int'},
'timeout': {'type': 'int'},
'ttl': {'type': 'int'},
'handle': {'type': 'bool'},
arg_spec = {'name': {'type': 'str', 'required': True},
'path': {'type': 'str', 'default': '/etc/sensu/conf.d/checks.json'},
'state': {'type': 'str', 'default': 'present', 'choices': ['present', 'absent']},
'backup': {'type': 'bool', 'default': 'no'},
'command': {'type': 'str'},
'handlers': {'type': 'list'},
'subscribers': {'type': 'list'},
'interval': {'type': 'int'},
'timeout': {'type': 'int'},
'ttl': {'type': 'int'},
'handle': {'type': 'bool'},
'subdue_begin': {'type': 'str'},
'subdue_end': {'type': 'str'},
'subdue_end': {'type': 'str'},
'dependencies': {'type': 'list'},
'metric': {'type': 'bool', 'default': 'no'},
'standalone': {'type': 'bool'},
'publish': {'type': 'bool'},
'occurrences': {'type': 'int'},
'refresh': {'type': 'int'},
'aggregate': {'type': 'bool'},
'low_flap_threshold': {'type': 'int'},
'metric': {'type': 'bool', 'default': 'no'},
'standalone': {'type': 'bool'},
'publish': {'type': 'bool'},
'occurrences': {'type': 'int'},
'refresh': {'type': 'int'},
'aggregate': {'type': 'bool'},
'low_flap_threshold': {'type': 'int'},
'high_flap_threshold': {'type': 'int'},
'custom': {'type': 'dict'},
'source': {'type': 'str'},
'custom': {'type': 'dict'},
'source': {'type': 'str'},
}
required_together = [['subdue_begin', 'subdue_end']]

View File

@@ -135,9 +135,9 @@ def sensu_subscription(module, path, name, state='present', backup=False):
def main():
arg_spec = {'name': {'type': 'str', 'required': True},
'path': {'type': 'str', 'default': '/etc/sensu/conf.d/subscriptions.json'},
'state': {'type': 'str', 'default': 'present', 'choices': ['present', 'absent']},
arg_spec = {'name': {'type': 'str', 'required': True},
'path': {'type': 'str', 'default': '/etc/sensu/conf.d/subscriptions.json'},
'state': {'type': 'str', 'default': 'present', 'choices': ['present', 'absent']},
'backup': {'type': 'bool', 'default': 'no'},
}

View File

@@ -124,6 +124,7 @@ def send_deploy_event(module, key, revision_id, deployed_by='Ansible', deployed_
return do_send_request(module, deploy_api, params, key)
def send_annotation_event(module, key, msg, annotated_by='Ansible', level=None, instance_id=None, event_epoch=None):
"""Send an annotation event to Stackdriver"""
annotation_api = "https://event-gateway.stackdriver.com/v1/annotationevent"
@@ -141,13 +142,14 @@ def send_annotation_event(module, key, msg, annotated_by='Ansible', level=None,
return do_send_request(module, annotation_api, params, key)
def do_send_request(module, url, params, key):
data = json.dumps(params)
headers = {
'Content-Type': 'application/json',
'x-stackdriver-apikey': key
}
response, info = fetch_url(module, url, headers=headers, data=data, method='POST')
response, info = fetch_url(module, url, headers=headers, data=data, method='POST')
if info['status'] != 200:
module.fail_json(msg="Unable to send msg: %s" % info['msg'])

View File

@@ -120,10 +120,10 @@ def pauseMonitor(module, params):
def main():
module = AnsibleModule(
argument_spec = dict(
state = dict(required=True, choices=['started', 'paused']),
apikey = dict(required=True),
monitorid = dict(required=True)
argument_spec=dict(
state=dict(required=True, choices=['started', 'paused']),
apikey=dict(required=True),
monitorid=dict(required=True)
),
supports_check_mode=SUPPORTS_CHECK_MODE
)

View File

@@ -186,7 +186,7 @@ class Proxy(object):
old_interface = {}
if 'interface' in self.existing_data and \
len(self.existing_data['interface']) > 0:
old_interface = self.existing_data['interface']
old_interface = self.existing_data['interface']
final_interface = old_interface.copy()
final_interface.update(new_interface)
@@ -206,7 +206,7 @@ class Proxy(object):
for item in data:
if data[item] and item in self.existing_data and \
self.existing_data[item] != data[item]:
parameters[item] = data[item]
parameters[item] = data[item]
if 'interface' in parameters:
parameters.pop('interface')