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"
相关推荐
哲伦贼稳妥30 分钟前
一天认识一个硬件之电源
运维·其他·电脑·硬件工程
暗恋 懒羊羊35 分钟前
Linux 生产者消费者模型
linux·开发语言·ubuntu
安红豆.1 小时前
Linux基础入门 --13 DAY(SHELL脚本编程基础)
linux·运维·操作系统
..空空的人1 小时前
linux基础指令的认识
linux·运维·服务器
penny_tcf1 小时前
Linux基础命令halt详解
linux·运维·服务器
万界星空科技2 小时前
界星空科技漆包线行业称重系统
运维·经验分享·科技·5g·能源·制造·业界资讯
荣世蓥2 小时前
10.2 Linux_进程_进程相关函数
linux·运维·服务器
gma9993 小时前
【MySQL】服务器管理与配置
运维·服务器
henan程序媛3 小时前
Jenkins Pipline流水线
运维·pipeline·jenkins
安全不再安全4 小时前
Linux 安装 yum
linux·运维·centos