ansible安全控制

Posted 我的紫霞辣辣

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ansible安全控制相关的知识,希望对你有一定的参考价值。

ansible对模块和命令做限制

vim /usr/local/python3/lib/python3.8/site-packages/ansible/playbook/play.py
...
from ansible.parsing.splitter import parse_kv
# 写在类的上面,否则调用不到(一定要写在全局)
def filter_cmd(data):
    filter_modules = ('command', 'shell', 'script', 'raw')
    filter_commands = ('rm -rf /','halt', 'poweroff', 'reboot', 'shutdown -h now','shutdown -r now','hostname')
    filter_commands = map(lambda x:x.replace(' ', '').lower(), filter_commands)
    for t in data['tasks']:
        if 'action' in t:
            if t['action']['module'] in filter_modules:
                if t['action']['args']['_raw_params'].replace(' ', '').lower() in filter_commands:
                    raise AnsibleParserError("Refused to execute the [%s] command in the [%s] module." % (t['action']['args']['_raw_params'], t['action']['module']))
    else:
        for m in filter_modules:
            if m in t:
                args=parse_kv(t[m], check_raw=True)
                if args['_raw_params'].replace(' ', '').lower() in filter_commands:
                    raise AnsibleParserError("Refused to execute the [%s] command in the [%s] module." % (t[m], m))

...
	# 在Play类的load方法中引用filter_cmd过滤命令
	# 在p = Play()上方添加filter_cmd(data)
    @staticmethod
    def load(data, variable_manager=None, loader=None, vars=None):
        if ('name' not in data or data['name'] is None) and 'hosts' in data:
            if data['hosts'] is None or all(host is None for host in data['hosts']):
                raise AnsibleParserError("Hosts list cannot be empty - please check your playbook")
            if isinstance(data['hosts'], list):
                data['name'] = ','.join(data['hosts'])
            else:
                data['name'] = data['hosts']
        filter_cmd(data)
        p = Play()
        if vars:
            p.vars = vars.copy()
        return p.load_data(data, variable_manager=variable_manager, loader=loader)

测试

ansible all -m shell -a "hostname"
# ERROR! Refused to execute the [hostname] command in the [shell] module.
ansible all -m shell -a "reboot"
# ERROR! Refused to execute the [reboot] command in the [shell] module.
ansible all -m shell -a "rm -rf /"
# ERROR! Refused to execute the [rm -rf /] command in the [shell] module.

以上是关于ansible安全控制的主要内容,如果未能解决你的问题,请参考以下文章

Ansible自动化工具的实践

ansible plugins简介

源代码控制中的 Ansible SSH 私钥?

在ansible模板中使用动态组名称

Ansible自动化运维安装

Ansible 安全 之加密主机清单