Ansible基于playbook批量修改主机名
这里的主机名是修改过之后的,IP 分别对应的主机名,具体操作如下
192.168.1.202 spider-01
192.168.1.201 spider-02
1、修改/etc/ansible/hosts文件
添加另外两台的IP+要完成修改的主机名+端口号+用户名+登录密码
[root@web ansible-playbook]# cat >> /etc/ansible/hosts << \EOF
[test]
192.168.1.202 hostname=spider-01 ansible_ssh_port=2968 ansible_ssh_user=root ansible_ssh_pass=1q2w3e4r
192.168.1.201 hostname=spider-02 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=1q2w3e4rEOF
2、编写playbook剧本
[root@web ansible-playbook]# vim /etc/ansible/ansible-playbook/modify_hostname.yml
- hosts: test
remote_user: root
tasks:
- name: change name
raw: "echo {{hostname|quote}} > /etc/hostname"
- name:
shell: hostname {{hostname|quote}}
3、检查语法及执行
[root@web ansible-playbook]# ansible-playbook --syntax-check modify_hostname.yml
[root@web ansible-playbook]# ansible-playbook -C modify_hostname.yml //预执行
[root@web ansible-playbook]# ansible-playbook modify_hostname.yml //真正执行
PLAY [test] **********************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************
ok: [192.168.1.202]
ok: [192.168.1.201]
TASK [change name] ***************************************************************************************************
changed: [192.168.1.202]
changed: [192.168.1.201]
TASK [shell] *********************************************************************************************************
changed: [192.168.1.202]
changed: [192.168.1.201]
PLAY RECAP ***********************************************************************************************************
192.168.1.201 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
192.168.1.202 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
4、查看是否已经修改成功
[root@web ansible-playbook]# ansible test -m shell -a "hostname"
192.168.1.202 | CHANGED | rc=0 >>
spider-01
192.168.1.201 | CHANGED | rc=0 >>
spider-02
Comments | NOTHING