Skip to content

Commit 41d42d8

Browse files
committed
Dev - Add bond
1 parent 1cdf42b commit 41d42d8

File tree

1 file changed

+78
-48
lines changed

1 file changed

+78
-48
lines changed

networkd.py

+78-48
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,41 @@
11
#!/usr/bin/python
2-
# -*- coding: utf-8 -*-
32

4-
#from __future__ import absolute_import, division, print_function
5-
6-
from ansible.module_utils.basic import AnsibleModule
7-
from ansible.module_utils.common.text.converters import to_text
83
import re
94
import os
10-
5+
from ansible.module_utils.basic import AnsibleModule
6+
from ansible.module_utils.common.text.converters import to_text
117

128
class NetworkdModuleError(Exception):
139
pass
1410

15-
class Networkd(object):
11+
def same_list_file(list1, filepath):
12+
same = True
13+
if os.path.exists(filepath):
14+
with open(filepath) as f:
15+
filepath_lines = f.readlines()
16+
if len(list1) != len(filepath_lines):
17+
same = False
18+
else:
19+
for i in range(0,len(list1),1):
20+
if list1[i] != filepath_lines[i].replace("\n", ""):
21+
same = False
22+
else:
23+
same = False
24+
return same
25+
26+
def write_list_to_file(list1, filepath):
27+
os.makedirs(filepath.split('/')[:-1], mode = 0o755, exist_ok=True)
28+
f = open(filepath, "w")
29+
for it in list1:
30+
f.write(it + "\n")
31+
f.close()
1632

17-
platform = 'Generic'
18-
distribution = None
33+
class Networkd(object):
1934

2035
def __init__(self, module):
2136
self.module = module
2237
self.conn_name = module.params['conn_name']
38+
self.master = module.params['master']
2339
self.state = module.params['state']
2440
self.ifname = module.params['ifname']
2541
self.type = module.params['type']
@@ -28,8 +44,9 @@ def __init__(self, module):
2844
self.routes4 = module.params['routes4']
2945
self.dns4 = module.params['dns4']
3046
self.method4 = module.params['method4']
47+
self.mode = module.params['mode']
3148

32-
def generate_networks(self):
49+
def generate_network(self):
3350
network = []
3451

3552
# MATCH
@@ -44,6 +61,9 @@ def generate_networks(self):
4461
if self.dns4 is not None:
4562
for dns4 in self.dns4:
4663
network.append("DNS=" + dns4)
64+
if self.type == "bond-slave":
65+
if self.master is not None:
66+
network.append("Bond=" + self.master)
4767

4868
# ADDRESS
4969
if self.method4 == "manual":
@@ -65,40 +85,48 @@ def generate_networks(self):
6585

6686
return network
6787

88+
def generate_netdev(self):
89+
netdev = []
90+
91+
# NETDEV
92+
netdev.append("[NetDev]")
93+
netdev.append("Name=" + self.conn_name)
94+
95+
if self.type == "bond":
96+
netdev.append("Kind=bond")
97+
98+
# BOND
99+
if self.type == "bond":
100+
netdev.append("[Bond]")
101+
if self.mode is not None:
102+
netdev.append("Mode=" + self.mode)
103+
else:
104+
netdev.append("Mode=802.3ad")
105+
106+
68107
def main():
69108
# Parsing argument file
70109
module = AnsibleModule(
71110
argument_spec=dict(
72111
state=dict(type='str', required=True, choices=['absent', 'present']),
73112
conn_name=dict(type='str', required=True),
113+
master=dict(type='str'),
74114
ifname=dict(type='str'),
75115
type=dict(type='str',
76116
choices=[
77117
'bond',
78118
'bond-slave',
79-
'bridge',
80-
'bridge-slave',
81-
'dummy',
82119
'ethernet',
83-
'generic',
84-
'gre',
85120
'infiniband',
86-
'ipip',
87-
'sit',
88-
'team',
89-
'team-slave',
90121
'vlan',
91-
'vxlan',
92-
'wifi',
93-
'gsm',
94-
'wireguard',
95-
'vpn',
96122
]),
97123
ip4=dict(type='list', elements='str'),
98124
gw4=dict(type='str'),
99125
routes4=dict(type='list', elements='str'),
100126
dns4=dict(type='list', elements='str'),
101127
method4=dict(type='str', choices=['auto', 'link-local', 'manual', 'shared', 'disabled']),
128+
mode=dict(type='str', default='balance-rr',
129+
choices=['802.3ad', 'active-backup', 'balance-alb', 'balance-rr', 'balance-tlb', 'balance-xor', 'broadcast']),
102130
),
103131
mutually_exclusive=[],
104132
required_if=[],
@@ -110,7 +138,7 @@ def main():
110138

111139
(rc, out, err) = (None, '', '')
112140
result = {'conn_name': networkd.conn_name, 'state': networkd.state}
113-
changed = 0
141+
changed = False
114142

115143

116144
# check for issues
@@ -122,33 +150,35 @@ def main():
122150
# Simply check no files are associated with this conn_name
123151
print("Absent")
124152
elif networkd.state == 'present':
125-
# Generate Network file
126-
network = networkd.generate_networks()
127-
# Read current Network file if exist and compare if changes
128-
network_file = "/etc/systemd/network/" + networkd.conn_name +".network"
129-
if os.path.exists(network_file):
130-
with open("/etc/systemd/network/" + networkd.conn_name +".network") as f:
131-
network_lines = f.readlines()
132-
if len(network) != len(network_lines):
133-
changed = 1
134-
else:
135-
for i in range(0,len(network),1):
136-
if network[i] != network_lines[i].replace("\n", ""):
137-
changed = 1
138-
else:
139-
changed = 1
140153

141-
# Write configuration if changes detected
142-
if changed == 1:
143-
f = open(network_file, "w")
144-
for it in network:
145-
f.write(it + "\n")
146-
f.close()
154+
if networkd.type in ['ethernet','infiniband','bond-slave']:
155+
156+
# Generate Network file
157+
network = networkd.generate_network()
158+
# Read current Network file if exist and compare if changes
159+
network_file = "/etc/systemd/network/" + networkd.conn_name +".network"
160+
# Check if content is the same
161+
changed = not same_list_file(network,network_file)
162+
# Write configuration if changes detected
163+
if changed:
164+
write_list_to_file(network, network_file)
165+
166+
elif networkd.type in ['bond']:
167+
168+
# Generate Netdev file
169+
netdev = networkd.generate_netdev()
170+
# Read current Network file if exist and compare if changes
171+
netdev_file = "/etc/systemd/network/" + networkd.conn_name +".netdev"
172+
# Check if content is the same
173+
changed = not same_list_file(netdev,netdev_file)
174+
# Write configuration if changes detected
175+
if changed:
176+
write_list_to_file(netdev, netdev_file)
147177

148178
# Post actions
149179
if changed == 1:
150-
stdout, stderr = subprocess.Popen("networkctl reload", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).communicate()
151-
stdout, stderr = subprocess.Popen("networkctl reconfigure " + self.conn_name, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).communicate()
180+
stdout, stderr = os.subprocess.Popen("networkctl reload", stdout=os.subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).communicate()
181+
stdout, stderr = os.subprocess.Popen("networkctl reconfigure " + networkd.conn_name, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).communicate()
152182

153183
except NetworkdModuleError as e:
154184
module.fail_json(name=networkd.conn_name, msg=str(e))

0 commit comments

Comments
 (0)