| •1 |
#!/usr/bin/env python3 |
| 2 |
# (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 os |
| 13 |
import stat |
| 14 |
|
| 15 |
from ansible import constants as C |
| 16 |
from ansible import context |
| 17 |
from ansible.cli.arguments import option_helpers as opt_help |
| 18 |
from ansible.errors import AnsibleError |
| 19 |
from ansible.executor.playbook_executor import PlaybookExecutor |
| 20 |
from ansible.module_utils.common.text.converters import to_bytes |
| 21 |
from ansible.playbook.block import Block |
| 22 |
from ansible.plugins.loader import add_all_plugin_dirs |
| 23 |
from ansible.utils.collection_loader import AnsibleCollectionConfig |
| 24 |
from ansible.utils.collection_loader._collection_finder import _get_collection_name_from_path, _get_collection_playbook_path |
| 25 |
from ansible.utils.display import Display |
| 26 |
|
| 27 |
|
| 28 |
display = Display() |
| 29 |
|
| 30 |
|
| 31 |
class PlaybookCLI(CLI): |
| 32 |
""" the tool to run *Ansible playbooks*, which are a configuration and multinode deployment system. |
| 33 |
See the project home page (https://docs.ansible.com) for more information. """ |
| 34 |
|
| 35 |
name = 'ansible-playbook' |
| 36 |
|
| 37 |
USES_CONNECTION = True |
| 38 |
|
| 39 |
def init_parser(self): |
| 40 |
|
| 41 |
# create parser for CLI options |
| 42 |
super(PlaybookCLI, self).init_parser( |
| 43 |
desc="Runs Ansible playbooks, executing the defined tasks on the targeted hosts.") |
| 44 |
|
| 45 |
opt_help.add_connect_options(self.parser) |
| 46 |
opt_help.add_meta_options(self.parser) |
| 47 |
opt_help.add_runas_options(self.parser) |
| 48 |
opt_help.add_subset_options(self.parser) |
| 49 |
opt_help.add_check_options(self.parser) |
| 50 |
opt_help.add_inventory_options(self.parser) |
| 51 |
opt_help.add_runtask_options(self.parser) |
| 52 |
opt_help.add_vault_options(self.parser) |
| 53 |
opt_help.add_fork_options(self.parser) |
| 54 |
opt_help.add_module_options(self.parser) |
| 55 |
|
| 56 |
# ansible playbook specific opts |
| 57 |
self.parser.add_argument('--syntax-check', dest='syntax', action='store_true', |
| 58 |
help="perform a syntax check on the playbook, but do not execute it") |
| 59 |
self.parser.add_argument('--list-tasks', dest='listtasks', action='store_true', |
| 60 |
help="list all tasks that would be executed") |
| 61 |
self.parser.add_argument('--list-tags', dest='listtags', action='store_true', |
| 62 |
help="list all available tags") |
| 63 |
self.parser.add_argument('--step', dest='step', action='store_true', |
| 64 |
help="one-step-at-a-time: confirm each task before running") |
| 65 |
self.parser.add_argument('--start-at-task', dest='start_at_task', |
| 66 |
help="start the playbook at the task matching this name") |
| 67 |
self.parser.add_argument('args', help='Playbook(s)', metavar='playbook', nargs='+') |
| 68 |
|
| 69 |
def post_process_args(self, options): |
| 70 |
|
| 71 |
# for listing, we need to know if user had tag input |
| 72 |
# capture here as parent function sets defaults for tags |
| 73 |
havetags = bool(options.tags or options.skip_tags) |
| 74 |
|
| 75 |
options = super(PlaybookCLI, self).post_process_args(options) |
| 76 |
|
| 77 |
if options.listtags: |
| 78 |
# default to all tags (including never), when listing tags |
| 79 |
# unless user specified tags |
| 80 |
if not havetags: |
| 81 |
options.tags = ['never', 'all'] |
| 82 |
|
| 83 |
display.verbosity = options.verbosity |
| 84 |
self.validate_conflicts(options, runas_opts=True, fork_opts=True) |
| 85 |
|
| 86 |
return options |
| 87 |
|
| 88 |
def run(self): |
| 89 |
|
| 90 |
super(PlaybookCLI, self).run() |
| 91 |
|
| 92 |
# Note: slightly wrong, this is written so that implicit localhost |
| 93 |
# manages passwords |
| 94 |
sshpass = None |
| 95 |
becomepass = None |
| 96 |
passwords = {} |
| 97 |
|
| 98 |
# initial error check, to make sure all specified playbooks are accessible |
| 99 |
# before we start running anything through the playbook executor |
| 100 |
# also prep plugin paths |
| 101 |
b_playbook_dirs = [] |
| 102 |
for playbook in context.CLIARGS['args']: |
| 103 |
|
| 104 |
# resolve if it is collection playbook with FQCN notation, if not, leaves unchanged |
| 105 |
resource = _get_collection_playbook_path(playbook) |
| 106 |
if resource is not None: |
| 107 |
playbook_collection = resource[2] |
| 108 |
else: |
| 109 |
# not an FQCN so must be a file |
| 110 |
if not os.path.exists(playbook): |
| 111 |
raise AnsibleError("the playbook: %s could not be found" % playbook) |
| 112 |
if not (os.path.isfile(playbook) or stat.S_ISFIFO(os.stat(playbook).st_mode)): |
| 113 |
raise AnsibleError("the playbook: %s does not appear to be a file" % playbook) |
| 114 |
|
| 115 |
# check if playbook is from collection (path can be passed directly) |
| 116 |
playbook_collection = _get_collection_name_from_path(playbook) |
| 117 |
|
| 118 |
# don't add collection playbooks to adjacency search path |
| 119 |
if not playbook_collection: |
| 120 |
# setup dirs to enable loading plugins from all playbooks in case they add callbacks/inventory/etc |
| 121 |
b_playbook_dir = os.path.dirname(os.path.abspath(to_bytes(playbook, errors='surrogate_or_strict'))) |
| 122 |
add_all_plugin_dirs(b_playbook_dir) |
| 123 |
b_playbook_dirs.append(b_playbook_dir) |
| 124 |
|
| 125 |
if b_playbook_dirs: |
| 126 |
# allow collections adjacent to these playbooks |
| 127 |
# we use list copy to avoid opening up 'adjacency' in the previous loop |
| 128 |
AnsibleCollectionConfig.playbook_paths = b_playbook_dirs |
| 129 |
|
| 130 |
# don't deal with privilege escalation or passwords when we don't need to |
| 131 |
if not (context.CLIARGS['listhosts'] or context.CLIARGS['listtasks'] or |
| 132 |
context.CLIARGS['listtags'] or context.CLIARGS['syntax']): |
| 133 |
(sshpass, becomepass) = self.ask_passwords() |
| 134 |
passwords = {'conn_pass': sshpass, 'become_pass': becomepass} |
| 135 |
|
| 136 |
# create base objects |
| 137 |
loader, inventory, variable_manager = self._play_prereqs() |
| 138 |
|
| 139 |
# (which is not returned in list_hosts()) is taken into account for |
| 140 |
# warning if inventory is empty. But it can't be taken into account for |
| 141 |
# checking if limit doesn't match any hosts. Instead we don't worry about |
| 142 |
# limit if only implicit localhost was in inventory to start with. |
| 143 |
# |
| 144 |
# Fix this when we rewrite inventory by making localhost a real host (and thus show up in list_hosts()) |
| 145 |
CLI.get_host_list(inventory, context.CLIARGS['subset']) |
| 146 |
|
| 147 |
# create the playbook executor, which manages running the plays via a task queue manager |
| 148 |
pbex = PlaybookExecutor(playbooks=context.CLIARGS['args'], inventory=inventory, |
| 149 |
variable_manager=variable_manager, loader=loader, |
| 150 |
passwords=passwords) |
| 151 |
|
| 152 |
results = pbex.run() |
| 153 |
|
| 154 |
if isinstance(results, list): |
| 155 |
for p in results: |
| 156 |
|
| 157 |
display.display('\nplaybook: %s' % p['playbook']) |
| 158 |
for idx, play in enumerate(p['plays']): |
| 159 |
if play._included_path is not None: |
| 160 |
loader.set_basedir(play._included_path) |
| 161 |
else: |
| 162 |
pb_dir = os.path.realpath(os.path.dirname(p['playbook'])) |
| 163 |
loader.set_basedir(pb_dir) |
| 164 |
|
| 165 |
# show host list if we were able to template into a list |
| 166 |
try: |
| 167 |
host_list = ','.join(play.hosts) |
| 168 |
except TypeError: |
| 169 |
host_list = '' |
| 170 |
|
| 171 |
msg = "\n play #%d (%s): %s" % (idx + 1, host_list, play.name) |
| 172 |
mytags = set(play.tags) |
| 173 |
msg += '\tTAGS: [%s]' % (','.join(mytags)) |
| 174 |
|
| 175 |
if context.CLIARGS['listhosts']: |
| 176 |
playhosts = set(inventory.get_hosts(play.hosts)) |
| 177 |
msg += "\n pattern: %s\n hosts (%d):" % (play.hosts, len(playhosts)) |
| 178 |
for host in playhosts: |
| 179 |
msg += "\n %s" % host |
| 180 |
|
| 181 |
display.display(msg) |
| 182 |
|
| 183 |
all_tags = set() |
| 184 |
if context.CLIARGS['listtags'] or context.CLIARGS['listtasks']: |
| 185 |
taskmsg = '' |
| 186 |
if context.CLIARGS['listtasks']: |
| 187 |
taskmsg = ' tasks:\n' |
| 188 |
|
| 189 |
def _process_block(b): |
| 190 |
taskmsg = '' |
| 191 |
for task in b.block: |
| 192 |
if isinstance(task, Block): |
| 193 |
taskmsg += _process_block(task) |
| 194 |
else: |
| 195 |
if task.action in C._ACTION_META and task.implicit: |
| 196 |
continue |
| 197 |
|
| 198 |
all_tags.update(task.tags) |
| 199 |
if context.CLIARGS['listtasks']: |
| 200 |
cur_tags = list(mytags.union(set(task.tags))) |
| 201 |
cur_tags.sort() |
| 202 |
if task.name: |
| 203 |
taskmsg += " %s" % task.get_name() |
| 204 |
else: |
| 205 |
taskmsg += " %s" % task.action |
| 206 |
taskmsg += "\tTAGS: [%s]\n" % ', '.join(cur_tags) |
| 207 |
|
| 208 |
return taskmsg |
| 209 |
|
| 210 |
all_vars = variable_manager.get_vars(play=play) |
| 211 |
for block in play.compile(): |
| 212 |
block = block.filter_tagged_tasks(all_vars) |
| 213 |
if not block.has_tasks(): |
| 214 |
continue |
| 215 |
taskmsg += _process_block(block) |
| 216 |
|
| 217 |
if context.CLIARGS['listtags']: |
| 218 |
cur_tags = list(mytags.union(all_tags)) |
| 219 |
cur_tags.sort() |
| 220 |
taskmsg += " TASK TAGS: [%s]\n" % ', '.join(cur_tags) |
| 221 |
|
| 222 |
display.display(taskmsg) |
| 223 |
|
| 224 |
return 0 |
| 225 |
else: |
| 226 |
return results |
| 227 |
|
| 228 |
|
| 229 |
def main(args=None): |
| 230 |
PlaybookCLI.cli_executor(args) |
| 231 |
|
| 232 |
|
| 233 |
if __name__ == '__main__': |
| 234 |
main() |