ansible基础使用--实战记录

**场景:**在局域网或者允许公网访问的集群、数量较多的主机,便捷部署各种环境、监控等。

此篇文章暂不涉及使用ansible-playbook,有时间再记录yaml文件的基本使用。

bash 复制代码
# centos安装:
yum install ansible -y

# ubunt安装:
apt -y install ansible

安装后配置文件路径:/etc/ansible/

/etc/ansible/host配置例子# 说明:

bash 复制代码
[minio]   # 自定义的组名
192.168.106.100    # 组内成员ip
192.168.106.101
192.168.106.102
192.168.106.103

[minio:vars]    # 指定组的参数
ansible_ssh_user=minio    # 相同的账号密码
ansible_ssh_pass=AAA123    # 相同的密码认证
ansible_python_interpreter=/usr/bin/python3    # 在提示未找到python的情况下指定python路径

[test]
192.168.1.1 ansible_ssh_user=root ansible_ssh_pass=111    # 指定的账号密码
192.168.1.2 ansible_ssh_user=root ansible_ssh_pass=222    # 指定的账号密码
192.168.1.3 ansible_ssh_user=root ansible_ssh_pass=333    # 指定的账号密码

⚠️可能报错一:被控方python环境找不到

**解决方案:**需要配置ansible_python_interpreter指定python路径,或者配置被控方的python系统环境

bash 复制代码
# 具体报错信息
"changed": false,
"module_stderr": "Shared connection to 192.168.106.100 closed.\r\n",
"module_stdout": "/bin/sh: 1: /usr/bin/python: not found\r\n",
"msg": "MODULE FAILURE",
"rc": 127

⚠️可能报错二:通过密码认证时提示需要安装sshpass

bash 复制代码
# 报错提示
you must install the sshpass program

**解决方案:**安装sshpass

bash 复制代码
centos:yum -y install sshpass

ubuntu:apt -y install sshpass

首次使用登录建议配置,二选一即可:

**第一种:**本地先SSH登录一下被控设备,下次ansible 就可以正常操作了,设备数量多就比较麻烦

**第二种:**设置参数为不检查key

bash 复制代码
vim /etc/ansible/ansible.cfg
在文件中进行搜索定位到 :/host_key_checking 
修改前:
#uncomment this to disable SSH key host checking 
#host_key_checking = False 
修改后: 
#uncomment this to disable SSH key host checking 
host_key_checking = False

常用模块命令:

bash 复制代码
# 确认与主机连通性
ansible all -m ping
ansible minio -m ping
# 查看分组内主机
ansible minio --list-hosts
# shell模块,个人使用最多的模块
ansible minio -m shell -a 'echo $HOSTNAME'
# 远程执行本地脚本
ansible all -m script -a "/home/test.sh"
# 复制本地文件到远端,同时可指定覆盖备份、权限、属主
ansible all -m copy -a 'src=2024-05-22.txt dest=/home/2024-05-22.txt backup=true'
#生成内容到远端
ansible all -m copy -a 'content=YouAreTheAppleOfMyEye\ne dest=/home/Good.txt'
# 管理服务、打开服务、并设置开机启动
# name (必须):指定要管理的服务名称
# enabled (可选):控制服务是否开机启动(自动启动)yes或true | no或false
# state (可选):控制服务的状态:started:启动服务 | stopped:停止服务 | restarted:重新启动服务 | reloaded:重新加载服务
ansible test -m service -a 'name=httpd enabled=true state=started'
#重启httpd服务,stop与start之间间隔3秒
ansible test -m service -a "name=httpd state=restarted sleep=3"
#重启网卡
ansible test -m service -a "name=network state=restarted args=ens33"
相关推荐
苏宸啊25 分钟前
linux网络编程udp服务器和客户端代码编写(echo版本和字典版本)
linux·网络
~|Bernard|40 分钟前
Linux 定时任务(Cron)完整教程
linux·运维·服务器
小周学学学1 小时前
vmware-horizon第一章:horizon服务器安装
运维·服务器·vmware
小雪崩1 小时前
嵌入式学习 day25:哈希表及排序与查找
linux·c语言·数据结构·学习·排序算法
gsls2008082 小时前
Penpot Docker 部署与 MCP 服务配置文档
运维·docker·容器·原型·penpot
九硕智慧建筑一体化厂家2 小时前
直流智能照明|全场景节能升级!打造安全低碳的智慧建筑光环境
运维·笔记·安全·智慧城市
蓝速科技2 小时前
蓝速科技丨数智人终端选型指南:后台运维如何决定长期运营成本
运维·科技
奇树谦2 小时前
HDD 为什么适合顺序大文件读写:从 RAID 5 到 RAID 50 的原理与性能分析
linux·运维·网络
hi_ro_a3 小时前
Linux基础开发工具详解
linux·运维·服务器
嵌入式阿蔡3 小时前
Linux_01:交叉编译与开发环境实战——从单片机跨到 Linux 的第一道坎
linux·运维·网络·单片机·嵌入式硬件·嵌入式实时数据库