| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import json |
| 10 |
|
| 11 |
|
| 12 |
from ansible.cli import CLI |
| 13 |
from ansible import constants as C |
| 14 |
from ansible import context |
| 15 |
from ansible.cli.arguments import option_helpers as opt_help |
| 16 |
from ansible.errors import AnsibleError, AnsibleOptionsError, AnsibleParserError |
| 17 |
from ansible.executor.task_queue_manager import AnsibleEndPlay, TaskQueueManager |
| 18 |
from ansible.module_utils.common.text.converters import to_text |
| 19 |
from ansible.parsing.splitter import parse_kv |
| 20 |
from ansible.playbook import Playbook |
| 21 |
from ansible.playbook.play import Play |
| 22 |
from ansible._internal._datatag._tags import Origin |
| 23 |
from ansible.utils.display import Display |
| 24 |
from ansible._internal._json._profiles import _legacy |
| 25 |
|
| 26 |
display = Display() |
| 27 |
|
| 28 |
|
| 29 |
class AdHocCLI(CLI): |
| 30 |
""" is an extra-simple tool/framework/API for doing 'remote things'. |
| 31 |
this command allows you to define and run a single task 'playbook' against a set of hosts |
| 32 |
""" |
| 33 |
|
| 34 |
name = 'ansible' |
| 35 |
|
| 36 |
USES_CONNECTION = True |
| 37 |
|
| 38 |
def init_parser(self): |
| 39 |
""" create an options parser for bin/ansible """ |
| 40 |
super(AdHocCLI, self).init_parser(desc="Define and run a single task 'playbook' against a set of hosts", |
| 41 |
epilog="Some actions do not make sense in Ad-Hoc (include, meta, etc)") |
| 42 |
|
| 43 |
opt_help.add_runas_options(self.parser) |
| 44 |
opt_help.add_inventory_options(self.parser) |
| 45 |
opt_help.add_async_options(self.parser) |
| 46 |
opt_help.add_output_options(self.parser) |
| 47 |
opt_help.add_connect_options(self.parser) |
| 48 |
opt_help.add_check_options(self.parser) |
| 49 |
opt_help.add_runtask_options(self.parser) |
| 50 |
opt_help.add_vault_options(self.parser) |
| 51 |
opt_help.add_fork_options(self.parser) |
| 52 |
opt_help.add_module_options(self.parser) |
| 53 |
opt_help.add_basedir_options(self.parser) |
| 54 |
opt_help.add_tasknoplay_options(self.parser) |
| 55 |
|
| 56 |
|
| 57 |
self.parser.add_argument('-a', '--args', dest='module_args', |
| 58 |
help="The action's options in space separated k=v format: -a 'opt1=val1 opt2=val2' " |
| 59 |
"or a json string: -a '{\"opt1\": \"val1\", \"opt2\": \"val2\"}'", |
| 60 |
default=C.DEFAULT_MODULE_ARGS) |
| 61 |
self.parser.add_argument('-m', '--module-name', dest='module_name', |
| 62 |
help="Name of the action to execute (default=%s)" % C.DEFAULT_MODULE_NAME, |
| 63 |
default=C.DEFAULT_MODULE_NAME) |
| 64 |
self.parser.add_argument('args', metavar='pattern', help='host pattern') |
| 65 |
|
| 66 |
def post_process_args(self, options): |
| 67 |
"""Post process and validate options for bin/ansible """ |
| 68 |
|
| 69 |
options = super(AdHocCLI, self).post_process_args(options) |
| 70 |
|
| 71 |
display.verbosity = options.verbosity |
| 72 |
self.validate_conflicts(options, runas_opts=True, fork_opts=True) |
| 73 |
|
| 74 |
return options |
| 75 |
|
| 76 |
def _play_ds(self, pattern, async_val, poll): |
| 77 |
check_raw = context.CLIARGS['module_name'] in C.MODULE_REQUIRE_ARGS |
| 78 |
|
| 79 |
module_args_raw = context.CLIARGS['module_args'] |
| 80 |
module_args = None |
| 81 |
if module_args_raw and module_args_raw.startswith('{') and module_args_raw.endswith('}'): |
| 82 |
try: |
| 83 |
module_args = json.loads(module_args_raw, cls=_legacy.Decoder) |
| 84 |
except AnsibleParserError: |
| 85 |
pass |
| 86 |
|
| 87 |
if not module_args: |
| 88 |
module_args = parse_kv(module_args_raw, check_raw=check_raw) |
| 89 |
|
| 90 |
mytask = dict( |
| 91 |
action=context.CLIARGS['module_name'], |
| 92 |
args=module_args, |
| 93 |
timeout=context.CLIARGS['task_timeout'], |
| 94 |
) |
| 95 |
|
| 96 |
mytask = Origin(description=f'<adhoc {context.CLIARGS["module_name"]!r} task>').tag(mytask) |
| 97 |
|
| 98 |
|
| 99 |
if context.CLIARGS['module_name'] not in C._ACTION_ALL_INCLUDE_ROLE_TASKS and any(frozenset((async_val, poll))): |
| 100 |
mytask['async_val'] = async_val |
| 101 |
mytask['poll'] = poll |
| 102 |
|
| 103 |
return dict( |
| 104 |
name="Ansible Ad-Hoc", |
| 105 |
hosts=pattern, |
| 106 |
gather_facts='no', |
| 107 |
tasks=[mytask]) |
| 108 |
|
| 109 |
def run(self): |
| 110 |
""" create and execute the single task playbook """ |
| 111 |
|
| 112 |
super(AdHocCLI, self).run() |
| 113 |
|
| 114 |
|
| 115 |
pattern = to_text(context.CLIARGS['args'], errors='surrogate_or_strict') |
| 116 |
|
| 117 |
|
| 118 |
sshpass = None |
| 119 |
becomepass = None |
| 120 |
|
| 121 |
(sshpass, becomepass) = self.ask_passwords() |
| 122 |
passwords = {'conn_pass': sshpass, 'become_pass': becomepass} |
| 123 |
|
| 124 |
|
| 125 |
loader, inventory, variable_manager = self._play_prereqs() |
| 126 |
|
| 127 |
|
| 128 |
try: |
| 129 |
hosts = self.get_host_list(inventory, context.CLIARGS['subset'], pattern) |
| 130 |
except AnsibleError: |
| 131 |
if context.CLIARGS['subset']: |
| 132 |
raise |
| 133 |
else: |
| 134 |
hosts = [] |
| 135 |
display.warning("No hosts matched, nothing to do") |
| 136 |
|
| 137 |
|
| 138 |
if context.CLIARGS['listhosts']: |
| 139 |
display.display(' hosts (%d):' % len(hosts)) |
| 140 |
for host in hosts: |
| 141 |
display.display(' %s' % host) |
| 142 |
return 0 |
| 143 |
|
| 144 |
|
| 145 |
if context.CLIARGS['module_name'] in C.MODULE_REQUIRE_ARGS and not context.CLIARGS['module_args']: |
| 146 |
err = "No argument passed to %s module" % context.CLIARGS['module_name'] |
| 147 |
if pattern.endswith(".yml"): |
| 148 |
err = err + ' (did you mean to run ansible-playbook?)' |
| 149 |
raise AnsibleOptionsError(err) |
| 150 |
|
| 151 |
|
| 152 |
if context.CLIARGS['module_name'] in C._ACTION_IMPORT_PLAYBOOK: |
| 153 |
raise AnsibleOptionsError("'%s' is not a valid action for ad-hoc commands" |
| 154 |
% context.CLIARGS['module_name']) |
| 155 |
|
| 156 |
|
| 157 |
play_ds = self._play_ds(pattern, context.CLIARGS['seconds'], context.CLIARGS['poll_interval']) |
| 158 |
play = Play().load(play_ds, variable_manager=variable_manager, loader=loader) |
| 159 |
|
| 160 |
|
| 161 |
playbook = Playbook(loader) |
| 162 |
playbook._entries.append(play) |
| 163 |
playbook._file_name = '__adhoc_playbook__' |
| 164 |
|
| 165 |
if self.callback: |
| 166 |
cb = self.callback |
| 167 |
elif context.CLIARGS['one_line']: |
| 168 |
cb = 'oneline' |
| 169 |
|
| 170 |
elif C.DEFAULT_LOAD_CALLBACK_PLUGINS and C.DEFAULT_STDOUT_CALLBACK != 'default': |
| 171 |
cb = C.DEFAULT_STDOUT_CALLBACK |
| 172 |
else: |
| 173 |
cb = 'minimal' |
| 174 |
|
| 175 |
run_tree = False |
| 176 |
if context.CLIARGS['tree']: |
| 177 |
C.CALLBACKS_ENABLED.append('tree') |
| 178 |
C.TREE_DIR = context.CLIARGS['tree'] |
| 179 |
run_tree = True |
| 180 |
|
| 181 |
|
| 182 |
self._tqm = None |
| 183 |
try: |
| 184 |
self._tqm = TaskQueueManager( |
| 185 |
inventory=inventory, |
| 186 |
variable_manager=variable_manager, |
| 187 |
loader=loader, |
| 188 |
passwords=passwords, |
| 189 |
stdout_callback_name=cb, |
| 190 |
run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS, |
| 191 |
run_tree=run_tree, |
| 192 |
forks=context.CLIARGS['forks'], |
| 193 |
) |
| 194 |
|
| 195 |
self._tqm.load_callbacks() |
| 196 |
self._tqm.send_callback('v2_playbook_on_start', playbook) |
| 197 |
|
| 198 |
result = self._tqm.run(play) |
| 199 |
|
| 200 |
self._tqm.send_callback('v2_playbook_on_stats', self._tqm._stats) |
| 201 |
except AnsibleEndPlay as e: |
| 202 |
result = e.result |
| 203 |
finally: |
| 204 |
if self._tqm: |
| 205 |
self._tqm.cleanup() |
| 206 |
if loader: |
| 207 |
loader.cleanup_all_tmp_files() |
| 208 |
|
| 209 |
return result |
| 210 |
|
| 211 |
|
| 212 |
def main(args=None): |
| 213 |
AdHocCLI.cli_executor(args) |
| 214 |
|
| 215 |
|
| 216 |
if __name__ == '__main__': |
| 217 |
main() |