工作中需要每三个月对服务器密码进行一次变更,通过shell脚本部署比较繁琐,所以决定采用Ansible脚本对远程主机root密码进行批量重置
配置Ansible到远程主机的ssh无密码登录的信任关系:请点击左下角往期的干货--Ansible
方法一:简单直接的方法
1、测试分发到服务器是否正常
[root@server ~]# ansible webservers -m shell -a "whoami"
192.168.210.177 | CHANGED | rc=0 >>
root
192.168.210.176 | CHANGED | rc=0 >>
2、编写yaml文件
[root@server ~]# more /opt/root_passwd.yaml(注意空格哦!)
---
- hosts: webservers
gather_facts: false
tasks:
- name: change user passwd
user: name={{ item.name }} password={{ item.chpass | password_hash('sha512') }} update_password=always
with_items:
- { name: 'root', chpass: '123' }
3、测试yaml文件正确性
[root@server ~]# ansible-playbook -C /opt/root_passwd.yaml
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yYidjM4EzNlljZ1MWMklDZ2Y2NkVWYzcDM3ADNhFTZ28CXyEzLcNDMxIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLzM3Lc9CX6MHc0RHaiojIsJye.png)
4、执行[root@server ~]# ansible-playbook /opt/root_passwd.yaml
5、执行ansible-playbook,使用-e参数传递用户名和密码给剧本,其中root为用户名,密码123
[root@server ~]# ansible-playbook /opt/root_passwd.yaml -e "name=root chpass=123"
[WARNING]: Found variable using reserved name: name
PLAY [webservers]
**************************************************************
TASK [change user passwd]
changed: [192.168.210.176] => (item={u'chpass': u'123', u'name': u'root'})
changed: [192.168.210.177] => (item={u'chpass': u'123', u'name': u'root'})
PLAY RECAP
***************************************************************
192.168.210.176 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.210.177 : ok=1 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
方法二:简单直接的方法
如果Ansible服务端没有和远程主机做ssh信任关系, 则可以在hosts清单配置里直接指明用户名和密码
[root@mgr01-3 ~]# more /etc/ansible/hosts |grep 192
192.168.210.85
192.168.210.177
[root@web ~]# vim /etc/ansible/hosts
192.168.210.85 ansible_ssh_user=root ansible_ssh_pass=123 ansible_ssh_port=22
192.168.210.177 ansible_ssh_user=root ansible_ssh_pass=123 ansible_ssh_port=22
[root@web~]# ansible web -m shell -a "ifconfig|grep ens33"
192.168.210.85 | CHANGED | rc=0 >>
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
********** 当你发现自己的才华撑不起野心时,就请安静下来学习吧!************
↓↓ 点击"阅读原文" 【加入DevOps运维团】
相关阅读:
请阅读往期干货-ansible
1、干货--ansible配置和服务器批量分发(一)
2、干货--ansible配置和服务器批量分发(二)