Ansible

文章介绍了如何基于SSH协议使用Ansible进行无代理管理,包括安装步骤、配置主机列表,以及遇到的`ImportError:Nomodulenamedcontext`问题的解决方法。重点在于Ansible的安全强化,通过代码修改禁止执行特定的危险操作,防止误操作导致的系统风险。

一、核心思想

        基于SSH协议直接进行管理。因此不需要在客户端安装什么软件工具之类的。

        基于SSH连接成功后,ansible会发送一个python脚本文件到目标主机去执行需要的操作。

二、安装

# yum install epel-release
# yum install ansible

三、配置

 默认配置文件为/etc/ansible/hosts

[root@Test ~]# cat /etc/ansible/hosts
[test]
172.1.0.1 ansible_ssh_user=root ansible_ssh_pass=登录密码 
172.1.0.2 ansible_ssh_user=root ansible_ssh_pass=登录密码
172.1.0.3 ansible_ssh_user=root ansible_ssh_pass=登录密码
172.1.0.4 ansible_ssh_user=root ansible_ssh_pass=登录密码
172.1.0.5 ansible_ssh_user=root ansible_ssh_pass=登录密码

关于/etc/ansible/hosts相关配置参数: 

四、常见模块

五、相关问题

【现象】使用yum安装好ansible之后,执行ansible后提示“ImportError: No module named context”。

【原因】使用pip和yum安装过ansible之后,可能会导致模块之间的关系搞混。

【解决方法】

到/usr/lib/python2.7/site-packages/这里边删掉有关ansible的模块之后,重装,就正常了。

六、Ansible禁止危险操作

6.1 变更内容(/usr/lib/python2.7/site-packages/ansible/playbook/play.py)

第1行,新增了如下内容:

# -*- coding: utf-8 -*-

第21行,新增了如下内容:

# ----------------------------------------------------------------------------------------------------------------------------------------------- #
from ansible.parsing.splitter import parse_kv           # Added by BiQing in 20231015 to forbidden sb. to do some Dangerous Operations.
# ----------------------------------------------------------------------------------------------------------------------------------------------- #

第114行,新增了如下内容:

# ----------------------------------------------------------------------------------------------------------------------------------------------- #
# Added by BiQing in 20231015 to forbidden sb. to do some Dangerous Operations. _v3: 输入命令中含有禁止的操作都会触发禁止动作,以及增强可读性
# ----------------------------------------------------------------------------------------------------------------------------------------------- #
        filter_modules = ('command', 'shell', 'script', 'raw')
        filter_commands = ('rm -rf /', 'rm -rf /opt', 'halt', 'poweroff', 'reboot', 'shutdown -h now', 'shutdown -r now')     # 禁止的操作
        filter_commands_origin = filter_commands     # 禁止的操作
        filter_commands = map(lambda x:x.replace(' ', '').lower(), filter_commands)     # 将上述定义的filter_commands进行一次数据操作:将命令转换为不含空格的全小写字符串
        for t in Play.new_method(data):
            if 'action' in t:
                if t['action']['module'] in filter_modules:
                        #if t['action']['args']['_raw_params'].replace(' ', '').lower() in filter_commands:   # S1:命令是否为禁止的操作
                    for i in filter_commands:    # S2:命令中是否包含被禁止的操作
                        if i in t['action']['args']['_raw_params'].replace(' ', '').lower():   # 判断命令中是否包含被禁止的操作
                            data = t['action']['args']['_raw_params'].lower() 
                            data = str(data).replace("'",'"').replace(": ",":").replace("{u","{").replace(":u",":").strip()
                            print("禁止进行以下命令:")
                            print("   \033[0;37;42m",filter_commands_origin,"\033[0m")
                            print("Ation:\n  ","\033[0;37;42m",data,"\033[0m","\n")
                            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))

 6.2 测试

09-17
### 关于 Ansible 的下载安装与使用教程 #### 一、Ansible 基础概念 Ansible 是一种简单而强大的 IT 自动化工具,用于配置管理、应用程序部署以及任务编排。它的设计原则是基于无代理架构(Agentless),即不需要在被控节点上安装任何软件。 - **Inventory 文件**: 这是一个包含受控服务器信息的文件,默认路径位于 `/etc/ansible/hosts`[^1]。该文件定义了主机列表及其分组方式。 #### 二、Ansible 的安装方法 以下是 AnsibleLinux 和 macOS 上的标准安装步骤: 对于 Ubuntu 系统: ```bash sudo apt update sudo apt install software-properties-common sudo add-apt-repository --yes --update ppa:ansible/ansible sudo apt install ansible ``` 对于 CentOS/RHEL 系统: ```bash sudo yum install epel-release sudo yum install ansible ``` macOS 用户可以借助 Homebrew 工具完成安装: ```bash brew install ansible ``` 验证安装成功与否可以通过以下命令检查版本号: ```bash ansible --version ``` #### 三、Ansible 的基本用法 ##### 1. 执行 Ad-Hoc 命令 Ad-Hoc 模式允许用户快速向远程主机发送单条指令并获取反馈。例如,查看目标主机上的 `~` 目录结构时可执行如下命令[^2]: ```bash ansible webserver -i ~/.ansible/hosts -m command -a 'ls ~' -k ``` 其中 `-k` 参数表示提示输入 SSH 密码而非依赖密钥认证。 ##### 2. 配置 Inventory 文件 默认情况下,Ansible 使用 `/etc/ansible/hosts` 作为 inventory 文件位置。如果需要指定自定义路径,则可通过 `-i` 参数实现。例如: ```ini [webserver] 192.168.1.10 ansible_user=root ``` ##### 3. Playbooks 编写入门 Playbook 是一组 YAML 格式的剧本脚本,用来描述一系列复杂操作序列。下面是一份最简化的 playbook 示例[^4]: ```yaml --- - name: Update all servers and reboot them hosts: webservers become: yes tasks: - name: Ensure system is up to date package: name: "*" state: latest - name: Reboot server after updates are installed reboot: ``` #### 四、跨平台支持——Windows 环境下的 Ansible 应用 尽管传统意义上 Ansible 更倾向于 Unix/Linux 平台的操作,但它同样具备良好的 Windows 支持能力。这主要得益于由社区开发者 jborean93 维护的一套专门针对 Microsoft 技术栈优化过的插件集合[^3]。这些组件让运维人员得以利用 PowerShell 脚本或者 WinRM 协议无缝衔接至企业内部混合云场景之中。 #### 五、容器集成解决方案-Ansible Bender 随着 DevOps 文化日益普及,越来越多的企业开始关注 CI/CD 流程中的镜像构建环节。为此官方推荐了一款名为 "Ansible Bender" 的第三方扩展程序[^5]。它允许使用者仅需编写一份声明性的 YAML 描述文档就能全自动完成 Dockerfile 替代工作流的设计思路。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值