| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
|
| 10 |
from ansible.cli import CLI |
| 11 |
|
| 12 |
import datetime |
| 13 |
import os |
| 14 |
import platform |
| 15 |
import secrets |
| 16 |
import shlex |
| 17 |
import shutil |
| 18 |
import socket |
| 19 |
import sys |
| 20 |
import time |
| 21 |
|
| 22 |
from ansible import constants as C |
| 23 |
from ansible import context |
| 24 |
from ansible.cli.arguments import option_helpers as opt_help |
| 25 |
from ansible.errors import AnsibleOptionsError |
| 26 |
from ansible.module_utils.common.text.converters import to_native, to_text |
| 27 |
from ansible.plugins.loader import module_loader |
| 28 |
from ansible.utils.cmd_functions import run_cmd |
| 29 |
from ansible.utils.display import Display |
| 30 |
|
| 31 |
|
| 32 |
display = Display() |
| 33 |
|
| 34 |
SAFE_OUTPUT_ENV = { |
| 35 |
'ANSIBLE_CALLBACK_RESULT_FORMAT': 'json', |
| 36 |
'ANSIBLE_LOAD_CALLBACK_PLUGINS': '0', |
| 37 |
} |
| 38 |
|
| 39 |
|
| 40 |
def safe_output_env(f): |
| 41 |
|
| 42 |
def wrapper(*args, **kwargs): |
| 43 |
|
| 44 |
orig = {} |
| 45 |
|
| 46 |
for k, v in SAFE_OUTPUT_ENV.items(): |
| 47 |
orig[k] = os.environ.get(k, None) |
| 48 |
os.environ[k] = v |
| 49 |
|
| 50 |
result = f(*args, **kwargs) |
| 51 |
|
| 52 |
for key in orig.keys(): |
| 53 |
if orig[key] is None: |
| 54 |
del os.environ[key] |
| 55 |
else: |
| 56 |
os.environ[key] = orig[key] |
| 57 |
|
| 58 |
return result |
| 59 |
|
| 60 |
return wrapper |
| 61 |
|
| 62 |
|
| 63 |
class PullCLI(CLI): |
| 64 |
""" Used to pull a remote copy of ansible on each managed node, |
| 65 |
each set to run via cron and update playbook source via a source repository. |
| 66 |
This inverts the default *push* architecture of ansible into a *pull* architecture, |
| 67 |
which has near-limitless scaling potential. |
| 68 |
|
| 69 |
None of the CLI tools are designed to run concurrently with themselves, |
| 70 |
you should use an external scheduler and/or locking to ensure there are no clashing operations. |
| 71 |
|
| 72 |
The setup playbook can be tuned to change the cron frequency, logging locations, and parameters to ansible-pull. |
| 73 |
This is useful both for extreme scale-out and periodic remediation. |
| 74 |
Usage of the 'fetch' module to retrieve logs from ansible-pull runs would be an |
| 75 |
excellent way to gather and analyze remote logs from ansible-pull. |
| 76 |
""" |
| 77 |
|
| 78 |
name = 'ansible-pull' |
| 79 |
|
| 80 |
DEFAULT_REPO_TYPE = 'git' |
| 81 |
DEFAULT_PLAYBOOK = 'local.yml' |
| 82 |
REPO_CHOICES = ('git', 'subversion', 'hg', 'bzr') |
| 83 |
PLAYBOOK_ERRORS = { |
| 84 |
1: 'File does not exist', |
| 85 |
2: 'File is not readable', |
| 86 |
} |
| 87 |
ARGUMENTS = {'playbook.yml': 'The name of one the YAML format files to run as an Ansible playbook. ' |
| 88 |
'This can be a relative path within the checkout. By default, Ansible will ' |
| 89 |
"look for a playbook based on the host's fully-qualified domain name, " |
| 90 |
'on the host hostname and finally a playbook named *local.yml*.', } |
| 91 |
|
| 92 |
SKIP_INVENTORY_DEFAULTS = True |
| 93 |
|
| 94 |
@staticmethod |
| 95 |
def _get_inv_cli(): |
| 96 |
inv_opts = '' |
| 97 |
if context.CLIARGS.get('inventory', False): |
| 98 |
for inv in context.CLIARGS['inventory']: |
| 99 |
if isinstance(inv, list): |
| 100 |
inv_opts += " -i '%s' " % ','.join(inv) |
| 101 |
elif ',' in inv or os.path.exists(inv): |
| 102 |
inv_opts += ' -i %s ' % inv |
| 103 |
|
| 104 |
return inv_opts |
| 105 |
|
| 106 |
def init_parser(self): |
| 107 |
""" Specific args/option parser for pull """ |
| 108 |
|
| 109 |
|
| 110 |
super(PullCLI, self).init_parser( |
| 111 |
desc="pulls playbooks from a VCS repo and executes them on target host") |
| 112 |
|
| 113 |
|
| 114 |
opt_help.add_connect_options(self.parser) |
| 115 |
opt_help.add_vault_options(self.parser) |
| 116 |
opt_help.add_runtask_options(self.parser) |
| 117 |
opt_help.add_subset_options(self.parser) |
| 118 |
opt_help.add_inventory_options(self.parser) |
| 119 |
opt_help.add_module_options(self.parser) |
| 120 |
opt_help.add_runas_prompt_options(self.parser) |
| 121 |
|
| 122 |
self.parser.add_argument('args', help='Playbook(s)', metavar='playbook.yml', nargs='*') |
| 123 |
|
| 124 |
|
| 125 |
self.parser.add_argument('--purge', default=False, action='store_true', help='purge checkout after playbook run') |
| 126 |
self.parser.add_argument('-o', '--only-if-changed', dest='ifchanged', default=False, action='store_true', |
| 127 |
help='only run the playbook if the repository has been updated') |
| 128 |
self.parser.add_argument('-s', '--sleep', dest='sleep', default=None, |
| 129 |
help='sleep for random interval (between 0 and n number of seconds) before starting. ' |
| 130 |
'This is a useful way to disperse git requests') |
| 131 |
self.parser.add_argument('-f', '--force', dest='force', default=False, action='store_true', |
| 132 |
help='run the playbook even if the repository could not be updated') |
| 133 |
self.parser.add_argument('-d', '--directory', dest='dest', default=None, type=opt_help.unfrack_path(), |
| 134 |
help='path to the directory to which Ansible will checkout the repository.') |
| 135 |
self.parser.add_argument('-U', '--url', dest='url', default=None, help='URL of the playbook repository') |
| 136 |
self.parser.add_argument('--full', dest='fullclone', action='store_true', help='Do a full clone, instead of a shallow one.') |
| 137 |
|
| 138 |
self.parser.add_argument('-C', '--checkout', dest='checkout', |
| 139 |
help='branch/tag/commit to checkout. Defaults to behavior of repository module.') |
| 140 |
self.parser.add_argument('--accept-host-key', default=False, dest='accept_host_key', action='store_true', |
| 141 |
help='adds the hostkey for the repo url if not already added') |
| 142 |
|
| 143 |
self.parser.add_argument('-m', '--module-name', dest='module_name', default=self.DEFAULT_REPO_TYPE, |
| 144 |
help='Repository module name, which ansible will use to check out the repo. Choices are %s. Default is %s.' |
| 145 |
% (self.REPO_CHOICES, self.DEFAULT_REPO_TYPE)) |
| 146 |
self.parser.add_argument('--verify-commit', dest='verify', default=False, action='store_true', |
| 147 |
help='verify GPG signature of checked out commit, if it fails abort running the playbook. ' |
| 148 |
'This needs the corresponding VCS module to support such an operation') |
| 149 |
self.parser.add_argument('--clean', dest='clean', default=False, action='store_true', |
| 150 |
help='modified files in the working repository will be discarded') |
| 151 |
self.parser.add_argument('--track-subs', dest='tracksubs', default=False, action='store_true', |
| 152 |
help='submodules will track the latest changes. This is equivalent to specifying the --remote flag to git submodule update') |
| 153 |
|
| 154 |
|
| 155 |
self.parser.add_argument("--check", default=False, dest='check', action='store_true', |
| 156 |
help="don't make any changes; instead, try to predict some of the changes that may occur") |
| 157 |
self.parser.add_argument("--diff", default=C.DIFF_ALWAYS, dest='diff', action='store_true', |
| 158 |
help="when changing (small) files and templates, show the differences in those files; works great with --check") |
| 159 |
|
| 160 |
def post_process_args(self, options): |
| 161 |
options = super(PullCLI, self).post_process_args(options) |
| 162 |
|
| 163 |
if not options.dest: |
| 164 |
hostname = socket.getfqdn() |
| 165 |
|
| 166 |
options.dest = os.path.join(C.ANSIBLE_HOME, 'pull', hostname) |
| 167 |
|
| 168 |
if os.path.exists(options.dest) and not os.path.isdir(options.dest): |
| 169 |
raise AnsibleOptionsError("%s is not a valid or accessible directory." % options.dest) |
| 170 |
|
| 171 |
if options.sleep: |
| 172 |
try: |
| 173 |
secs = secrets.randbelow(int(options.sleep)) |
| 174 |
options.sleep = secs |
| 175 |
except ValueError: |
| 176 |
raise AnsibleOptionsError("%s is not a number." % options.sleep) |
| 177 |
|
| 178 |
if not options.url: |
| 179 |
raise AnsibleOptionsError("URL for repository not specified, use -h for help") |
| 180 |
|
| 181 |
if options.module_name not in self.REPO_CHOICES: |
| 182 |
raise AnsibleOptionsError("Unsupported repo module %s, choices are %s" % (options.module_name, ','.join(self.REPO_CHOICES))) |
| 183 |
|
| 184 |
display.verbosity = options.verbosity |
| 185 |
self.validate_conflicts(options) |
| 186 |
|
| 187 |
return options |
| 188 |
|
| 189 |
def run(self): |
| 190 |
""" use Runner lib to do SSH things """ |
| 191 |
|
| 192 |
super(PullCLI, self).run() |
| 193 |
|
| 194 |
|
| 195 |
now = datetime.datetime.now() |
| 196 |
display.display(now.strftime("Starting Ansible Pull at %F %T")) |
| 197 |
display.display(' '.join(sys.argv)) |
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
node = platform.node() |
| 202 |
host = socket.getfqdn() |
| 203 |
hostnames = ','.join(set([host, node, host.split('.')[0], node.split('.')[0]])) |
| 204 |
if hostnames: |
| 205 |
limit_opts = 'localhost,%s,127.0.0.1' % hostnames |
| 206 |
else: |
| 207 |
limit_opts = 'localhost,127.0.0.1' |
| 208 |
base_opts = '-c local ' |
| 209 |
if context.CLIARGS['verbosity'] > 0: |
| 210 |
base_opts += ' -%s' % ''.join(["v" for dummy in range(0, context.CLIARGS['verbosity'])]) |
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
inv_opts = self._get_inv_cli() |
| 215 |
if not inv_opts: |
| 216 |
inv_opts = " -i localhost, " |
| 217 |
|
| 218 |
inv_opts += '-e %s ' % shlex.quote('ansible_python_interpreter=%s' % sys.executable) |
| 219 |
|
| 220 |
|
| 221 |
if context.CLIARGS['module_name'] == 'git': |
| 222 |
repo_opts = "name=%s dest=%s" % (context.CLIARGS['url'], context.CLIARGS['dest']) |
| 223 |
if context.CLIARGS['checkout']: |
| 224 |
repo_opts += ' version=%s' % context.CLIARGS['checkout'] |
| 225 |
|
| 226 |
if context.CLIARGS['accept_host_key']: |
| 227 |
repo_opts += ' accept_hostkey=yes' |
| 228 |
|
| 229 |
if context.CLIARGS['private_key_file']: |
| 230 |
repo_opts += ' key_file=%s' % context.CLIARGS['private_key_file'] |
| 231 |
|
| 232 |
if context.CLIARGS['verify']: |
| 233 |
repo_opts += ' verify_commit=yes' |
| 234 |
|
| 235 |
if context.CLIARGS['tracksubs']: |
| 236 |
repo_opts += ' track_submodules=yes' |
| 237 |
|
| 238 |
if not context.CLIARGS['fullclone']: |
| 239 |
repo_opts += ' depth=1' |
| 240 |
elif context.CLIARGS['module_name'] == 'subversion': |
| 241 |
repo_opts = "repo=%s dest=%s" % (context.CLIARGS['url'], context.CLIARGS['dest']) |
| 242 |
if context.CLIARGS['checkout']: |
| 243 |
repo_opts += ' revision=%s' % context.CLIARGS['checkout'] |
| 244 |
if not context.CLIARGS['fullclone']: |
| 245 |
repo_opts += ' export=yes' |
| 246 |
elif context.CLIARGS['module_name'] == 'hg': |
| 247 |
repo_opts = "repo=%s dest=%s" % (context.CLIARGS['url'], context.CLIARGS['dest']) |
| 248 |
if context.CLIARGS['checkout']: |
| 249 |
repo_opts += ' revision=%s' % context.CLIARGS['checkout'] |
| 250 |
elif context.CLIARGS['module_name'] == 'bzr': |
| 251 |
repo_opts = "name=%s dest=%s" % (context.CLIARGS['url'], context.CLIARGS['dest']) |
| 252 |
if context.CLIARGS['checkout']: |
| 253 |
repo_opts += ' version=%s' % context.CLIARGS['checkout'] |
| 254 |
else: |
| 255 |
raise AnsibleOptionsError('Unsupported (%s) SCM module for pull, choices are: %s' |
| 256 |
% (context.CLIARGS['module_name'], |
| 257 |
','.join(self.REPO_CHOICES))) |
| 258 |
|
| 259 |
|
| 260 |
if context.CLIARGS['clean']: |
| 261 |
repo_opts += ' force=yes' |
| 262 |
|
| 263 |
path = module_loader.find_plugin(context.CLIARGS['module_name']) |
| 264 |
if path is None: |
| 265 |
raise AnsibleOptionsError(("module '%s' not found.\n" % context.CLIARGS['module_name'])) |
| 266 |
|
| 267 |
bin_path = os.path.dirname(os.path.abspath(sys.argv[0])) |
| 268 |
|
| 269 |
cmd = '%s/ansible %s %s -m %s -a "%s" all -l "%s"' % (bin_path, inv_opts, base_opts, |
| 270 |
context.CLIARGS['module_name'], |
| 271 |
repo_opts, limit_opts) |
| 272 |
for ev in context.CLIARGS['extra_vars']: |
| 273 |
cmd += ' -e %s' % shlex.quote(ev) |
| 274 |
|
| 275 |
|
| 276 |
if context.CLIARGS['sleep']: |
| 277 |
display.display("Sleeping for %d seconds..." % context.CLIARGS['sleep']) |
| 278 |
time.sleep(context.CLIARGS['sleep']) |
| 279 |
|
| 280 |
|
| 281 |
display.debug("running ansible with VCS module to checkout repo") |
| 282 |
display.vvvv('EXEC: %s' % cmd) |
| 283 |
rc, b_out, b_err = safe_output_env(run_cmd)(cmd, live=True) |
| 284 |
|
| 285 |
if rc != 0: |
| 286 |
if context.CLIARGS['force']: |
| 287 |
display.warning("Unable to update repository. Continuing with (forced) run of playbook.") |
| 288 |
else: |
| 289 |
return rc |
| 290 |
elif context.CLIARGS['ifchanged']: |
| 291 |
|
| 292 |
for detect in (b'"changed": true', b"changed: True", b"| CHANGED =>"): |
| 293 |
if detect in b_out: |
| 294 |
break |
| 295 |
else: |
| 296 |
|
| 297 |
display.display(f"Repository has not changed, quitting: {b_out!r}") |
| 298 |
return 0 |
| 299 |
|
| 300 |
playbook = self.select_playbook(context.CLIARGS['dest']) |
| 301 |
if playbook is None: |
| 302 |
raise AnsibleOptionsError("Could not find a playbook to run.") |
| 303 |
|
| 304 |
|
| 305 |
cmd = '%s/ansible-playbook %s %s' % (bin_path, base_opts, playbook) |
| 306 |
if context.CLIARGS['vault_password_files']: |
| 307 |
for vault_password_file in context.CLIARGS['vault_password_files']: |
| 308 |
cmd += " --vault-password-file=%s" % vault_password_file |
| 309 |
if context.CLIARGS['vault_ids']: |
| 310 |
for vault_id in context.CLIARGS['vault_ids']: |
| 311 |
cmd += " --vault-id=%s" % vault_id |
| 312 |
|
| 313 |
if context.CLIARGS['become_password_file']: |
| 314 |
cmd += " --become-password-file=%s" % context.CLIARGS['become_password_file'] |
| 315 |
|
| 316 |
if context.CLIARGS['connection_password_file']: |
| 317 |
cmd += " --connection-password-file=%s" % context.CLIARGS['connection_password_file'] |
| 318 |
|
| 319 |
for ev in context.CLIARGS['extra_vars']: |
| 320 |
cmd += ' -e %s' % shlex.quote(ev) |
| 321 |
|
| 322 |
if context.CLIARGS['become_ask_pass']: |
| 323 |
cmd += ' --ask-become-pass' |
| 324 |
if context.CLIARGS['skip_tags']: |
| 325 |
cmd += ' --skip-tags "%s"' % to_native(u','.join(context.CLIARGS['skip_tags'])) |
| 326 |
if context.CLIARGS['tags']: |
| 327 |
cmd += ' -t "%s"' % to_native(u','.join(context.CLIARGS['tags'])) |
| 328 |
if context.CLIARGS['subset']: |
| 329 |
cmd += ' -l "%s"' % context.CLIARGS['subset'] |
| 330 |
else: |
| 331 |
cmd += ' -l "%s"' % limit_opts |
| 332 |
if context.CLIARGS['check']: |
| 333 |
cmd += ' -C' |
| 334 |
if context.CLIARGS['diff']: |
| 335 |
cmd += ' -D' |
| 336 |
|
| 337 |
if context.CLIARGS['flush_cache']: |
| 338 |
cmd += ' --flush-cache' |
| 339 |
|
| 340 |
os.chdir(context.CLIARGS['dest']) |
| 341 |
|
| 342 |
|
| 343 |
inv_opts = self._get_inv_cli() |
| 344 |
if inv_opts: |
| 345 |
cmd += inv_opts |
| 346 |
|
| 347 |
|
| 348 |
display.debug("running ansible-playbook to do actual work") |
| 349 |
display.debug('EXEC: %s' % cmd) |
| 350 |
rc, b_out, b_err = run_cmd(cmd, live=True) |
| 351 |
|
| 352 |
if context.CLIARGS['purge']: |
| 353 |
os.chdir('/') |
| 354 |
try: |
| 355 |
display.debug("removing: %s" % context.CLIARGS['dest']) |
| 356 |
shutil.rmtree(context.CLIARGS['dest']) |
| 357 |
except Exception as e: |
| 358 |
display.error(u"Failed to remove %s: %s" % (context.CLIARGS['dest'], to_text(e))) |
| 359 |
|
| 360 |
return rc |
| 361 |
|
| 362 |
@staticmethod |
| 363 |
def try_playbook(path): |
| 364 |
if not os.path.exists(path): |
| 365 |
return 1 |
| 366 |
if not os.access(path, os.R_OK): |
| 367 |
return 2 |
| 368 |
return 0 |
| 369 |
|
| 370 |
@staticmethod |
| 371 |
def select_playbook(path): |
| 372 |
playbook = None |
| 373 |
errors = [] |
| 374 |
if context.CLIARGS['args'] and context.CLIARGS['args'][0] is not None: |
| 375 |
playbooks = [] |
| 376 |
for book in context.CLIARGS['args']: |
| 377 |
book_path = os.path.join(path, book) |
| 378 |
rc = PullCLI.try_playbook(book_path) |
| 379 |
if rc != 0: |
| 380 |
errors.append("%s: %s" % (book_path, PullCLI.PLAYBOOK_ERRORS[rc])) |
| 381 |
continue |
| 382 |
playbooks.append(book_path) |
| 383 |
if 0 < len(errors): |
| 384 |
display.warning("\n".join(errors)) |
| 385 |
elif len(playbooks) == len(context.CLIARGS['args']): |
| 386 |
playbook = " ".join(playbooks) |
| 387 |
return playbook |
| 388 |
else: |
| 389 |
fqdn = socket.getfqdn() |
| 390 |
hostpb = os.path.join(path, fqdn + '.yml') |
| 391 |
shorthostpb = os.path.join(path, fqdn.split('.')[0] + '.yml') |
| 392 |
localpb = os.path.join(path, PullCLI.DEFAULT_PLAYBOOK) |
| 393 |
for pb in [hostpb, shorthostpb, localpb]: |
| 394 |
rc = PullCLI.try_playbook(pb) |
| 395 |
if rc == 0: |
| 396 |
playbook = pb |
| 397 |
break |
| 398 |
else: |
| 399 |
errors.append("%s: %s" % (pb, PullCLI.PLAYBOOK_ERRORS[rc])) |
| 400 |
if playbook is None: |
| 401 |
display.warning("\n".join(errors)) |
| 402 |
return playbook |
| 403 |
|
| 404 |
|
| 405 |
def main(args=None): |
| 406 |
PullCLI.cli_executor(args) |
| 407 |
|
| 408 |
|
| 409 |
if __name__ == '__main__': |
| 410 |
main() |