The question was misleading, that is why I edited it
I have two keywords OK
and CRITICAL
. I would like to create lists of these two keywords dynamically according to the length of a list A
and the state of the hosts in list B
.
If list A = [a, b]
, and B = ['master', 'FAULT']
or B = ['master', None]
then I want to create C = ['OK', 'CRITICAL']
.
If B = ['FAULT', 'master']
or B = [None, 'master']
then I want to create C = ['OK', 'CRITICAL']
.
If List A = [a, b, c]
, and B = ['master', 'FAULT', None]
or what ever combination where master
occurs only one time and the other states are FAULT|None
I want to create C = ['OK', 'CRITICAL', 'CRITICAL']
, basically OK
in C
should be at the same index of master
in B
, and so on.
The main idea is I am checking the state of hots in list A
, A
is dynamically created and passed as an argument, so I have no idea about len(A)
. That is why I need to generate the needed lists at run time. I already handled the case where no host is OK, and when no 'CRITICAL' occurs, now I would like to handle these cases, if one host is OK and the rest are CRITICAL, and accordingly generate my sys.exit()
code dynamically according to len(A)
and the host index in A
to identify which host is in CRITICAL state. A small demonstration:
hosts = [a, b]
state = ['master', 'backup']
msg = ['OK', 'CRITICAL']
if state.count('master') != 1:
print(', '.join('CRITICAL - host {} state is {}'.format(hosts[i], state[0]) for i in range(len(hosts))))
sys.exit(2)
# Problem, how many if statements are needed? How can this be created dynamically
elif state[0] == 'master' and 'backup' not in state:
print(', '.join('{} - host {} state is {}'.format(msg[i], hosts[i], state[i]) for i in range(len(hosts))))
sys.exit(1)
...........................
...........................
...........................
else:
print(', '.join("OK - host {} state is {}".format(hosts[i], state[i]) for i in range(len(hosts))))
sys.exit(0)
After all I need to generate [msg]
for the print
function, and it should be dynamically, so using [state]
to get the matched [msg]
according to the OK|master
index.
Thanks for any help.
Answer:
a = ['master', 'FAULT', None]
b = ['FAULT', None, 'master']
c = [None, 'master', 'FAULT']
def getMsg(state):
d = []
for i in state:
if i == 'master':
d.append('OK')
else:
d.append('CRITICAL')
return(d)
print(getMsg(a)) # --> ['OK', 'CRITICAL', 'CRITICAL']
print(getMsg(b)) # --> ['CRITICAL', 'CRITICAL', 'OK']
print(getMsg(c)) # --> ['CRITICAL', 'OK', 'CRITICAL']
and the create a loop:
....................
....................
state = ['master', 'FAULT', None]
msg = getMsg(state)
if 'master' in state and 'backup' not in state:
print(', '.join('{} - host {} state is {}'.format(msg[i], hosts[i], state[i]) for i in range(len(hosts))))
sys.exit(1)
....................
....................
Once again sorry for the misleading formulation.