mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-04-18 09:51:41 +00:00
Reformat everything.
This commit is contained in:
parent
3f2213791a
commit
340ff8586d
1008 changed files with 61301 additions and 58309 deletions
|
|
@ -271,6 +271,7 @@ from itertools import zip_longest
|
|||
LXML_ETREE_IMP_ERR = None
|
||||
try:
|
||||
import lxml.etree
|
||||
|
||||
HAS_LXML_ETREE = True
|
||||
except ImportError:
|
||||
LXML_ETREE_IMP_ERR = traceback.format_exc()
|
||||
|
|
@ -279,6 +280,7 @@ except ImportError:
|
|||
XMLJSON_COBRA_IMP_ERR = None
|
||||
try:
|
||||
from xmljson import cobra
|
||||
|
||||
HAS_XMLJSON_COBRA = True
|
||||
except ImportError:
|
||||
XMLJSON_COBRA_IMP_ERR = traceback.format_exc()
|
||||
|
|
@ -292,31 +294,31 @@ from ansible_collections.community.general.plugins.module_utils.datetime import
|
|||
)
|
||||
|
||||
|
||||
def imc_response(module, rawoutput, rawinput=''):
|
||||
''' Handle IMC returned data '''
|
||||
def imc_response(module, rawoutput, rawinput=""):
|
||||
"""Handle IMC returned data"""
|
||||
xmloutput = lxml.etree.fromstring(rawoutput)
|
||||
result = cobra.data(xmloutput)
|
||||
|
||||
# Handle errors
|
||||
if xmloutput.get('errorCode') and xmloutput.get('errorDescr'):
|
||||
if xmloutput.get("errorCode") and xmloutput.get("errorDescr"):
|
||||
if rawinput:
|
||||
result['input'] = rawinput
|
||||
result['output'] = rawoutput
|
||||
result['error_code'] = xmloutput.get('errorCode')
|
||||
result['error_text'] = xmloutput.get('errorDescr')
|
||||
result["input"] = rawinput
|
||||
result["output"] = rawoutput
|
||||
result["error_code"] = xmloutput.get("errorCode")
|
||||
result["error_text"] = xmloutput.get("errorDescr")
|
||||
module.fail_json(msg=f"Request failed: {result['error_text']}", **result)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def logout(module, url, cookie, timeout):
|
||||
''' Perform a logout, if needed '''
|
||||
"""Perform a logout, if needed"""
|
||||
data = f'<aaaLogout cookie="{cookie}" inCookie="{cookie}"/>'
|
||||
resp, auth = fetch_url(module, url, data=data, method="POST", timeout=timeout)
|
||||
|
||||
|
||||
def merge(one, two):
|
||||
''' Merge two complex nested datastructures into one'''
|
||||
"""Merge two complex nested datastructures into one"""
|
||||
if isinstance(one, dict) and isinstance(two, dict):
|
||||
copy = dict(one)
|
||||
copy.update({key: merge(one.get(key, None), two[key]) for key in two})
|
||||
|
|
@ -331,34 +333,34 @@ def merge(one, two):
|
|||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec=dict(
|
||||
hostname=dict(type='str', required=True, aliases=['host', 'ip']),
|
||||
username=dict(type='str', default='admin', aliases=['user']),
|
||||
password=dict(type='str', default='password', no_log=True),
|
||||
content=dict(type='str'),
|
||||
path=dict(type='path', aliases=['config_file', 'src']),
|
||||
protocol=dict(type='str', default='https', choices=['http', 'https']),
|
||||
timeout=dict(type='int', default=60),
|
||||
validate_certs=dict(type='bool', default=True),
|
||||
hostname=dict(type="str", required=True, aliases=["host", "ip"]),
|
||||
username=dict(type="str", default="admin", aliases=["user"]),
|
||||
password=dict(type="str", default="password", no_log=True),
|
||||
content=dict(type="str"),
|
||||
path=dict(type="path", aliases=["config_file", "src"]),
|
||||
protocol=dict(type="str", default="https", choices=["http", "https"]),
|
||||
timeout=dict(type="int", default=60),
|
||||
validate_certs=dict(type="bool", default=True),
|
||||
),
|
||||
supports_check_mode=True,
|
||||
mutually_exclusive=[['content', 'path']],
|
||||
mutually_exclusive=[["content", "path"]],
|
||||
)
|
||||
|
||||
if not HAS_LXML_ETREE:
|
||||
module.fail_json(msg=missing_required_lib('lxml'), exception=LXML_ETREE_IMP_ERR)
|
||||
module.fail_json(msg=missing_required_lib("lxml"), exception=LXML_ETREE_IMP_ERR)
|
||||
|
||||
if not HAS_XMLJSON_COBRA:
|
||||
module.fail_json(msg=missing_required_lib('xmljson >= 0.1.8'), exception=XMLJSON_COBRA_IMP_ERR)
|
||||
module.fail_json(msg=missing_required_lib("xmljson >= 0.1.8"), exception=XMLJSON_COBRA_IMP_ERR)
|
||||
|
||||
hostname = module.params['hostname']
|
||||
username = module.params['username']
|
||||
password = module.params['password']
|
||||
hostname = module.params["hostname"]
|
||||
username = module.params["username"]
|
||||
password = module.params["password"]
|
||||
|
||||
content = module.params['content']
|
||||
path = module.params['path']
|
||||
content = module.params["content"]
|
||||
path = module.params["path"]
|
||||
|
||||
protocol = module.params['protocol']
|
||||
timeout = module.params['timeout']
|
||||
protocol = module.params["protocol"]
|
||||
timeout = module.params["timeout"]
|
||||
|
||||
result = dict(
|
||||
failed=False,
|
||||
|
|
@ -371,69 +373,69 @@ def main():
|
|||
if os.path.isfile(path):
|
||||
file_exists = True
|
||||
else:
|
||||
module.fail_json(msg=f'Cannot find/access path:\n{path}')
|
||||
module.fail_json(msg=f"Cannot find/access path:\n{path}")
|
||||
|
||||
start = now()
|
||||
|
||||
# Perform login first
|
||||
url = f'{protocol}://{hostname}/nuova'
|
||||
url = f"{protocol}://{hostname}/nuova"
|
||||
data = f'<aaaLogin inName="{username}" inPassword="{password}"/>'
|
||||
resp, auth = fetch_url(module, url, data=data, method='POST', timeout=timeout)
|
||||
if resp is None or auth['status'] != 200:
|
||||
result['elapsed'] = (now() - start).seconds
|
||||
resp, auth = fetch_url(module, url, data=data, method="POST", timeout=timeout)
|
||||
if resp is None or auth["status"] != 200:
|
||||
result["elapsed"] = (now() - start).seconds
|
||||
module.fail_json(msg=f"Task failed with error {auth['status']}: {auth['msg']}", **result)
|
||||
result.update(imc_response(module, resp.read()))
|
||||
|
||||
# Store cookie for future requests
|
||||
cookie = ''
|
||||
cookie = ""
|
||||
try:
|
||||
cookie = result['aaaLogin']['attributes']['outCookie']
|
||||
cookie = result["aaaLogin"]["attributes"]["outCookie"]
|
||||
except Exception:
|
||||
module.fail_json(msg='Could not find cookie in output', **result)
|
||||
module.fail_json(msg="Could not find cookie in output", **result)
|
||||
|
||||
try:
|
||||
# Prepare request data
|
||||
if content:
|
||||
rawdata = content
|
||||
elif file_exists:
|
||||
with open(path, 'r') as config_object:
|
||||
with open(path, "r") as config_object:
|
||||
rawdata = config_object.read()
|
||||
|
||||
# Wrap the XML documents in a <root> element
|
||||
xmldata = lxml.etree.fromstring('<root>%s</root>' % rawdata.replace('\n', ''))
|
||||
xmldata = lxml.etree.fromstring("<root>%s</root>" % rawdata.replace("\n", ""))
|
||||
|
||||
# Handle each XML document separately in the same session
|
||||
for xmldoc in list(xmldata):
|
||||
if xmldoc.tag is lxml.etree.Comment:
|
||||
continue
|
||||
# Add cookie to XML
|
||||
xmldoc.set('cookie', cookie)
|
||||
xmldoc.set("cookie", cookie)
|
||||
data = lxml.etree.tostring(xmldoc)
|
||||
|
||||
# Perform actual request
|
||||
resp, info = fetch_url(module, url, data=data, method='POST', timeout=timeout)
|
||||
if resp is None or info['status'] != 200:
|
||||
result['elapsed'] = (now() - start).seconds
|
||||
resp, info = fetch_url(module, url, data=data, method="POST", timeout=timeout)
|
||||
if resp is None or info["status"] != 200:
|
||||
result["elapsed"] = (now() - start).seconds
|
||||
module.fail_json(msg=f"Task failed with error {info['status']}: {info['msg']}", **result)
|
||||
|
||||
# Merge results with previous results
|
||||
rawoutput = resp.read()
|
||||
result = merge(result, imc_response(module, rawoutput, rawinput=data))
|
||||
result['response'] = info['msg']
|
||||
result['status'] = info['status']
|
||||
result["response"] = info["msg"]
|
||||
result["status"] = info["status"]
|
||||
|
||||
# Check for any changes
|
||||
# NOTE: Unfortunately IMC API always report status as 'modified'
|
||||
xmloutput = lxml.etree.fromstring(rawoutput)
|
||||
results = xmloutput.xpath('/configConfMo/outConfig/*/@status')
|
||||
result['changed'] = ('modified' in results)
|
||||
results = xmloutput.xpath("/configConfMo/outConfig/*/@status")
|
||||
result["changed"] = "modified" in results
|
||||
|
||||
# Report success
|
||||
result['elapsed'] = (now() - start).seconds
|
||||
result["elapsed"] = (now() - start).seconds
|
||||
module.exit_json(**result)
|
||||
finally:
|
||||
logout(module, url, cookie, timeout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue