-
Notifications
You must be signed in to change notification settings - Fork 7
/
SaltGenResource.py
executable file
·585 lines (503 loc) · 19.4 KB
/
SaltGenResource.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Salt Resource Generator for Rundeck
A script that uses Mine function of SaltStack to populate nodes
in Rundeck. In addition to providing nodes, any Salt Grain can be
added as a node attribute or tag.
"""
import logging
import os
import sys
import yaml
import salt.client
import salt.utils
import salt.grains
import salt.version as version
import salt.utils.parsers
import salt.syspaths as syspaths
import salt.config as config
import salt.utils.args as saltargs
import salt.utils.data as datautils
import salt.utils.stringutils as stringutils
LOG = logging.getLogger("salt-gen-resource")
# noinspection PyClassHasNoInit
# pylint: disable=no-init
class SaltNodesCommandParser(
salt.utils.parsers.OptionParser,
salt.utils.parsers.ConfigDirMixIn,
salt.utils.parsers.ExtendedTargetOptionsMixIn,
salt.utils.parsers.LogLevelMixIn,
metaclass=salt.utils.parsers.OptionParserMeta,
):
"""
Argument parser used by SaltGenResource to generate
Rundeck node definitions.
"""
usage = "%prog [options] <target> [<attr>=<value> ...]"
description = "Salt Mine node source for Rundeck."
epilog = None
_config_filename_ = "minion"
_logfile_config_setting_name_ = "resource_generator_logfile"
_logfile_loglevel_config_setting_name_ = "resource_generator_log_level_logfile"
_default_logging_logfile_ = os.path.join(syspaths.LOGS_DIR, "resource-generator")
_setup_mp_logging_listener_ = False
_default_logging_level_ = "warning"
# Ignore requests to provide reserved attribute names
ignore_attributes = [
"hostname",
"osName",
"osVersion",
"osFamily",
"osArch",
"tags",
]
ignore_servernode = ["username", "description"]
# pylint: disable=no-member
def _mixin_setup(self):
"""
Define arguments specific to SaltGenResource
"""
self.add_option(
"-m",
"--mine-function",
default="grains.items",
type=str,
help=(
"Set the function name for Salt Mine to execute "
"to retrieve grains. Default value is grains.items "
"but this could be different if mine function "
"aliases are used."
),
)
self.add_option(
"-s",
"--include-server-node",
action="store_true",
help=(
"Include the Rundeck server node in the output. "
"The server node is required for some workflows "
"and must be provided by exactly one resource provider."
),
)
self.add_option(
"-u",
"--server-node-user",
type=str,
default="rundeck",
help=(
"Specify the user name to use when running jobs on the "
"server node. This would typically be the same user that "
"the Rundeck service is running as. Default: 'rundeck'."
),
)
self.add_option(
"-a",
"--attributes",
type=str,
default=[],
action="callback",
callback=self.set_callback,
help=(
"Create Rundeck node attributes from the values of grains. "
"Multiple grains may be specified "
"when separated by a space or comma."
),
)
self.add_option(
"-t",
"--tags",
type=str,
default=[],
action="callback",
callback=self.set_callback,
help=(
"Create Rundeck node tags from the values of grains. "
"Multiple grains may be specified "
"when separated by a space or comma."
),
)
def _mixin_after_parsed(self):
"""
Validate and process arguments
"""
if not os.path.isfile(self.get_config_file_path()):
LOG.critical("Configuration file not found")
sys.exit(-1)
# Extract targeting expression
try:
if self.options.list:
if "," in self.args[0]:
self.config["tgt"] = self.args[0].replace(" ", "").split(",")
else:
self.config["tgt"] = self.args[0].split()
else:
self.config["tgt"] = self.args[0]
except IndexError:
self.exit(42, "\nCannot execute command without defining a target.\n\n")
if self.options.log_level:
self.config["log_level"] = self.options.log_level
else:
self.config["log_level"] = self._default_logging_level_
# Set default targeting option
if self.config["selected_target_option"] is None:
self.config["selected_target_option"] = "glob"
# Remove conflicting grains
self.options.attributes = [
x for x in self.options.attributes if x not in self.ignore_attributes
]
def setup_config(self):
"""Configure file-based logging
This method is called by the base class to modify minion
configuration options. It is used here to configure a
log file from the minion config file.
"""
config_opts = config.minion_config(
self.get_config_file_path(),
cache_minion_id=True,
ignore_config_errors=False,
)
# Make file based logging work
if getattr(self.options, self._logfile_config_setting_name_, "None") is None:
# Copy the default log file path into the config dict
if self._logfile_config_setting_name_ not in config_opts:
config_opts[
self._logfile_config_setting_name_
] = self._default_logging_logfile_
# Prepend the root_dir setting to the log file path
config.prepend_root_dir(config_opts, [self._logfile_config_setting_name_])
# Copy the altered path back to the options, or it will revert to the default
setattr(
self.options,
self._logfile_config_setting_name_,
config_opts[self._logfile_config_setting_name_],
)
else:
# Copy the provided log file path into the config dict
if self._logfile_config_setting_name_ not in config_opts:
config_opts[self._logfile_config_setting_name_] = getattr(
self.options,
self._logfile_config_setting_name_,
self._default_logging_logfile_,
)
if getattr(self.options, self._logfile_loglevel_config_setting_name_, "None") is None:
# Copy the default log file path into the config dict
if self._logfile_loglevel_config_setting_name_ not in config_opts:
config_opts[
self._logfile_loglevel_config_setting_name_
] = self._default_logging_level_
# Copy the altered path back to the options, or it will revert to the default
setattr(
self.options,
self._logfile_loglevel_config_setting_name_,
config_opts[self._logfile_loglevel_config_setting_name_],
)
else:
# Copy the provided log file path into the config dict
if self._logfile_loglevel_config_setting_name_ not in config_opts:
config_opts[self._logfile_loglevel_config_setting_name_] = getattr(
self.options,
self._logfile_loglevel_config_setting_name_,
self._default_logging_level_,
)
return config_opts
# noinspection PyUnusedLocal
@staticmethod
def set_callback(option, opt, value, parser): # pylint: disable=unused-argument
"""
Argument parser callback for handling multi-value sets.
This callback converts comma-delimited or space-delimited strings
to list types.
"""
if "," in value:
setattr(parser.values, option.dest, set(value.replace(" ", "").split(",")))
else:
setattr(parser.values, option.dest, set(value.split()))
class ResourceGenerator:
"""
Provide a dictionary of node definitions.
When written to stdout in YAML format, this dictionary is consumable
by Rundeck.
"""
# Define maps from grain values into expected strings
_os_family_map = {"Linux": "unix", "Windows": "windows"}
_os_arch_map = {"x86_64": "amd64", "AMD64": "amd64"}
_server_node_name = "localhost"
_mine_func = "mine.get"
resources = {}
# pylint: disable=no-member
def __init__(self, args=None):
"""
Parse command arguments
"""
# Call the configuration parser
parser = SaltNodesCommandParser()
parser.parse_args(args)
# Removing 'conf_file' prevents the file from being re-read when rendering grains
parser.config.pop("conf_file", None)
# Parse the static attribute definitions
self.static = saltargs.parse_input(parser.args, False)[1]
# Create local references to the parser data
self.config = parser.config
self.options = parser.options
# Generate resources
self._generate()
def as_dict(self):
"""
Return the generated resources as a Python dictionary
"""
return self.resources
def as_yaml(self):
"""
Return the generated resources as YAML
"""
return self._dump_yaml(self.resources)
@staticmethod
def _dump_yaml(resources):
return yaml.safe_dump(resources, default_flow_style=False)
def _generate(self):
"""
The main function for SaltGenResource. This method calls the Salt Mine
and converts the returned data into a dictionary that conforms to the
Rundeck specification for an external resource generator.
The return is a Python dictionary. The caller is responsible for converting
the dictionary into YAML for consumption by Rundeck.
"""
# Create a Salt Caller object
caller = salt.client.Caller(c_path=None, mopts=self.config)
# Account for an API change in Salt Nitrogen (2017.7)
kwargs = {"exclude_minion": self.options.include_server_node}
if version.__saltstack_version__ >= version.SaltStackVersion.from_name(
"Nitrogen"
):
kwargs["tgt_type"] = self.config["selected_target_option"]
else:
kwargs["expr_form"] = self.config["selected_target_option"]
# Call Salt Mine to retrieve grains for all nodes
LOG.debug(
"Calling %s with target: '%s' type: '%s'",
self._mine_func,
self.config["tgt"],
self.config["selected_target_option"],
)
mine = caller.cmd(
self._mine_func, self.config["tgt"], self.options.mine_function, **kwargs
)
LOG.debug(
"Salt Mine function '%s' returned %d minion%s",
self._mine_func,
len(mine),
"" if len(mine) == 1 else "s",
)
# Special handling for server node
if self.options.include_server_node is True:
# Map required node attributes from grains
local_grains = caller.sminion.opts["grains"]
self.resources[self._server_node_name] = {
"hostname": self._server_node_name,
"description": "Rundeck server node",
"username": self.options.server_node_user,
"osName": local_grains["kernel"],
"osVersion": local_grains["kernelrelease"],
"osFamily": self._os_family(local_grains["kernel"]),
"osArch": self._os_arch(local_grains["cpuarch"]),
}
# Create additional attributes from grains
self.resources[self._server_node_name].update(
self._create_attributes(self._server_node_name, local_grains)
)
# Create static attributes
self.resources[self._server_node_name].update(
{
k: v
for k, v in self.static.items()
if k
not in SaltNodesCommandParser.ignore_attributes
+ SaltNodesCommandParser.ignore_servernode
}
)
# Create tags from grains
tags = self._create_tags(self._server_node_name, local_grains)
if len(tags) > 0:
self.resources[self._server_node_name]["tags"] = tags
# Map grains into a Rundeck resource dict
for minion, minion_grains in mine.items():
# Map required node attributes from grains
self.resources[minion] = {
"hostname": minion_grains["fqdn"],
"osName": minion_grains["kernel"],
"osVersion": minion_grains["kernelrelease"],
"osFamily": self._os_family(minion_grains["kernel"]),
"osArch": self._os_arch(minion_grains["cpuarch"]),
}
# Create additional attributes from grains
self.resources[minion].update(
self._create_attributes(minion, minion_grains)
)
# Create static attributes
self.resources[minion].update(
{
k: v
for k, v in self.static.items()
if k not in SaltNodesCommandParser.ignore_attributes
}
)
# Create tags from grains
tags = self._create_tags(minion, minion_grains)
if len(tags) > 0:
self.resources[minion]["tags"] = tags
if not self.resources:
LOG.warning("No resources returned.")
def _create_attributes(self, minion, grains):
"""
Loop over requested attributes and request a value for each
"""
attributes = {}
for item in self.options.attributes:
try:
key, value = self._attribute_from_grain(item, grains)
if value is not None:
LOG.debug(
(
"Adding attribute for minion: "
"'%s' grain: '%s', attribute: '%s', value: '%s'"
),
minion,
item,
key,
value,
)
attributes[key] = value
else:
LOG.warning(
"Requested grain '%s' is not available on minion: %s",
item,
minion,
)
except TypeError:
LOG.warning(
"Minion '%s' grain '%s' ignored because grain type is unsupported.",
minion,
item,
)
return attributes
def _attribute_from_grain(self, item, grains):
"""
Provide the value for a single attribute from a grain
"""
key = item.replace(":", "_")
value = datautils.traverse_dict_and_list(
grains, item, default="", delimiter=self.options.delimiter
)
if isinstance(value, list):
LOG.warning(
"Grain '%s' is a list. First item will be selected by default.", item
)
return key, ResourceGenerator._get_grain_value(value, 0)
@staticmethod
def _get_grain_value(value, depth):
"""
Process different value types, recursing lists if necessary
"""
# Ignore dicts. Creating attributes from this type is not useful.
if isinstance(value, dict):
raise TypeError
# Return string value
if isinstance(value, str):
return stringutils.to_unicode(value)
# Return the first element of a list
if hasattr(value, "__iter__"):
if isinstance(value, list) and len(value) > 0:
return ResourceGenerator._get_grain_value(value[0], depth + 1)
raise TypeError
return value
def _create_tags(self, minion, grains):
"""
Loop over requested tags and request a value for each
"""
tags = set()
for item in self.options.tags:
try:
new_tags = self._tags_from_grain(item, grains)
if not new_tags:
LOG.warning(
"Requested grain '%s' is not available on minion: %s",
item,
minion,
)
for tag in new_tags:
LOG.debug(
"Adding tag for minion: '%s', grain: '%s', tag: '%s'",
minion,
item,
tag,
)
tags.add(tag)
except TypeError:
LOG.warning(
(
"Tag not added for minion: '%s', grain: '%s' "
"because its data type is not supported."
),
minion,
item,
)
return list(tags)
def _tags_from_grain(self, item, grains):
"""
Define a single tag from a grain value
"""
value = datautils.traverse_dict_and_list(
grains, item, default=None, delimiter=self.options.delimiter
)
return self._tags_from_value(value, 0)
@staticmethod
def _tags_from_value(value, depth):
"""Add tags from a grain value
Args:
value (any): The grain value from which to create tag(s)
depth (int): The recursion depth. This is not currently used,
but may be in the future to support a maximum
recursion depth setting.
Returns:
set: Set of tags to create from this value
Raises:
TypeError: Raised when the type of the value is not supported
"""
tags = set()
# Ignore None values
if value is None:
return tags
# Ignore numbers, booleans, and dicts. Creating tags
# from these types is not useful.
if isinstance(value, (int, float, bool, dict)):
raise TypeError
# Create tags from string types
if isinstance(value, str):
tags.add(stringutils.to_unicode(value))
# Create tags from binary types
elif isinstance(value, bytes):
tags.add(value)
# If the type is iterable, add each element
elif hasattr(value, "__iter__"):
for item in value:
tags.update(ResourceGenerator._tags_from_value(item, depth + 1))
return tags
@classmethod
def _os_family(cls, value):
"""
Map the os_family used by Salt to one used by Rundeck
"""
if value in cls._os_family_map:
return cls._os_family_map[value]
return value
@classmethod
def _os_arch(cls, value):
"""
Map the os_arch used by Salt to one used by Rundeck
"""
if value in cls._os_arch_map:
return cls._os_arch_map[value]
return value
if __name__ == "__main__":
# Print dict as YAML on stdout
print(ResourceGenerator().as_yaml())