summaryrefslogtreecommitdiff
path: root/plugins/modules/_vyos_interface.py
diff options
context:
space:
mode:
authoransible-zuul[bot] <48994755+ansible-zuul[bot]@users.noreply.github.com>2019-08-09 18:52:36 +0000
committerGitHub <noreply@github.com>2019-08-09 18:52:36 +0000
commitfbe294b702e757252a66f64edf66bce060e87494 (patch)
tree6910d3c526815c0e21f20cfbccd08bea727cf11c /plugins/modules/_vyos_interface.py
parent4a485b24db1abf87cdf0d4ef2f7acb1159aaab68 (diff)
parent5fb9df4e907a6ab2da7a6c2dafdec9c1971e8d44 (diff)
downloadvyos.vyos-fbe294b702e757252a66f64edf66bce060e87494.tar.gz
vyos.vyos-fbe294b702e757252a66f64edf66bce060e87494.zip
Merge pull request #8 from ansible-network/bt_blacked
Bt blacked Reviewed-by: Paul Belanger https://github.com/pabelanger
Diffstat (limited to 'plugins/modules/_vyos_interface.py')
-rw-r--r--plugins/modules/_vyos_interface.py250
1 files changed, 132 insertions, 118 deletions
diff --git a/plugins/modules/_vyos_interface.py b/plugins/modules/_vyos_interface.py
index e4b989e..ee82107 100644
--- a/plugins/modules/_vyos_interface.py
+++ b/plugins/modules/_vyos_interface.py
@@ -19,9 +19,11 @@
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
-ANSIBLE_METADATA = {'metadata_version': '1.1',
- 'status': ['deprecated'],
- 'supported_by': 'network'}
+ANSIBLE_METADATA = {
+ "metadata_version": "1.1",
+ "status": ["deprecated"],
+ "supported_by": "network",
+}
DOCUMENTATION = """
@@ -174,17 +176,19 @@ from ansible.module_utils._text import to_text
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import exec_command
from ansible.module_utils.network.common.utils import conditional, remove_default_spec
-from ansible_collections.vyos.vyos.plugins.module_utils.network. \
- vyos.vyos import load_config, get_config
-
-from ansible_collections.vyos.vyos.plugins.module_utils.network. \
- vyos.vyos import vyos_argument_spec
+from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import (
+ load_config,
+ get_config,
+)
+from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import (
+ vyos_argument_spec,
+)
def search_obj_in_list(name, lst):
for o in lst:
- if o['name'] == name:
+ if o["name"] == name:
return o
return None
@@ -194,92 +198,92 @@ def map_obj_to_commands(updates):
commands = list()
want, have = updates
- params = ('speed', 'description', 'duplex', 'mtu')
+ params = ("speed", "description", "duplex", "mtu")
for w in want:
- name = w['name']
- disable = w['disable']
- state = w['state']
+ name = w["name"]
+ disable = w["disable"]
+ state = w["state"]
obj_in_have = search_obj_in_list(name, have)
- set_interface = 'set interfaces ethernet ' + name
- delete_interface = 'delete interfaces ethernet ' + name
+ set_interface = "set interfaces ethernet " + name
+ delete_interface = "delete interfaces ethernet " + name
- if state == 'absent' and obj_in_have:
+ if state == "absent" and obj_in_have:
commands.append(delete_interface)
- elif state in ('present', 'up', 'down'):
+ elif state in ("present", "up", "down"):
if obj_in_have:
for item in params:
value = w.get(item)
if value and value != obj_in_have.get(item):
- if item == 'description':
- value = "\'" + str(value) + "\'"
- commands.append(set_interface + ' ' + item + ' ' + str(value))
-
- if disable and not obj_in_have.get('disable', False):
- commands.append(set_interface + ' disable')
- elif not disable and obj_in_have.get('disable', False):
- commands.append(delete_interface + ' disable')
+ if item == "description":
+ value = "'" + str(value) + "'"
+ commands.append(set_interface + " " + item + " " + str(value))
+
+ if disable and not obj_in_have.get("disable", False):
+ commands.append(set_interface + " disable")
+ elif not disable and obj_in_have.get("disable", False):
+ commands.append(delete_interface + " disable")
else:
commands.append(set_interface)
for item in params:
value = w.get(item)
if value:
- if item == 'description':
- value = "\'" + str(value) + "\'"
- commands.append(set_interface + ' ' + item + ' ' + str(value))
+ if item == "description":
+ value = "'" + str(value) + "'"
+ commands.append(set_interface + " " + item + " " + str(value))
if disable:
- commands.append(set_interface + ' disable')
+ commands.append(set_interface + " disable")
return commands
def map_config_to_obj(module):
- data = get_config(module, flags=['| grep interface'])
+ data = get_config(module, flags=["| grep interface"])
obj = []
- for line in data.split('\n'):
- if line.startswith('set interfaces ethernet'):
- match = re.search(r'set interfaces ethernet (\S+)', line, re.M)
+ for line in data.split("\n"):
+ if line.startswith("set interfaces ethernet"):
+ match = re.search(r"set interfaces ethernet (\S+)", line, re.M)
name = match.group(1)
if name:
interface = {}
for item in obj:
- if item['name'] == name:
+ if item["name"] == name:
interface = item
break
if not interface:
- interface = {'name': name}
+ interface = {"name": name}
obj.append(interface)
- match = re.search(r'%s (\S+)' % name, line, re.M)
+ match = re.search(r"%s (\S+)" % name, line, re.M)
if match:
param = match.group(1)
- if param == 'description':
- match = re.search(r'description (.+)', line, re.M)
+ if param == "description":
+ match = re.search(r"description (.+)", line, re.M)
description = match.group(1).strip("'")
- interface['description'] = description
- elif param == 'speed':
- match = re.search(r'speed (\S+)', line, re.M)
+ interface["description"] = description
+ elif param == "speed":
+ match = re.search(r"speed (\S+)", line, re.M)
speed = match.group(1).strip("'")
- interface['speed'] = speed
- elif param == 'mtu':
- match = re.search(r'mtu (\S+)', line, re.M)
+ interface["speed"] = speed
+ elif param == "mtu":
+ match = re.search(r"mtu (\S+)", line, re.M)
mtu = match.group(1).strip("'")
- interface['mtu'] = int(mtu)
- elif param == 'duplex':
- match = re.search(r'duplex (\S+)', line, re.M)
+ interface["mtu"] = int(mtu)
+ elif param == "duplex":
+ match = re.search(r"duplex (\S+)", line, re.M)
duplex = match.group(1).strip("'")
- interface['duplex'] = duplex
- elif param.strip("'") == 'disable':
- interface['disable'] = True
+ interface["duplex"] = duplex
+ elif param.strip("'") == "disable":
+ interface["disable"] = True
return obj
def map_params_to_obj(module):
obj = []
- aggregate = module.params.get('aggregate')
+ aggregate = module.params.get("aggregate")
if aggregate:
for item in aggregate:
for key in item:
@@ -287,28 +291,28 @@ def map_params_to_obj(module):
item[key] = module.params[key]
d = item.copy()
- if d['enabled']:
- d['disable'] = False
+ if d["enabled"]:
+ d["disable"] = False
else:
- d['disable'] = True
+ d["disable"] = True
obj.append(d)
else:
params = {
- 'name': module.params['name'],
- 'description': module.params['description'],
- 'speed': module.params['speed'],
- 'mtu': module.params['mtu'],
- 'duplex': module.params['duplex'],
- 'delay': module.params['delay'],
- 'state': module.params['state'],
- 'neighbors': module.params['neighbors']
+ "name": module.params["name"],
+ "description": module.params["description"],
+ "speed": module.params["speed"],
+ "mtu": module.params["mtu"],
+ "duplex": module.params["duplex"],
+ "delay": module.params["delay"],
+ "state": module.params["state"],
+ "neighbors": module.params["neighbors"],
}
- if module.params['enabled']:
- params.update({'disable': False})
+ if module.params["enabled"]:
+ params.update({"disable": False})
else:
- params.update({'disable': True})
+ params.update({"disable": True})
obj.append(params)
return obj
@@ -318,53 +322,65 @@ def check_declarative_intent_params(module, want, result):
failed_conditions = []
have_neighbors = None
for w in want:
- want_state = w.get('state')
- want_neighbors = w.get('neighbors')
+ want_state = w.get("state")
+ want_neighbors = w.get("neighbors")
- if want_state not in ('up', 'down') and not want_neighbors:
+ if want_state not in ("up", "down") and not want_neighbors:
continue
- if result['changed']:
- sleep(w['delay'])
+ if result["changed"]:
+ sleep(w["delay"])
- command = 'show interfaces ethernet %s' % w['name']
+ command = "show interfaces ethernet %s" % w["name"]
rc, out, err = exec_command(module, command)
if rc != 0:
- module.fail_json(msg=to_text(err, errors='surrogate_then_replace'), command=command, rc=rc)
-
- if want_state in ('up', 'down'):
- match = re.search(r'%s (\w+)' % 'state', out, re.M)
+ module.fail_json(
+ msg=to_text(err, errors="surrogate_then_replace"),
+ command=command,
+ rc=rc,
+ )
+
+ if want_state in ("up", "down"):
+ match = re.search(r"%s (\w+)" % "state", out, re.M)
have_state = None
if match:
have_state = match.group(1)
- if have_state is None or not conditional(want_state, have_state.strip().lower()):
- failed_conditions.append('state ' + 'eq(%s)' % want_state)
+ if have_state is None or not conditional(
+ want_state, have_state.strip().lower()
+ ):
+ failed_conditions.append("state " + "eq(%s)" % want_state)
if want_neighbors:
have_host = []
have_port = []
if have_neighbors is None:
- rc, have_neighbors, err = exec_command(module, 'show lldp neighbors detail')
+ rc, have_neighbors, err = exec_command(
+ module, "show lldp neighbors detail"
+ )
if rc != 0:
- module.fail_json(msg=to_text(err, errors='surrogate_then_replace'), command=command, rc=rc)
+ module.fail_json(
+ msg=to_text(err, errors="surrogate_then_replace"),
+ command=command,
+ rc=rc,
+ )
if have_neighbors:
- lines = have_neighbors.strip().split('Interface: ')
+ lines = have_neighbors.strip().split("Interface: ")
for line in lines:
- field = line.split('\n')
- if field[0].split(',')[0].strip() == w['name']:
+ field = line.split("\n")
+ if field[0].split(",")[0].strip() == w["name"]:
for item in field:
- if item.strip().startswith('SysName:'):
- have_host.append(item.split(':')[1].strip())
- if item.strip().startswith('PortDescr:'):
- have_port.append(item.split(':')[1].strip())
+ if item.strip().startswith("SysName:"):
+ have_host.append(item.split(":")[1].strip())
+ if item.strip().startswith("PortDescr:"):
+ have_port.append(item.split(":")[1].strip())
for item in want_neighbors:
- host = item.get('host')
- port = item.get('port')
+ host = item.get("host")
+ port = item.get("port")
if host and host not in have_host:
- failed_conditions.append('host ' + host)
+ failed_conditions.append("host " + host)
if port and port not in have_port:
- failed_conditions.append('port ' + port)
+ failed_conditions.append("port " + port)
return failed_conditions
@@ -372,75 +388,73 @@ def check_declarative_intent_params(module, want, result):
def main():
""" main entry point for module execution
"""
- neighbors_spec = dict(
- host=dict(),
- port=dict()
- )
+ neighbors_spec = dict(host=dict(), port=dict())
element_spec = dict(
name=dict(),
description=dict(),
speed=dict(),
- mtu=dict(type='int'),
- duplex=dict(choices=['full', 'half', 'auto']),
- enabled=dict(default=True, type='bool'),
- neighbors=dict(type='list', elements='dict', options=neighbors_spec),
- delay=dict(default=10, type='int'),
- state=dict(default='present',
- choices=['present', 'absent', 'up', 'down'])
+ mtu=dict(type="int"),
+ duplex=dict(choices=["full", "half", "auto"]),
+ enabled=dict(default=True, type="bool"),
+ neighbors=dict(type="list", elements="dict", options=neighbors_spec),
+ delay=dict(default=10, type="int"),
+ state=dict(default="present", choices=["present", "absent", "up", "down"]),
)
aggregate_spec = deepcopy(element_spec)
- aggregate_spec['name'] = dict(required=True)
+ aggregate_spec["name"] = dict(required=True)
# remove default in aggregate spec, to handle common arguments
remove_default_spec(aggregate_spec)
argument_spec = dict(
- aggregate=dict(type='list', elements='dict', options=aggregate_spec),
+ aggregate=dict(type="list", elements="dict", options=aggregate_spec)
)
argument_spec.update(element_spec)
argument_spec.update(vyos_argument_spec)
- required_one_of = [['name', 'aggregate']]
- mutually_exclusive = [['name', 'aggregate']]
+ required_one_of = [["name", "aggregate"]]
+ mutually_exclusive = [["name", "aggregate"]]
- required_together = [['speed', 'duplex']]
- module = AnsibleModule(argument_spec=argument_spec,
- required_one_of=required_one_of,
- mutually_exclusive=mutually_exclusive,
- required_together=required_together,
- supports_check_mode=True)
+ required_together = [["speed", "duplex"]]
+ module = AnsibleModule(
+ argument_spec=argument_spec,
+ required_one_of=required_one_of,
+ mutually_exclusive=mutually_exclusive,
+ required_together=required_together,
+ supports_check_mode=True,
+ )
warnings = list()
- result = {'changed': False}
+ result = {"changed": False}
if warnings:
- result['warnings'] = warnings
+ result["warnings"] = warnings
want = map_params_to_obj(module)
have = map_config_to_obj(module)
commands = map_obj_to_commands((want, have))
- result['commands'] = commands
+ result["commands"] = commands
if commands:
commit = not module.check_mode
diff = load_config(module, commands, commit=commit)
if diff:
if module._diff:
- result['diff'] = {'prepared': diff}
- result['changed'] = True
+ result["diff"] = {"prepared": diff}
+ result["changed"] = True
failed_conditions = check_declarative_intent_params(module, want, result)
if failed_conditions:
- msg = 'One or more conditional statements have not been satisfied'
+ msg = "One or more conditional statements have not been satisfied"
module.fail_json(msg=msg, failed_conditions=failed_conditions)
module.exit_json(**result)
-if __name__ == '__main__':
+if __name__ == "__main__":
main()