jumpserver/apps/ops/ansible/runner.py

262 lines
8.6 KiB
Python
Raw Normal View History

2017-03-05 12:53:24 +00:00
# ~*~ coding: utf-8 ~*~
2017-03-05 15:30:14 +00:00
import os
import shutil
2017-12-06 10:31:51 +00:00
from collections import namedtuple
2017-03-05 15:30:14 +00:00
from ansible import context
from ansible.playbook import Playbook
from ansible.module_utils.common.collections import ImmutableDict
2017-03-05 15:30:14 +00:00
from ansible.executor.task_queue_manager import TaskQueueManager
2017-12-06 10:31:51 +00:00
from ansible.vars.manager import VariableManager
2017-03-05 15:30:14 +00:00
from ansible.parsing.dataloader import DataLoader
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.playbook.play import Play
import ansible.constants as C
from .callback import (
AdHocResultCallback, PlaybookResultCallBack, CommandResultCallback
)
2017-03-05 15:30:14 +00:00
from common.utils import get_logger
2017-12-06 10:31:51 +00:00
from .exceptions import AnsibleError
from .display import AdHocDisplay
2017-03-05 15:30:14 +00:00
__all__ = ["AdHocRunner", "PlayBookRunner", "CommandRunner"]
2017-03-05 15:30:14 +00:00
C.HOST_KEY_CHECKING = False
logger = get_logger(__name__)
2017-12-06 10:31:51 +00:00
Options = namedtuple('Options', [
'listtags', 'listtasks', 'listhosts', 'syntax', 'connection',
'module_path', 'forks', 'remote_user', 'private_key_file', 'timeout',
'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
'scp_extra_args', 'become', 'become_method', 'become_user',
'verbosity', 'check', 'extra_vars', 'playbook_path', 'passwords',
2017-12-28 04:03:02 +00:00
'diff', 'gathering', 'remote_tmp',
2017-12-06 10:31:51 +00:00
])
def get_default_options():
options = dict(
2017-12-06 10:31:51 +00:00
syntax=False,
timeout=30,
2017-12-06 10:31:51 +00:00
connection='ssh',
forks=10,
remote_user='root',
private_key_file=None,
become=None,
become_method=None,
become_user=None,
verbosity=1,
2017-12-06 10:31:51 +00:00
check=False,
diff=False,
2017-12-07 08:25:50 +00:00
gathering='implicit',
2017-12-28 04:03:02 +00:00
remote_tmp='/tmp/.ansible'
2017-12-06 10:31:51 +00:00
)
return options
1.5.7 Merge to dev (#3766) * [Update] 暂存,优化解决不了问题 * [Update] 待续(小白) * [Update] 修改asset user * [Update] 计划再次更改 * [Update] 修改asset user * [Update] 暂存与喜爱 * [Update] Add id in * [Update] 阶段性完成ops task该做 * [Update] 修改asset user api * [Update] 修改asset user 任务,查看认证等 * [Update] 基本完成asset user改造 * [Update] dynamic user only allow 1 * [Update] 修改asset user task * [Update] 修改node admin user task api * [Update] remove file header license * [Update] 添加sftp root * [Update] 暂存 * [Update] 暂存 * [Update] 修改翻译 * [Update] 修改系统用户改为同名后,用户名改为空 * [Update] 基本完成CAS调研 * [Update] 支持cas server * [Update] 支持cas server * [Update] 添加requirements * [Update] 为方便调试添加mysql ipython到包中 * [Update] 添加huaweiyun翻译 * [Update] 增加下载session 录像 * [Update] 只有第一次通知replay离线的使用方法 * [Update] 暂存一下 * [Bugfix] 获取系统用户信息报错 * [Bugfix] 修改system user info * [Update] 改成清理10天git status * [Update] 修改celery日志保留时间 * [Update]修复部分pip包依赖的版本不兼容问题 (#3672) * [Update] 修复用户更新页面会清空用户public_key的问题 * Fix broken dependencies Co-authored-by: BaiJiangJie <32935519+BaiJiangJie@users.noreply.github.com> * [Update] 修改获取系统用户auth info * [Update] Remove log * [Bugfix] 修复sftp home设置的bug * [Update] 授权的系统用户添加sftp root * [Update] 修改系统用户关联的用户 * [Update] 修改placeholder * [Update] 优化获取授权的系统用户 * [Update] 修改tasks * [Update] tree service update * [Update] 暂存 * [Update] 基本完成用户授权树和资产树改造 * [Update] Dashbaord perf * [update] Add huawei cloud sdk requirements * [Updte] 优化dashboard页面 * [Update] system user auth info 添加id * [Update] 修改系统用户serializer * [Update] 优化api * [Update] LDAP Test Util (#3720) * [Update] LDAPTestUtil 1 * [Update] LDAPTestUtil 2 * [Update] LDAPTestUtil 3 * [Update] LDAPTestUtil 4 * [Update] LDAPTestUtil 5 * [Update] LDAPTestUtil 6 * [Update] LDAPTestUtil 7 * [Update] session 已添加is success,并且添加display serializer * [Bugfix] 修复无法删除空节点的bug * [Update] 命令记录分组织显示 * [Update] Session is_success 添加迁移文件 * [Update] 批量命令添加org_id * [Update] 修复一些文案,修改不绑定MFA,不能ssh登录 * [Update] 修改replay api, 返回session信息 * [Update] 解决无效es导致访问命令记录页面失败的问题 * [Update] 拆分profile view * [Update] 修改一个翻译 * [Update] 修改aysnc api框架 * [Update] 命令列表添加risk level * [Update] 完成录像打包下载 * [Update] 更改登陆otp页面 * [Update] 修改command 存储redis_level * [Update] 修改翻译 * [Update] 修改系统用户的用户列表字段 * [Update] 使用新logo和统一Jumpserver为JumpServer * [Update] 优化cloud task * [Update] 统一period task * [Update] 统一period form serializer字段 * [Update] 修改period task * [Update] 修改资产网关信息 * [Update] 用户授权资产树资产信息添加domain * [Update] 修改翻译 * [Update] 测试可连接性 * 1.5.7 bai (#3764) * [Update] 修复index页面Bug;修复测试资产用户可连接性问题; * [Update] 修改测试资产用户可连接 * [Bugfix] 修复backends问题 * [Update] 修改marksafe依赖版本 * [Update] 修改测试资产用户可连接性 * [Update] 修改检测服务器性能时获取percent值 * [Update] 更新依赖boto3=1.12.14 Co-authored-by: Yanzhe Lee <lee.yanzhe@yanzhe.org> Co-authored-by: BaiJiangJie <32935519+BaiJiangJie@users.noreply.github.com> Co-authored-by: Bai <bugatti_it@163.com>
2020-03-12 08:24:38 +00:00
# JumpServer not use playbook
2017-12-06 10:31:51 +00:00
class PlayBookRunner:
2017-03-05 15:30:14 +00:00
"""
用于执行AnsiblePlaybook的接口.简化Playbook对象的使用.
"""
2017-12-06 10:31:51 +00:00
# Default results callback
results_callback_class = PlaybookResultCallBack
loader_class = DataLoader
variable_manager_class = VariableManager
options = get_default_options()
2017-12-10 16:29:25 +00:00
def __init__(self, inventory=None, options=None):
2017-12-06 10:31:51 +00:00
"""
:param options: Ansible options like ansible.cfg
2017-12-10 16:29:25 +00:00
:param inventory: Ansible inventory
2017-12-06 10:31:51 +00:00
"""
if options:
self.options = options
2017-03-05 15:30:14 +00:00
C.RETRY_FILES_ENABLED = False
2017-12-10 16:29:25 +00:00
self.inventory = inventory
2017-12-06 10:31:51 +00:00
self.loader = self.loader_class()
self.results_callback = self.results_callback_class()
self.playbook_path = options.playbook_path
self.variable_manager = self.variable_manager_class(
loader=self.loader, inventory=self.inventory
2017-03-05 15:30:14 +00:00
)
2017-12-06 10:31:51 +00:00
self.passwords = options.passwords
self.__check()
2017-03-05 15:30:14 +00:00
2017-12-06 10:31:51 +00:00
def __check(self):
if self.options.playbook_path is None or \
not os.path.exists(self.options.playbook_path):
raise AnsibleError(
"Not Found the playbook file: {}.".format(self.options.playbook_path)
)
if not self.inventory.list_hosts('all'):
raise AnsibleError('Inventory is empty')
2017-03-05 15:30:14 +00:00
2017-12-06 10:31:51 +00:00
def run(self):
executor = PlaybookExecutor(
2017-03-05 15:30:14 +00:00
playbooks=[self.playbook_path],
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
passwords={"conn_pass": self.passwords}
2017-12-06 10:31:51 +00:00
)
context.CLIARGS = ImmutableDict(self.options)
2017-03-05 15:30:14 +00:00
2017-12-06 10:31:51 +00:00
if executor._tqm:
executor._tqm._stdout_callback = self.results_callback
executor.run()
executor._tqm.cleanup()
return self.results_callback.output
2017-03-05 15:30:14 +00:00
2017-12-06 10:31:51 +00:00
class AdHocRunner:
2017-03-05 15:30:14 +00:00
"""
2017-12-06 10:31:51 +00:00
ADHoc Runner接口
2017-03-05 15:30:14 +00:00
"""
2017-03-13 16:58:25 +00:00
results_callback_class = AdHocResultCallback
2018-03-30 14:03:43 +00:00
results_callback = None
2017-12-06 10:31:51 +00:00
loader_class = DataLoader
variable_manager_class = VariableManager
default_options = get_default_options()
2018-12-10 11:51:35 +00:00
command_modules_choices = ('shell', 'raw', 'command', 'script', 'win_shell')
2017-03-13 16:58:25 +00:00
2017-12-10 16:29:25 +00:00
def __init__(self, inventory, options=None):
2018-03-30 14:03:43 +00:00
self.options = self.update_options(options)
2017-12-10 16:29:25 +00:00
self.inventory = inventory
2017-03-05 15:30:14 +00:00
self.loader = DataLoader()
2017-12-10 16:29:25 +00:00
self.variable_manager = VariableManager(
loader=self.loader, inventory=self.inventory
)
2017-03-06 15:34:54 +00:00
def get_result_callback(self, execution_id=None):
return self.__class__.results_callback_class(display=AdHocDisplay(execution_id))
2018-03-30 14:03:43 +00:00
2017-03-06 15:34:54 +00:00
@staticmethod
def check_module_args(module_name, module_args=''):
if module_name in C.MODULE_REQUIRE_ARGS and not module_args:
err = "No argument passed to '%s' module." % module_name
2017-12-06 10:31:51 +00:00
raise AnsibleError(err)
def check_pattern(self, pattern):
2017-12-10 16:29:25 +00:00
if not pattern:
raise AnsibleError("Pattern `{}` is not valid!".format(pattern))
2017-12-06 10:31:51 +00:00
if not self.inventory.list_hosts("all"):
raise AnsibleError("Inventory is empty.")
if not self.inventory.list_hosts(pattern):
raise AnsibleError(
"pattern: %s dose not match any hosts." % pattern
)
2017-03-06 15:34:54 +00:00
2018-12-10 11:51:35 +00:00
def clean_args(self, module, args):
if not args:
return ''
2018-12-10 11:51:35 +00:00
if module not in self.command_modules_choices:
return args
if isinstance(args, str):
if args.startswith('executable='):
_args = args.split(' ')
executable, command = _args[0].split('=')[1], ' '.join(_args[1:])
args = {'executable': executable, '_raw_params': command}
else:
args = {'_raw_params': args}
return args
else:
return args
2017-12-10 16:29:25 +00:00
def clean_tasks(self, tasks):
cleaned_tasks = []
for task in tasks:
2018-12-10 11:51:35 +00:00
module = task['action']['module']
args = task['action'].get('args')
cleaned_args = self.clean_args(module, args)
task['action']['args'] = cleaned_args
self.check_module_args(module, cleaned_args)
2017-12-10 16:29:25 +00:00
cleaned_tasks.append(task)
return cleaned_tasks
2018-03-30 14:03:43 +00:00
def update_options(self, options):
_options = {k: v for k, v in self.default_options.items()}
2018-03-30 14:03:43 +00:00
if options and isinstance(options, dict):
_options.update(options)
return _options
2017-12-07 05:01:33 +00:00
def set_control_master_if_need(self, cleaned_tasks):
modules = [task.get('action', {}).get('module') for task in cleaned_tasks]
if {'ping', 'win_ping'} & set(modules):
self.results_callback.context = {
'ssh_args': '-C -o ControlMaster=no'
}
def run(self, tasks, pattern, play_name='Ansible Ad-hoc', gather_facts='no', execution_id=None):
2017-03-06 15:34:54 +00:00
"""
2017-12-06 10:31:51 +00:00
:param tasks: [{'action': {'module': 'shell', 'args': 'ls'}, ...}, ]
:param pattern: all, *, or others
:param play_name: The play name
2018-03-30 14:03:43 +00:00
:param gather_facts:
2017-03-06 15:34:54 +00:00
:return:
"""
2017-12-10 16:29:25 +00:00
self.check_pattern(pattern)
self.results_callback = self.get_result_callback(execution_id)
2017-12-10 16:29:25 +00:00
cleaned_tasks = self.clean_tasks(tasks)
self.set_control_master_if_need(cleaned_tasks)
context.CLIARGS = ImmutableDict(self.options)
2017-12-06 10:31:51 +00:00
play_source = dict(
name=play_name,
2017-03-06 15:34:54 +00:00
hosts=pattern,
2017-12-06 10:31:51 +00:00
gather_facts=gather_facts,
2017-12-10 16:29:25 +00:00
tasks=cleaned_tasks
2017-03-05 15:30:14 +00:00
)
2017-12-06 10:31:51 +00:00
play = Play().load(
play_source,
2017-03-05 15:30:14 +00:00
variable_manager=self.variable_manager,
loader=self.loader,
)
loader = DataLoader()
# used in start callback
playbook = Playbook(loader)
playbook._entries.append(play)
playbook._file_name = '__adhoc_playbook__'
2017-03-05 15:30:14 +00:00
2017-12-06 10:31:51 +00:00
tqm = TaskQueueManager(
2017-03-05 15:30:14 +00:00
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
2018-03-30 14:03:43 +00:00
stdout_callback=self.results_callback,
passwords={"conn_pass": self.options.get("password", "")}
2017-03-05 15:30:14 +00:00
)
try:
tqm.send_callback('v2_playbook_on_start', playbook)
2017-12-06 10:31:51 +00:00
tqm.run(play)
tqm.send_callback('v2_playbook_on_stats', tqm._stats)
2018-03-30 14:03:43 +00:00
return self.results_callback
2017-03-05 15:30:14 +00:00
except Exception as e:
2017-12-06 10:31:51 +00:00
raise AnsibleError(e)
2017-03-05 15:30:14 +00:00
finally:
if tqm is not None:
tqm.cleanup()
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
2017-03-05 15:30:14 +00:00
self.results_callback.close()
2017-03-05 15:30:14 +00:00
2017-12-06 10:31:51 +00:00
class CommandRunner(AdHocRunner):
results_callback_class = CommandResultCallback
2019-12-21 11:44:25 +00:00
modules_choices = ('shell', 'raw', 'command', 'script', 'win_shell')
2017-12-06 10:31:51 +00:00
2021-07-08 06:36:18 +00:00
def execute(self, cmd, pattern, module='shell'):
2017-12-06 10:31:51 +00:00
if module and module not in self.modules_choices:
raise AnsibleError("Module should in {}".format(self.modules_choices))
tasks = [
{"action": {"module": module, "args": cmd}}
]
return self.run(tasks, pattern, play_name=cmd)
2017-03-05 15:30:14 +00:00