实战--Playbook批量更改服务器主机名
作者:互联网
Playbook 介绍
Playbook是 一个不同于使用Ansible命令行执行方式的模式,其功能更强大灵活。简单来说,playbook是一个非常简单的配置管理和多主机部署系统,不同于任何已经存在的模式,可作为一个适合部署复杂应用程序的基础。Playbook可以定制配置,可以按照指定的操作步骤有序执行,支持同步和异步方式。值得注意的是playbook是通过YAML格式来进行描述定义的。
1、目前两台服务器的主机名:
192.168.20.40
[root@docker02 ~]# hostname
docker02
192.168.20.39
[root@slavedb tmp]# hostname
slavedb
2、Ansible配置
root@docker02 ~]# vim /etc/ansible/hosts
[web]
k8s-master ansible_ssh_host=192.168.20.40
k8s-node3 ansible_ssh_host=192.168.20.39
3、Playbook配置
[root@docker02 ~]# more host.yml
---
- hosts: web
tasks:
- name: hostname
shell: hostnamectl set-hostname {{ inventory_hostname }}
when: ansible_distribution_major_version == "7"
4、执行playbook
[root@docker02 ~]# ansible-playbook host.yml
[root@docker02 ~]# hostname
k8s-master
[root@slavedb tmp]# hostname
k8s-node3
5、主机名写入/etc/hosts
服务器:192.168.20.40
[root@docker02 ~]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.20.40 docker02
192.168.20.39 slavedb
服务器:192.168.20.39
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.20.40 docker02
192.168.20.39 slavedb
6、执行playbook
[root@docker02 ~]# more host.yml
---
- hosts: web
tasks:
- name: hostname
shell: hostnamectl set-hostname {{ inventory_hostname }}
when: ansible_distribution_major_version == "7"
- name: modify etc hosts
shell: echo "{{ ansible_ens33['ipv4']['address'] }} {{ inventory_hostname }}" >>/etc/hosts
register: result
- debug: var=result
[root@docker02 ~]# ansible-playbook host.yml
7、检查hosts
[root@docker02 ~]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.20.40 docker02
192.168.20.39 slavedb
192.168.20.40 k8s-master
[root@slavedb tmp]# cat /etc/hosts |egrep -v "^$|^#" /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.20.40 docker02
192.168.20.39 slavedb
192.168.20.39 k8s-node3
相关阅读:
标签:--,主机名,etc,hosts,Playbook,docker02,root,localhost 来源: https://blog.51cto.com/15127516/2657652