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"
相关推荐
伤不起bb1 小时前
MySQL 高可用
linux·运维·数据库·mysql·安全·高可用
IT成长日记2 小时前
【Ansible基础】Ansible设计理念与无代理架构深度解析
架构·自动化·ansible·无代理
whgjjim3 小时前
docker迅雷自定义端口号、登录用户名密码
运维·docker·容器
tmacfrank4 小时前
网络编程中的直接内存与零拷贝
java·linux·网络
瀚高PG实验室6 小时前
连接指定数据库时提示not currently accepting connections
运维·数据库
QQ2740287566 小时前
Soundness Gitpod 部署教程
linux·运维·服务器·前端·chrome·web3
淡忘_cx6 小时前
【frp XTCP 穿透配置教程
运维
qwfys2006 小时前
How to configure Linux mint desktop
linux·desktop·configure·mint
南方以南_7 小时前
Ubuntu操作合集
linux·运维·ubuntu
冼紫菜7 小时前
[特殊字符]CentOS 7.6 安装 JDK 11(适配国内服务器环境)
java·linux·服务器·后端·centos