-
Notifications
You must be signed in to change notification settings - Fork 3
/
cmtinv
executable file
·2138 lines (1921 loc) · 80.5 KB
/
cmtinv
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /bin/sh
# vim: ts=4 filetype=python expandtab shiftwidth=4 softtabstop=4 syntax=python
''''eval version=$( ls /usr/bin/python3.* | \
grep '.*[0-9]$' | sort -nr -k2 -t. | head -n1 ) && \
version=${version##/usr/bin/python3.} && [ ${version} ] && \
[ ${version} -ge 9 ] && exec /usr/bin/python3.${version} "$0" "$@" || \
exec /usr/bin/env python3 "$0" "$@"' #'''
# The above hack is to handle distros where /usr/bin/python3
# doesn't point to the latest version of python3 they provide
# Requires: python3 (>= 3.9)
# Requires: python3-natsort
#
# Copyright the Cluster Management Toolkit for Kubernetes contributors.
# SPDX-License-Identifier: MIT
# pylint: disable=too-many-lines
import errno
from getpass import getuser
import os
from pathlib import Path
import re
import sys
from typing import Any, cast, Optional, Union
try:
import yaml
except ModuleNotFoundError: # pragma: no cover
sys.exit("ModuleNotFoundError: Could not import yaml; "
"you may need to (re-)run `cmt-install` or `pip3 install PyYAML`; aborting.")
try:
from natsort import natsorted
except ModuleNotFoundError: # pragma: no cover
sys.exit("ModuleNotFoundError: Could not import natsort; "
"you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")
from clustermanagementtoolkit.cmttypes import deep_get, deep_get_with_fallback, DictPath, FilePath
from clustermanagementtoolkit.cmttypes import FilePathAuditError, ProgrammingError, UnknownError
from clustermanagementtoolkit.cmttypes import SecurityStatus
from clustermanagementtoolkit.cmtpaths import SYSTEM_ANSIBLE_PLAYBOOK_DIR, ANSIBLE_PLAYBOOK_DIR
from clustermanagementtoolkit.cmtpaths import HOMEDIR, SSH_DIR
from clustermanagementtoolkit.cmtpaths import DEFAULT_THEME_FILE, KUBE_CONFIG_FILE
from clustermanagementtoolkit import cmtio
from clustermanagementtoolkit import cmtio_yaml
from clustermanagementtoolkit.commandparser import parse_commandline
from clustermanagementtoolkit.ansible_helper import ansible_configuration
from clustermanagementtoolkit.ansible_helper import ansible_get_inventory_pretty
from clustermanagementtoolkit.ansible_helper import ansible_get_inventory_dict
from clustermanagementtoolkit.ansible_helper import ansible_get_groups, ansible_get_groups_by_host
from clustermanagementtoolkit.ansible_helper import ansible_get_hosts_by_group
from clustermanagementtoolkit.ansible_helper import ansible_add_hosts, ansible_remove_hosts
from clustermanagementtoolkit.ansible_helper import ansible_create_groups, ansible_remove_groups
from clustermanagementtoolkit.ansible_helper import ansible_set_vars
from clustermanagementtoolkit.ansible_helper import ansible_set_hostvars, ansible_unset_hostvars
from clustermanagementtoolkit.ansible_helper import ansible_set_groupvars, ansible_unset_groupvars
from clustermanagementtoolkit.ansible_helper import ansible_ping
from clustermanagementtoolkit.ansible_helper import ansible_print_play_results
from clustermanagementtoolkit.ansible_helper import ansible_run_playbook_on_selection
from clustermanagementtoolkit.ansible_helper import ANSIBLE_INVENTORY
from clustermanagementtoolkit import cmtlib
from clustermanagementtoolkit.cmtlib import read_cmtconfig, get_latest_upstream_version
from clustermanagementtoolkit import kubernetes_helper
from clustermanagementtoolkit import checks
from clustermanagementtoolkit.ansithemeprint import ANSIThemeStr, ansithemeprint
from clustermanagementtoolkit.ansithemeprint import ansithemestr_join_list
from clustermanagementtoolkit import about
PROGRAMDESCRIPTION = "Query or modify the host inventory"
PROGRAMAUTHORS = "Written by David Weinehall."
# pylint: disable-next=unused-argument
def set_host_vars(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Set host-specific variables
Parameters:
options ([(str, str)]): Unused
args ([str,str]):
(str): Comma-separated list of key:value pairs
(str): Comma-separated list of hosts
Returns:
(int): 0
"""
hostvars: list[tuple[str, Union[str, int]]] = []
keyvals: list[str] = args[0].split(",")
hosts: list[str] = args[1].split(",")
for keyval in keyvals:
try:
key, value = keyval.split(":")
except ValueError:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": Setting a variable requires a ", "default"),
ANSIThemeStr("KEY", "argument"),
ANSIThemeStr(":", "separator"),
ANSIThemeStr("VALUE ", "argument"),
ANSIThemeStr("pair.", "default")], stderr=True)
print()
ansithemeprint([ANSIThemeStr("Try “", "default"),
ANSIThemeStr(f"{about.INVENTORY_PROGRAM_NAME} ", "programname"),
ANSIThemeStr("help", "command"),
ANSIThemeStr("“ for more information.", "default")], stderr=True)
sys.exit(errno.EINVAL)
hostvars.append((key, value))
# Set vars
if hostvars:
retval = ansible_set_hostvars(inventory=ANSIBLE_INVENTORY,
hosts=hosts, hostvars=hostvars)
if not retval:
raise ProgrammingError(f"Failed to set vars for hosts {hosts}")
return 0
# pylint: disable-next=unused-argument
def set_group_vars(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Set group-specific variables
Parameters:
options ([(str, str)]): Unused
args ([str,str]):
(str): Comma-separated list of key:value pairs
(str): Comma-separated list of groups
Returns:
(int): 0
"""
groupvars = []
keyvals = args[0].split(",")
groups = args[1].split(",")
for keyval in keyvals:
try:
key, value = keyval.split(":")
except ValueError:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": Setting a variable requires a ", "default"),
ANSIThemeStr("KEY", "argument"),
ANSIThemeStr(":", "separator"),
ANSIThemeStr("VALUE ", "argument"),
ANSIThemeStr("pair.", "default")], stderr=True)
print()
ansithemeprint([ANSIThemeStr("Try “", "default"),
ANSIThemeStr(f"{about.INVENTORY_PROGRAM_NAME} ", "programname"),
ANSIThemeStr("help", "command"),
ANSIThemeStr("“ for more information.", "default")], stderr=True)
sys.exit(errno.EINVAL)
groupvars.append((key, value))
# Set vars
if groupvars:
retval = ansible_set_groupvars(inventory=ANSIBLE_INVENTORY,
groups=groups, groupvars=groupvars)
if not retval:
raise ProgrammingError(f"Failed to set vars for groups {groups}")
return 0
def set_global_vars(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Set global variables
Parameters:
options ([(str, str)]): Unused
args ([str]): Comma-separated list of key:value pairs
Returns:
Return value from set_group_vars()
"""
return set_group_vars(options=options, args=[args[0], "all"])
# pylint: disable-next=unused-argument
def unset_host_vars(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Unset host-specific variables
Parameters:
options ([(str, str)]): Unused
args ([str]):
(str): Comma-separated list of keys
(str): Comma-separated list of hosts
Returns:
(int): 0
"""
hostvars = args[0].split(",")
hosts = args[1].split(",")
# Unset vars
if hostvars:
retval = ansible_unset_hostvars(inventory=ANSIBLE_INVENTORY,
hosts=hosts, hostvars=hostvars)
if not retval:
raise ProgrammingError(f"Failed to unset vars for hosts {hosts}")
return 0
# pylint: disable-next=unused-argument
def unset_group_vars(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Unset group-specific variables
Parameters:
options ([(str, str)]): Unused
args ([str]):
(str): Comma-separated list of keys
(str): Comma-separated list of groups
Returns:
(int): 0
"""
groupvars = args[0].split(",")
groups = args[1].split(",")
# Unset vars
if groupvars:
retval = ansible_unset_groupvars(inventory=ANSIBLE_INVENTORY,
groups=groups, groupvars=groupvars)
if not retval:
raise ProgrammingError(f"Failed to unset vars for groups {groups}")
return 0
def unset_global_vars(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Unset global variables
Parameters:
options ([(str, str)]): Unused
args ([str]): Comma-separated list of keys
Returns:
Return value from unset_group_vars()
"""
return unset_group_vars(options=options, args=[args[0], "all"])
def add_groups(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Add groups
Parameters:
options ([(str, str)]): List of opt, optarg
args ([str]): Comma-separated list of groups
Returns:
(int): 0
"""
groupvars = []
groups = args[0].split(",")
# We should not try to add "all" (it may cause unexpected issues with variables)
if "all" in groups:
ansithemeprint([ANSIThemeStr("Warning", "warning"),
ANSIThemeStr(": Ignoring attempt to add group “", "default"),
ANSIThemeStr("all", "argument"),
ANSIThemeStr("“.", "default")], stderr=True)
groups.remove("all")
if not groups:
return 0
for opt, optarg in options:
if opt == "--vars":
tmp = optarg.split(",")
for var in tmp:
key, value = var.split(":")
groupvars.append((key, value))
# Add the groups
retval = ansible_create_groups(inventory=ANSIBLE_INVENTORY, groups=groups)
if not retval:
raise ProgrammingError(f"Failed to add {groups} to inventory")
# Set vars
if groupvars:
retval = ansible_set_groupvars(inventory=ANSIBLE_INVENTORY,
groups=groups, groupvars=groupvars)
if not retval:
raise ProgrammingError(f"Failed to set vars {groupvars} for groups {groups}")
return 0
# pylint: disable-next=too-many-branches
def add_hosts(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Add hosts
Parameters:
options ([(str, str)]): List of opt, optarg
args ([str]): Comma-separated list of hosts
Returns:
(int): 0
"""
groups = []
hostvars = []
hosts = args[0].split(",")
if len(args) > 1:
groups = args[1].split(",")
for opt, optarg in options:
if opt == "--vars":
tmp = optarg.split(",")
for var in tmp:
key, value = var.split(":")
hostvars.append((key, value))
elif opt == "--groups":
if groups:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": Invalid option; “", "default"),
ANSIThemeStr(f"{opt}", "option"),
ANSIThemeStr("“ cannot be used with ", "default"),
ANSIThemeStr("HOST", "argument"),
ANSIThemeStr(",", "separator"),
ANSIThemeStr("... ", "argument"),
ANSIThemeStr("GROUP", "argument"),
ANSIThemeStr(",", "separator"),
ANSIThemeStr("... ", "argument"),
ANSIThemeStr("syntax.", "default")], stderr=True)
print()
ansithemeprint([ANSIThemeStr("Try “", "default"),
ANSIThemeStr(f"{about.INVENTORY_PROGRAM_NAME} ", "programname"),
ANSIThemeStr("help", "command"),
ANSIThemeStr("“ for more information.", "default")],
stderr=True)
sys.exit(errno.EINVAL)
groups = optarg.split(",")
retval = True
# Add the host to every specified group
if not groups:
retval = ansible_add_hosts(inventory=ANSIBLE_INVENTORY, hosts=hosts, skip_all=False)
if not retval:
raise ProgrammingError(f"Failed to add {hosts}")
else:
group = ""
for group in groups:
retval = ansible_add_hosts(inventory=ANSIBLE_INVENTORY,
hosts=hosts, group=group, skip_all=False)
if not retval:
raise ProgrammingError(f"Failed to add {hosts} to group {group}")
# Set vars
if hostvars:
retval = ansible_set_hostvars(inventory=ANSIBLE_INVENTORY, hosts=hosts, hostvars=hostvars)
if not retval:
raise ProgrammingError(f"Failed to set vars for hosts {hosts}")
return 0
def format_members(group: str, members: list[str]) -> list[ANSIThemeStr]:
"""
Format a list of group members as a themearray
Parameters:
group (str): The name of the group
members ([str]): A list of hostnames
Returns:
formatted ([ANSIThemeStr]): A themearray
"""
formatted = [ANSIThemeStr(f"{group}: ", "default")]
i = 0
for i, member in enumerate(members):
if i < len(members) - 1:
formatted += [ANSIThemeStr(member, "yaml_key"),
ANSIThemeStr(", ", "separator")]
else:
formatted += [ANSIThemeStr(member, "yaml_key")]
return formatted
def remove_groups(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Remove groups
Parameters:
options ([(str, str)]): List of opt, optarg
args ([str]): Comma-separated list of groups
Returns:
(int): 0
"""
extrahosts = []
forceneeded = False
force = False
groups = args[0].split(",")
for opt, _optarg in options:
if opt == "--force":
force = True
if "all" in groups:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": The group “", "default"),
ANSIThemeStr("all", "argument"),
ANSIThemeStr("“ cannot be removed.", "default")], stderr=True)
print()
ansithemeprint([ANSIThemeStr("Try “", "default"),
ANSIThemeStr(f"{about.INVENTORY_PROGRAM_NAME} ", "programname"),
ANSIThemeStr("help", "command"),
ANSIThemeStr("“ for more information.", "default")], stderr=True)
sys.exit(errno.EINVAL)
for group in groups:
grouphosts = ansible_get_hosts_by_group(ANSIBLE_INVENTORY, group)
if grouphosts:
forceneeded = True
extrahosts.append((group, grouphosts))
if forceneeded and not force:
if forceneeded:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": The following groups are non-empty:", "default")])
for group, hosts in extrahosts:
ansithemeprint(format_members(group, hosts))
print()
ansithemeprint([ANSIThemeStr("Removing groups that still contain hosts “", "default"),
ANSIThemeStr("requires specifying “", "default"),
ANSIThemeStr("--force", "option"),
ANSIThemeStr("“.", "default")], stderr=True)
print()
ansithemeprint([ANSIThemeStr("Try “", "default"),
ANSIThemeStr(f"{about.INVENTORY_PROGRAM_NAME} ", "programname"),
ANSIThemeStr("help", "command"),
ANSIThemeStr("“ for more information.", "default")], stderr=True)
sys.exit(errno.EINVAL)
retval = ansible_remove_groups(inventory=ANSIBLE_INVENTORY, groups=groups, force=force)
if not retval:
raise ProgrammingError(f"Failed to remove {groups}")
return 0
def get_cluster_name() -> Optional[str]:
"""
Return the name of the cluster
Returns:
cluster_name (str): On success
None (None): On failure
"""
try:
d1 = cmtio_yaml.secure_read_yaml(KUBE_CONFIG_FILE)
except FileNotFoundError:
return None
current_context = d1.get("current-context", None)
if current_context is None:
return None
cluster_name = None
for context in d1.get("contexts", []):
if context.get("name", "") == current_context:
cluster_name = context["context"].get("cluster", None)
break
return cluster_name
# pylint: disable-next=unused-argument,too-many-locals,too-many-branches
def rebuild_inventory(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Build an inventory based on information from Kubernetes
Parameters:
options ([(opt, optarg)]): A list of opt, optarg
args ([str]): Unused
Returns:
(int): 0
"""
force = False
for opt, _optarg in options:
if opt == "--force":
force = True
# Is there a pre-existing inventory?
if Path(ANSIBLE_INVENTORY).is_file() and not force:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": Overwriting an existing ", "default"),
ANSIThemeStr("inventory requires specifying “", "default"),
ANSIThemeStr("--force", "option"),
ANSIThemeStr("“.", "default")], stderr=True)
print()
ansithemeprint([ANSIThemeStr("Try “", "default"),
ANSIThemeStr(f"{about.INVENTORY_PROGRAM_NAME} ", "programname"),
ANSIThemeStr("help", "command"),
ANSIThemeStr("“ for more information.", "default")], stderr=True)
sys.exit(errno.EINVAL)
# We ideally want to iterate over all clusters here,
# but for now we only import the current-context.
cluster_name = get_cluster_name()
if cluster_name is None:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": Could not obtain cluster name; do you ", "default"),
ANSIThemeStr("have a cluster available? Aborting.", "default")],
stderr=True)
sys.exit(errno.ENOENT)
kh = kubernetes_helper.KubernetesHelper(about.PROGRAM_SUITE_NAME,
about.PROGRAM_SUITE_VERSION, None)
vlist, status = kh.get_list_by_kind_namespace(("Node", ""), "")
if status != 200:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": API-server returned ", "default"),
ANSIThemeStr(f"{status}", "errorvalue"),
ANSIThemeStr("; aborting.", "default")], stderr=True)
sys.exit(errno.EINVAL)
if vlist is None:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": API-server did not return any data", "default")],
stderr=True)
sys.exit(errno.EINVAL)
for node in vlist:
roles = kubernetes_helper.get_node_roles(cast(dict, node))
if "control-plane" in roles:
groups = ["all", "controlplane", cluster_name]
else:
groups = ["all", "nodes", cluster_name]
group = ""
hosts = [deep_get(node, DictPath("metadata#name"))]
retval = True
for group in groups:
retval = ansible_add_hosts(inventory=ANSIBLE_INVENTORY,
hosts=hosts, group=group, skip_all=False)
if not retval:
raise ProgrammingError(f"Failed to add {hosts} to group {group}")
# Finally import the hostkey into authorized_keys
pubkey = None
try:
tmp = cmtio.secure_read_string(SSH_DIR.joinpath("id_ecdsa.pub"))
except FilePathAuditError as e:
# We cannot import non-existing hostkeys...
if "SecurityStatus.DOES_NOT_EXIST" in str(e):
tmp = None
if tmp is not None:
tmplines = tmp.splitlines()
pubkey = tmplines[0]
if pubkey is None or not pubkey:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": Failed to read ", "default"),
ANSIThemeStr(f"{HOMEDIR}/.ssh/id_ecdsa.pub", "path"),
ANSIThemeStr("; aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
values = {
"authorized_keys": [pubkey],
}
ansible_set_vars(ANSIBLE_INVENTORY, "all", values)
return 0
def remove_hosts(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Remove hosts
Parameters:
options ([(str, str)]): List of opt, optarg
args ([str]): Comma-separated list of hosts
Returns:
(int): 0
"""
groups = ["all"]
extragroups = []
forceneeded = False
force = False
hosts = args[0].split(",")
if len(args) > 1:
groups = args[1].split(",")
# This returns a YAML tree with the inventory of nodes
inventory_dict = ansible_get_inventory_dict()
# If the hosts are only members of "all"
# (or are not in the inventory at all),
# it is OK to remove them without --force.
#
# All hosts are members of the groups "all";
# this means that if len(hostgroups) > 1
# we have auxilliary groups and --force is needed.
for host in hosts:
hostgroups = ansible_get_groups_by_host(inventory_dict, host)
if len(hostgroups) > 1:
forceneeded = True
hostgroups.remove("all")
extragroups.append((host, hostgroups))
for opt, _optarg in options:
if opt == "--force":
force = True
if "all" in groups and forceneeded and (not force or len(groups) > 1):
if forceneeded:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": The following hosts are parts of ", "default"),
ANSIThemeStr("other groups than “", "default"),
ANSIThemeStr("all", "argument"),
ANSIThemeStr("“:", "default")])
for host, groups in extragroups:
ansithemeprint(format_members(host, groups))
print()
ansithemeprint([ANSIThemeStr("Removing hosts from “", "default"),
ANSIThemeStr("all", "argument"),
ANSIThemeStr("“ requires specifying “", "default"),
ANSIThemeStr("--force", "option"),
ANSIThemeStr("“", "default")], stderr=True)
ansithemeprint([ANSIThemeStr("unless “", "default"),
ANSIThemeStr("all", "argument"),
ANSIThemeStr("“ is the only group or the hosts ", "default"),
ANSIThemeStr("are not members of other groups.", "default")],
stderr=True)
print()
ansithemeprint([ANSIThemeStr("Try “", "default"),
ANSIThemeStr(f"{about.INVENTORY_PROGRAM_NAME} ", "programname"),
ANSIThemeStr("help", "command"),
ANSIThemeStr("“ for more information.", "default")], stderr=True)
sys.exit(errno.EINVAL)
retval = True
# If groups is ["all"] and "force" is specified
# we need to substitute ["all"] for a list of all groups.
if groups == ["all"]:
groups = ansible_get_groups(inventory=ANSIBLE_INVENTORY)
for group in groups:
retval = ansible_remove_hosts(inventory=ANSIBLE_INVENTORY, hosts=hosts, group=group)
if not retval:
raise ProgrammingError(f"Failed to remove {hosts} to group {group}")
return 0
def inventory(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Show the inventory
Parameters:
options ([(str, str)]): List of opt, optarg
args ([str]): Comma-separated list of groups (optional)
Returns:
(int): 0
"""
color = "auto"
include_groupvars = False
include_hostvars = False
for opt, optarg in options:
if opt == "--color":
color = optarg
elif opt == "--include-vars":
include_groupvars = True
include_hostvars = True
groups = None
if args is not None and args:
groups = args[0].split(",")
for item in ansible_get_inventory_pretty(groups=groups, highlight=True,
include_groupvars=include_groupvars,
include_hostvars=include_hostvars):
ansithemeprint(cast(list, item), color=color)
return 0
# pylint: disable-next=unused-argument
def list_groups(options: list[tuple[str, str]], args: list[str]) -> int:
"""
List groups
Parameters:
options (list[(str, str)]): List of opt, optarg
args (list[str]): Unused
Returns:
(int): 0
"""
color = "auto"
# Valid formats:
# default = Normal output format (default)
# csv = Comma-separated values
# ssv = Space-separated values
# tsv = Tab-separated values
output_format = "default"
include_groupvars = False
for opt, optarg in options:
if opt == "--color":
color = optarg
elif opt == "--format":
output_format = optarg
elif opt == "--include-vars":
include_groupvars = True
if output_format != "default":
separator = ""
if output_format == "csv":
separator = ","
elif output_format == "ssv":
separator = " "
elif output_format == "tsv":
separator = "\t"
d = ansible_get_inventory_dict()
sorted_groups = cast(list[str], natsorted(d.keys()))
ansithemeprint(ansithemestr_join_list(sorted_groups, formatting="hostname",
separator=ANSIThemeStr(separator, "separator")),
color=color)
else:
for item in ansible_get_inventory_pretty(groups=None, highlight=True,
include_groupvars=include_groupvars,
include_hosts=False):
ansithemeprint(cast(list, item), color=color)
return 0
# pylint: disable-next=unused-argument
def list_hosts(options: list[tuple[str, str]], args: list[str]) -> int:
"""
List hosts
Parameters:
options (list[(str, str)]): List of opt, optarg
args (list[str]): Unused
Returns:
(int): 0
"""
color = "auto"
# Valid formats:
# default = Normal output format (default)
# csv = Comma-separated values
# ssv = Space-separated values
# tsv = Tab-separated values
output_format = "default"
include_hostvars = False
for opt, optarg in options:
if opt == "--color":
color = optarg
elif opt == "--format":
output_format = optarg
elif opt == "--include-vars":
include_hostvars = True
groups = ["all"]
if output_format != "default":
separator = ""
if output_format == "csv":
separator = ","
elif output_format == "ssv":
separator = " "
elif output_format == "tsv":
separator = "\t"
d = ansible_get_inventory_dict()
hosts = set()
for group in groups:
for host in deep_get(d, DictPath(f"{group}#hosts"), []):
hosts.add(host)
sorted_hosts = cast(list[str], natsorted(list(hosts)))
ansithemeprint(ansithemestr_join_list(sorted_hosts, formatting="hostname",
separator=ANSIThemeStr(separator, "separator")), color=color)
else:
for item in ansible_get_inventory_pretty(groups=groups, highlight=True,
include_hostvars=include_hostvars):
ansithemeprint(cast(list, item), color=color)
return 0
# pylint: disable-next=too-many-branches
def populate_playbooks() -> dict:
"""
Populate the list of playbooks runnable from the command line
Returns:
(dict): The dict of playbooks
"""
playbook_dirs: list = []
playbooks: dict = {}
local_playbook_dirs: list = deep_get(cmtlib.cmtconfig, DictPath("Ansible#local_playbooks"), [])
for playbook_dir in local_playbook_dirs:
# Substitute {HOME}/ for {HOMEDIR}
if playbook_dir.startswith(("{HOME}/", "{HOME}\\")):
playbook_dir = HOMEDIR.joinpath(playbook_dir[len('{HOME}/'):])
# Skip non-existing playbook paths
if not os.path.isdir(playbook_dir):
continue
playbook_dirs.append(playbook_dir)
playbook_dirs.append(ANSIBLE_PLAYBOOK_DIR)
playbook_dirs.append(SYSTEM_ANSIBLE_PLAYBOOK_DIR)
yaml_regex: re.Pattern[str] = re.compile(r"^(.*)\.ya?ml$")
# This should be moved to ansible_helper and generalised to be usable both in cmu and cmtinv
for playbook_dir in playbook_dirs:
# Skip non-existing playbook paths
if not os.path.isdir(playbook_dir):
continue
for playbook_path in Path(playbook_dir).iterdir():
if playbook_path.name.startswith(("~", ".")):
continue
tmp = yaml_regex.match(playbook_path.name)
if tmp is None:
continue
playbookname = str(tmp[1])
if playbookname in playbooks:
continue
description = None
try:
d = cmtio_yaml.secure_read_yaml(FilePath(playbook_path),
directory_is_symlink=True)
except yaml.YAMLError:
# This entry could not be parsed; add a dummy entry
playbooks[playbookname] = {
"description": playbook_path,
"playbook": str(playbook_path),
"category": "__INVALID__",
"comments": "Failed to parse (Not valid YAML)",
}
continue
# Empty files are used to disable playbooks completely
if d is None or not d:
playbooks[playbookname] = {
"description": playbook_path,
"playbook": str(playbook_path),
"category": "__DISABLED__",
}
continue
if not isinstance(d, list):
# This entry could not be parsed; add a dummy entry
playbooks[playbookname] = {
"description": playbook_path,
"playbook": str(playbook_path),
"category": "__INVALID__",
"comments": "Failed to parse (Not a list of plays)",
}
continue
description = deep_get(d[0], DictPath("vars#metadata#description"))
# Ignore all playbooks that lack a description;
# typically they are internal playbooks
if description is None:
continue
playbooktypes = deep_get_with_fallback(d[0],
[DictPath("vars#metadata#playbook_types"),
DictPath("vars#metadata#playbook-types")], [])
description = deep_get(d[0], DictPath("vars#metadata#description"))
category = deep_get(d[0], DictPath("vars#metadata#category"), "Uncategorized")
readonly = deep_get_with_fallback(d[0],
[DictPath("vars#metadata#read_only"),
DictPath("vars#metadata#read-only")], False)
comments = deep_get(d[0], DictPath("vars#metadata#comments"), "")
if "cmtinv" not in playbooktypes:
continue
playbooks[playbookname] = {
"description": description,
"playbook": str(playbook_path),
"category": category,
"comments": comments,
"read_only": readonly,
}
return playbooks
# pylint: disable-next=unused-argument,too-many-locals,too-many-branches
def list_playbooks(options: list[tuple[str, str]], args: list[str]) -> int:
"""
List playbooks
Parameters:
options (list[(str, str)]): List of opt, optarg
args (list[str]): Unused
Returns:
(int): 0
"""
color = "auto"
# Valid formats:
# default = Normal output format (default)
# csv = Comma-separated values
# ssv = Space-separated values
# tsv = Tab-separated values
output_format = "default"
separator = ""
for opt, optarg in options:
if opt == "--color":
color = optarg
elif opt == "--format":
output_format = optarg
if output_format != "default":
if output_format == "csv":
separator = ","
elif output_format == "ssv":
separator = " "
elif output_format == "tsv":
separator = "\t"
playbooks = populate_playbooks()
if output_format == "default":
headers = ["Name:", "Description:", "Category:", "Read Only:"]
rows = []
maxlengths = []
for header in headers:
maxlengths.append(len(header))
for playbook, data in playbooks.items():
name = playbook
description = deep_get(data, DictPath("description"), "<unset>")
category = deep_get(data, DictPath("category"), "<unset>")
read_only = str(deep_get(data, DictPath("read_only"), False))
if category in ("__DISABLED__", "__INVALID__"):
continue
rows.append([name, description, category, read_only])
for row in rows:
for i, field in enumerate(row):
maxlengths[i] = max(maxlengths[i], len(field))
header_array = []
for i, header in enumerate(headers):
header_array.append(ANSIThemeStr(header, "header"))
header_array.append(ANSIThemeStr("".ljust(maxlengths[i] - len(header) + 2), "default"))
ansithemeprint(header_array)
for row in rows:
row_array = []
for i, field in enumerate(row):
row_array.append(ANSIThemeStr(field, "default"))
row_array.append(ANSIThemeStr("".ljust(maxlengths[i] - len(field) + 2), "default"))
ansithemeprint(row_array)
else:
ansithemeprint(ansithemestr_join_list(list(playbooks), formatting="default",
separator=ANSIThemeStr(separator, "separator")), color=color)
return 0
# pylint: disable-next=too-many-locals,too-many-branches,too-many-statements
def run_playbook(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Run playbook on host(s) or group(s)
A well-formed inventory should not have groups with the same name as any of the hosts,
thus mixing group and host names should be OK; but if there are overlaps the group
are prioritised over the hostname