runbook-py 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- runbook_py/__init__.py +4 -0
- runbook_py/__main__.py +5 -0
- runbook_py/cli.py +266 -0
- runbook_py/config.py +168 -0
- runbook_py/plan.py +307 -0
- runbook_py/report.py +76 -0
- runbook_py/runner.py +538 -0
- runbook_py/schema.py +76 -0
- runbook_py/util.py +111 -0
- runbook_py-1.0.0.dist-info/METADATA +225 -0
- runbook_py-1.0.0.dist-info/RECORD +15 -0
- runbook_py-1.0.0.dist-info/WHEEL +5 -0
- runbook_py-1.0.0.dist-info/entry_points.txt +2 -0
- runbook_py-1.0.0.dist-info/licenses/LICENSE +21 -0
- runbook_py-1.0.0.dist-info/top_level.txt +1 -0
runbook_py/__init__.py
ADDED
runbook_py/__main__.py
ADDED
runbook_py/cli.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Command-line interface: runbook [run] plan.json | validate | report | schema | init-config."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import signal
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .config import COLOR_MODES, CONFIRM_MODES, SAMPLE, ConfigError, load_config
|
|
12
|
+
from .plan import NAME_RE, PlanError, builtin_vars, check_variables, load_plan, parse_cli_vars, render
|
|
13
|
+
from .report import load_result, render_report
|
|
14
|
+
from .runner import EXIT_INTERRUPTED, EXIT_INVALID, EXIT_LOCKED, Lock, Runner
|
|
15
|
+
from .schema import PLAN_SCHEMA
|
|
16
|
+
from .util import Console, redact, slug
|
|
17
|
+
|
|
18
|
+
SUBCOMMANDS = ("run", "validate", "report", "schema", "init-config")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _csv(value):
|
|
22
|
+
return [part.strip() for part in value.split(",") if part.strip()]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _add_plan_options(parser):
|
|
26
|
+
parser.add_argument("plan", help="plan file (JSON)")
|
|
27
|
+
parser.add_argument("--var", action="append", default=[], metavar="NAME=VALUE",
|
|
28
|
+
help="set a {{variable}} (repeatable; overrides the plan and .runbook.ini)")
|
|
29
|
+
parser.add_argument("--config", metavar="FILE", help="extra .runbook.ini read last (also $RUNBOOK_CONFIG)")
|
|
30
|
+
parser.add_argument("--no-config", action="store_true", help="ignore /etc, ~ and ./ .runbook.ini files")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def build_parser():
|
|
34
|
+
parser = argparse.ArgumentParser(
|
|
35
|
+
prog="runbook",
|
|
36
|
+
description="Run a JSON plan of shell commands and write a complete JSON report "
|
|
37
|
+
"(rc, stdout, stderr, duration) for each command.",
|
|
38
|
+
epilog="Exit codes: 0 all ok, 1 a command failed, 2 invalid plan or config, "
|
|
39
|
+
"3 requirements not met, 4 another run holds the lock, 130 interrupted.")
|
|
40
|
+
parser.add_argument("--version", action="version", version="runbook-py " + __version__)
|
|
41
|
+
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
42
|
+
|
|
43
|
+
run = sub.add_parser("run", help="run a plan (default when a plan file is given directly)")
|
|
44
|
+
_add_plan_options(run)
|
|
45
|
+
run.add_argument("-o", "--output", metavar="FILE", help="result file (default: <plan>_<host>_<timestamp>.result.json)")
|
|
46
|
+
run.add_argument("--output-dir", metavar="DIR", help="directory for the result file ([runbook] output_dir)")
|
|
47
|
+
run.add_argument("--dry-run", action="store_true", help="show what would run, execute nothing")
|
|
48
|
+
run.add_argument("--confirm", choices=CONFIRM_MODES, help="ask before: none, dangerous (default) or all commands")
|
|
49
|
+
run.add_argument("-y", "--yes", action="store_true", help="never ask (same as --confirm none)")
|
|
50
|
+
run.add_argument("--from", dest="start_from", metavar="ID", help="start at this command; earlier ones are skipped")
|
|
51
|
+
run.add_argument("--only", type=_csv, metavar="ID[,ID...]", help="run only these commands")
|
|
52
|
+
run.add_argument("--skip", type=_csv, metavar="ID[,ID...]", help="skip these commands")
|
|
53
|
+
run.add_argument("--resume", metavar="RESULT", help="previous .result.json: commands that were ok are skipped, "
|
|
54
|
+
"failed and skipped ones run again")
|
|
55
|
+
run.add_argument("--max-output", type=int, metavar="BYTES", help="bytes kept per stream, head + tail (0 = all)")
|
|
56
|
+
run.add_argument("--redact", action="append", default=[], metavar="REGEX", help="mask matches as [REDACTED] (repeatable)")
|
|
57
|
+
group = run.add_mutually_exclusive_group()
|
|
58
|
+
group.add_argument("--stream", dest="stream", action="store_const", const="true", help="show output live")
|
|
59
|
+
group.add_argument("--no-stream", dest="stream", action="store_const", const="false", help="do not show output live")
|
|
60
|
+
run.add_argument("--color", choices=COLOR_MODES, help="console colours")
|
|
61
|
+
run.add_argument("--no-lock", action="store_true", help="do not take the lock file")
|
|
62
|
+
run.add_argument("-q", "--quiet", action="store_true", help="only print the result path and errors")
|
|
63
|
+
|
|
64
|
+
val = sub.add_parser("validate", help="check a plan (structure, ids, variables) without running it")
|
|
65
|
+
_add_plan_options(val)
|
|
66
|
+
|
|
67
|
+
rep = sub.add_parser("report", help="summarize a .result.json file")
|
|
68
|
+
rep.add_argument("result", help="result file")
|
|
69
|
+
rep.add_argument("--format", choices=("text", "markdown"), default="text")
|
|
70
|
+
rep.add_argument("--lines", type=int, default=20, help="output lines shown per failed command (default 20)")
|
|
71
|
+
rep.add_argument("--all", action="store_true", help="show the output of every command, not only failures")
|
|
72
|
+
|
|
73
|
+
sub.add_parser("schema", help="print the JSON Schema of a plan")
|
|
74
|
+
|
|
75
|
+
init = sub.add_parser("init-config", help="print a commented .runbook.ini (or write it to FILE)")
|
|
76
|
+
init.add_argument("file", nargs="?", help="where to write it (refuses to overwrite)")
|
|
77
|
+
return parser
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def normalize_argv(argv):
|
|
81
|
+
"""`runbook plan.json ...` is accepted as a shorthand for `runbook run plan.json ...`."""
|
|
82
|
+
if argv and argv[0] not in SUBCOMMANDS and not argv[0].startswith("-"):
|
|
83
|
+
return ["run"] + list(argv)
|
|
84
|
+
return list(argv)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _prepare(args, console):
|
|
88
|
+
cfg = load_config(args.config, search=not args.no_config)
|
|
89
|
+
plan = load_plan(args.plan)
|
|
90
|
+
variables = builtin_vars(plan["name"])
|
|
91
|
+
variables.update(plan["vars"])
|
|
92
|
+
for key in cfg.vars:
|
|
93
|
+
if not NAME_RE.match(key):
|
|
94
|
+
raise ConfigError("invalid variable name %r in [vars]" % key)
|
|
95
|
+
variables.update(cfg.vars)
|
|
96
|
+
variables.update(parse_cli_vars(args.var))
|
|
97
|
+
check_variables(plan, variables)
|
|
98
|
+
return cfg, plan, variables
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _compile(patterns):
|
|
102
|
+
compiled = []
|
|
103
|
+
for pattern in patterns:
|
|
104
|
+
try:
|
|
105
|
+
compiled.append(re.compile(pattern))
|
|
106
|
+
except re.error as exc:
|
|
107
|
+
raise PlanError("invalid redact regex %r: %s" % (pattern, exc))
|
|
108
|
+
return compiled
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def cmd_validate(args, console):
|
|
112
|
+
cfg, plan, variables = _prepare(args, console)
|
|
113
|
+
cmds = plan["commands"]
|
|
114
|
+
dangerous = sum(1 for c in cmds if c["dangerous"])
|
|
115
|
+
captures = [c["capture"] for c in cmds if c["capture"]]
|
|
116
|
+
console.write("OK: %s — %d command(s), %d dangerous%s" % (
|
|
117
|
+
plan["name"], len(cmds), dangerous, (", captures: " + ", ".join(captures)) if captures else ""), force=True)
|
|
118
|
+
if cfg.files:
|
|
119
|
+
console.write("config: " + ", ".join(cfg.files), force=True)
|
|
120
|
+
return 0
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _dry_run(plan, variables, console, opts, patterns):
|
|
124
|
+
placeholders = dict(variables)
|
|
125
|
+
for c in plan["commands"]:
|
|
126
|
+
if c["capture"]:
|
|
127
|
+
placeholders.setdefault(c["capture"], "{{%s}}" % c["capture"])
|
|
128
|
+
console.write(console.paint("DRY RUN: %s — %d command(s) on %s" % (
|
|
129
|
+
plan["name"], len(plan["commands"]), variables.get("host")), "36;1"), force=True)
|
|
130
|
+
ids = [c["id"] for c in plan["commands"]]
|
|
131
|
+
start = ids.index(opts.start_from) if opts.start_from else 0
|
|
132
|
+
for index, c in enumerate(plan["commands"]):
|
|
133
|
+
selected = index >= start and (not opts.only or c["id"] in opts.only) and not (opts.skip and c["id"] in opts.skip)
|
|
134
|
+
cmd = render(c["cmd"], placeholders)
|
|
135
|
+
shown = redact(cmd if isinstance(cmd, str) else json.dumps(cmd), patterns)
|
|
136
|
+
flags = []
|
|
137
|
+
if c["dangerous"]:
|
|
138
|
+
flags.append("DANGEROUS")
|
|
139
|
+
if not c["stop_on_error"]:
|
|
140
|
+
flags.append("continue-on-error")
|
|
141
|
+
if c["only_if"]:
|
|
142
|
+
flags.append("only_if=" + ",".join(c["only_if"]))
|
|
143
|
+
if c["skip_if"]:
|
|
144
|
+
flags.append("skip_if")
|
|
145
|
+
if c["capture"]:
|
|
146
|
+
flags.append("capture=" + c["capture"])
|
|
147
|
+
if c["retries"]:
|
|
148
|
+
flags.append("retries=%d" % c["retries"])
|
|
149
|
+
if not selected:
|
|
150
|
+
flags.append("NOT SELECTED")
|
|
151
|
+
line = " [%s] %s" % (c["id"], shown)
|
|
152
|
+
console.write(line + console.paint(" (%s)" % ", ".join(flags), "90") if flags else line, force=True)
|
|
153
|
+
return 0
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _load_resume(path, plan, console):
|
|
157
|
+
data = load_result(path)
|
|
158
|
+
if data.get("plan_sha256") and plan.get("_sha256") and data["plan_sha256"] != plan["_sha256"]:
|
|
159
|
+
console.warn("the plan changed since %s; resuming by command id" % path)
|
|
160
|
+
ok = {e["id"] for e in data.get("results", []) if e.get("status") == "ok"}
|
|
161
|
+
known = {c["id"] for c in plan["commands"]}
|
|
162
|
+
return ok & known, data.get("captures") or {}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def cmd_run(args, console):
|
|
166
|
+
cfg, plan, variables = _prepare(args, console)
|
|
167
|
+
ids = {c["id"] for c in plan["commands"]}
|
|
168
|
+
for opt_name, values in (("--only", args.only or []), ("--skip", args.skip or []),
|
|
169
|
+
("--from", [args.start_from] if args.start_from else [])):
|
|
170
|
+
unknown = [v for v in values if v not in ids]
|
|
171
|
+
if unknown:
|
|
172
|
+
raise PlanError("%s: unknown command id(s): %s" % (opt_name, ", ".join(unknown)))
|
|
173
|
+
|
|
174
|
+
if args.yes:
|
|
175
|
+
args.confirm = "none"
|
|
176
|
+
if args.color:
|
|
177
|
+
console = Console(args.color, quiet=args.quiet)
|
|
178
|
+
elif cfg["color"] != "auto":
|
|
179
|
+
console = Console(cfg["color"], quiet=args.quiet)
|
|
180
|
+
args.resume_path = os.path.abspath(args.resume) if args.resume else None
|
|
181
|
+
args.resume_ok, args.resume_captures = set(), {}
|
|
182
|
+
if args.resume:
|
|
183
|
+
args.resume_ok, args.resume_captures = _load_resume(args.resume, plan, console)
|
|
184
|
+
|
|
185
|
+
patterns = _compile(cfg["redact"] + plan["redact"] + args.redact)
|
|
186
|
+
if args.dry_run:
|
|
187
|
+
return _dry_run(plan, variables, console, args, patterns)
|
|
188
|
+
|
|
189
|
+
if args.output:
|
|
190
|
+
out_path = args.output
|
|
191
|
+
else:
|
|
192
|
+
out_dir = os.path.expanduser(args.output_dir or cfg["output_dir"])
|
|
193
|
+
if not os.path.isdir(out_dir):
|
|
194
|
+
os.makedirs(out_dir)
|
|
195
|
+
out_path = os.path.join(out_dir, "%s_%s_%s.result.json" % (
|
|
196
|
+
slug(plan["name"]), slug(variables["host"]), variables["timestamp"]))
|
|
197
|
+
out_path = os.path.abspath(out_path)
|
|
198
|
+
|
|
199
|
+
lock = Lock(None if args.no_lock else cfg.get_lock_file())
|
|
200
|
+
if not lock.acquire():
|
|
201
|
+
console.error("another runbook is running (lock %s); use --no-lock to bypass" % lock.path)
|
|
202
|
+
return EXIT_LOCKED
|
|
203
|
+
try:
|
|
204
|
+
runner = Runner(plan, cfg, args, console, variables, patterns)
|
|
205
|
+
code = runner.run(out_path)
|
|
206
|
+
finally:
|
|
207
|
+
lock.release()
|
|
208
|
+
print(out_path)
|
|
209
|
+
return code
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def cmd_report(args, console):
|
|
213
|
+
data = load_result(args.result)
|
|
214
|
+
sys.stdout.write(render_report(data, args.format, args.lines, args.all))
|
|
215
|
+
return 0
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def cmd_init_config(args, console):
|
|
219
|
+
if not args.file:
|
|
220
|
+
sys.stdout.write(SAMPLE)
|
|
221
|
+
return 0
|
|
222
|
+
if os.path.exists(args.file):
|
|
223
|
+
console.error("%s already exists" % args.file)
|
|
224
|
+
return EXIT_INVALID
|
|
225
|
+
with open(args.file, "w", encoding="utf-8") as handle:
|
|
226
|
+
handle.write(SAMPLE)
|
|
227
|
+
console.write("wrote %s" % args.file, force=True)
|
|
228
|
+
return 0
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _sigterm(signum, frame):
|
|
232
|
+
raise KeyboardInterrupt()
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def main(argv=None):
|
|
236
|
+
argv = normalize_argv(sys.argv[1:] if argv is None else argv)
|
|
237
|
+
parser = build_parser()
|
|
238
|
+
args = parser.parse_args(argv)
|
|
239
|
+
console = Console("auto", quiet=getattr(args, "quiet", False))
|
|
240
|
+
if not args.command:
|
|
241
|
+
parser.print_help()
|
|
242
|
+
return EXIT_INVALID
|
|
243
|
+
try:
|
|
244
|
+
signal.signal(signal.SIGTERM, _sigterm)
|
|
245
|
+
except ValueError:
|
|
246
|
+
pass
|
|
247
|
+
try:
|
|
248
|
+
if args.command == "schema":
|
|
249
|
+
sys.stdout.write(json.dumps(PLAN_SCHEMA, indent=2) + "\n")
|
|
250
|
+
return 0
|
|
251
|
+
if args.command == "init-config":
|
|
252
|
+
return cmd_init_config(args, console)
|
|
253
|
+
if args.command == "report":
|
|
254
|
+
return cmd_report(args, console)
|
|
255
|
+
if args.command == "validate":
|
|
256
|
+
return cmd_validate(args, console)
|
|
257
|
+
return cmd_run(args, console)
|
|
258
|
+
except (PlanError, ConfigError) as exc:
|
|
259
|
+
console.error(str(exc))
|
|
260
|
+
return EXIT_INVALID
|
|
261
|
+
except (OSError, ValueError) as exc:
|
|
262
|
+
console.error(str(exc))
|
|
263
|
+
return EXIT_INVALID
|
|
264
|
+
except KeyboardInterrupt:
|
|
265
|
+
console.error("interrupted")
|
|
266
|
+
return EXIT_INTERRUPTED
|
runbook_py/config.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Loads .runbook.ini files.
|
|
2
|
+
|
|
3
|
+
Lookup order (later files override earlier ones):
|
|
4
|
+
/etc/runbook.ini, ~/.runbook.ini, ./.runbook.ini, then $RUNBOOK_CONFIG or --config.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import configparser
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
import tempfile
|
|
11
|
+
|
|
12
|
+
CONFIRM_MODES = ("none", "dangerous", "all")
|
|
13
|
+
TRISTATE = ("auto", "true", "false")
|
|
14
|
+
COLOR_MODES = ("auto", "always", "never")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def default_lock_file():
|
|
18
|
+
if os.path.isdir("/run/lock") and os.access("/run/lock", os.W_OK):
|
|
19
|
+
return "/run/lock/runbook.lock"
|
|
20
|
+
return os.path.join(tempfile.gettempdir(), "runbook-%d.lock" % os.getuid())
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
DEFAULTS = {
|
|
24
|
+
"output_dir": ".",
|
|
25
|
+
"max_output": 65536,
|
|
26
|
+
"confirm": "dangerous",
|
|
27
|
+
"timeout": 60,
|
|
28
|
+
"shell": "", # empty = /bin/bash, then /bin/sh
|
|
29
|
+
"stream": "auto", # live output: auto = when stderr is a terminal
|
|
30
|
+
"color": "auto",
|
|
31
|
+
"strip_ansi": True,
|
|
32
|
+
"lock_file": None, # None = default_lock_file(); "" disables locking
|
|
33
|
+
"redact": [],
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
SEARCH_PATHS = ("/etc/runbook.ini", "~/.runbook.ini", "./.runbook.ini")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ConfigError(Exception):
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Config(object):
|
|
44
|
+
def __init__(self):
|
|
45
|
+
self.values = dict(DEFAULTS)
|
|
46
|
+
self.values["redact"] = []
|
|
47
|
+
self.vars = {}
|
|
48
|
+
self.files = []
|
|
49
|
+
|
|
50
|
+
def __getitem__(self, key):
|
|
51
|
+
return self.values[key]
|
|
52
|
+
|
|
53
|
+
def get_lock_file(self):
|
|
54
|
+
lock = self.values["lock_file"]
|
|
55
|
+
return default_lock_file() if lock is None else lock
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _parse_bool(value, key, path):
|
|
59
|
+
low = value.strip().lower()
|
|
60
|
+
if low in ("1", "yes", "true", "on"):
|
|
61
|
+
return True
|
|
62
|
+
if low in ("0", "no", "false", "off"):
|
|
63
|
+
return False
|
|
64
|
+
raise ConfigError("%s: [runbook] %s must be true or false, got %r" % (path, key, value))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _apply_file(cfg, path):
|
|
68
|
+
parser = configparser.ConfigParser(interpolation=None)
|
|
69
|
+
parser.optionxform = str # keep variable names case-sensitive
|
|
70
|
+
try:
|
|
71
|
+
with open(path, encoding="utf-8") as handle:
|
|
72
|
+
parser.read_file(handle)
|
|
73
|
+
except (OSError, configparser.Error) as exc:
|
|
74
|
+
raise ConfigError("%s: %s" % (path, exc))
|
|
75
|
+
|
|
76
|
+
for section in parser.sections():
|
|
77
|
+
if section not in ("runbook", "vars"):
|
|
78
|
+
raise ConfigError("%s: unknown section [%s] (expected [runbook] and [vars])" % (path, section))
|
|
79
|
+
|
|
80
|
+
if parser.has_section("runbook"):
|
|
81
|
+
for key, raw in parser.items("runbook"):
|
|
82
|
+
if key not in DEFAULTS:
|
|
83
|
+
raise ConfigError("%s: unknown key %r in [runbook] (known: %s)"
|
|
84
|
+
% (path, key, ", ".join(sorted(DEFAULTS))))
|
|
85
|
+
value = raw.strip()
|
|
86
|
+
if key in ("max_output", "timeout"):
|
|
87
|
+
try:
|
|
88
|
+
value = int(value)
|
|
89
|
+
except ValueError:
|
|
90
|
+
raise ConfigError("%s: [runbook] %s must be an integer, got %r" % (path, key, raw))
|
|
91
|
+
if value < 0:
|
|
92
|
+
raise ConfigError("%s: [runbook] %s must be >= 0" % (path, key))
|
|
93
|
+
elif key == "strip_ansi":
|
|
94
|
+
value = _parse_bool(value, key, path)
|
|
95
|
+
elif key == "confirm" and value not in CONFIRM_MODES:
|
|
96
|
+
raise ConfigError("%s: [runbook] confirm must be one of %s" % (path, ", ".join(CONFIRM_MODES)))
|
|
97
|
+
elif key == "stream" and value.lower() not in TRISTATE:
|
|
98
|
+
raise ConfigError("%s: [runbook] stream must be auto, true or false" % path)
|
|
99
|
+
elif key == "color" and value not in COLOR_MODES:
|
|
100
|
+
raise ConfigError("%s: [runbook] color must be one of %s" % (path, ", ".join(COLOR_MODES)))
|
|
101
|
+
elif key == "output_dir":
|
|
102
|
+
value = os.path.expanduser(value)
|
|
103
|
+
elif key == "redact":
|
|
104
|
+
patterns = [line.strip() for line in raw.splitlines() if line.strip()]
|
|
105
|
+
for pattern in patterns:
|
|
106
|
+
try:
|
|
107
|
+
re.compile(pattern)
|
|
108
|
+
except re.error as exc:
|
|
109
|
+
raise ConfigError("%s: invalid redact regex %r: %s" % (path, pattern, exc))
|
|
110
|
+
cfg.values["redact"].extend(patterns)
|
|
111
|
+
continue
|
|
112
|
+
if key == "stream":
|
|
113
|
+
value = value.lower()
|
|
114
|
+
cfg.values[key] = value
|
|
115
|
+
|
|
116
|
+
if parser.has_section("vars"):
|
|
117
|
+
for key, value in parser.items("vars"):
|
|
118
|
+
cfg.vars[key] = value
|
|
119
|
+
cfg.files.append(os.path.abspath(path))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def load_config(explicit=None, search=True):
|
|
123
|
+
cfg = Config()
|
|
124
|
+
if search:
|
|
125
|
+
for candidate in SEARCH_PATHS:
|
|
126
|
+
path = os.path.expanduser(candidate)
|
|
127
|
+
if os.path.isfile(path):
|
|
128
|
+
_apply_file(cfg, path)
|
|
129
|
+
explicit = explicit or os.environ.get("RUNBOOK_CONFIG")
|
|
130
|
+
if explicit:
|
|
131
|
+
if not os.path.isfile(explicit):
|
|
132
|
+
raise ConfigError("config file not found: %s" % explicit)
|
|
133
|
+
_apply_file(cfg, explicit)
|
|
134
|
+
return cfg
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
SAMPLE = """\
|
|
138
|
+
# .runbook.ini - runbook-py configuration
|
|
139
|
+
# Looked up in /etc/runbook.ini, ~/.runbook.ini, ./.runbook.ini, then $RUNBOOK_CONFIG / --config.
|
|
140
|
+
# Later files override earlier ones; command-line options override everything.
|
|
141
|
+
|
|
142
|
+
[runbook]
|
|
143
|
+
# Where <plan>_<host>_<timestamp>.result.json files are written
|
|
144
|
+
output_dir = .
|
|
145
|
+
# Bytes kept per stream (stdout, stderr); the head and the tail are kept. 0 = unlimited
|
|
146
|
+
max_output = 65536
|
|
147
|
+
# Ask before running: none | dangerous | all
|
|
148
|
+
confirm = dangerous
|
|
149
|
+
# Default timeout per command, in seconds (0 = none)
|
|
150
|
+
timeout = 60
|
|
151
|
+
# Shell used for string commands (empty = /bin/bash, falling back to /bin/sh)
|
|
152
|
+
shell =
|
|
153
|
+
# Show command output live: auto (when stderr is a terminal) | true | false
|
|
154
|
+
stream = auto
|
|
155
|
+
# auto | always | never (NO_COLOR is honoured)
|
|
156
|
+
color = auto
|
|
157
|
+
# Remove ANSI colour codes and carriage-return progress lines from captured output
|
|
158
|
+
strip_ansi = true
|
|
159
|
+
# Prevents two runs at once; empty disables locking
|
|
160
|
+
# lock_file = /run/lock/runbook.lock
|
|
161
|
+
# Regexes masked as [REDACTED] in the report, one per line
|
|
162
|
+
redact =
|
|
163
|
+
(?i)(password|passwd|secret|token)\\s*[:=]\\s*\\S+
|
|
164
|
+
|
|
165
|
+
[vars]
|
|
166
|
+
# Host-specific values available as {{name}} in every plan; they override the plan's own "vars".
|
|
167
|
+
# mac_nic0 = b8:3f:d2:0d:9f:16
|
|
168
|
+
"""
|