ansible基础使用--实战记录

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

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

# centos安装:
yum install ansible -y

# ubunt安装:
apt -y install ansible

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

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

[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系统环境

# 具体报错信息
"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

# 报错提示
you must install the sshpass program

解决方案:安装sshpass

centos:yum -y install sshpass

ubuntu:apt -y install sshpass

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

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

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

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

常用模块命令:

# 确认与主机连通性
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"

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值