Debian Codegraph @

lib/ansible/cli/pull.py

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