Playbook introduction
Playbook is a mode different from using Ansible command line execution mode, and its functions are more powerful and flexible. Simply put, a playbook is a very simple configuration management and multi-host deployment system, which is different from any existing model and can be used as a basis for deploying complex applications. Playbook can be customized and configured, can be executed in an orderly manner according to the specified operation steps, and supports synchronous and asynchronous modes. It is worth noting that the playbook is described and defined in the YAML format.
1. The host names of the current two servers:
192.168.20.40
[root@docker02 ~]# hostname
docker02
192.168.20.39
[root@slavedb tmp]# hostname
slavedb
2. Ansible configuration
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 configuration
[root@docker02 ~]# more host.yml
---
- hosts: web
tasks:
- name: hostname
shell: hostnamectl set-hostname {{ inventory_hostname }}
when: ansible_distribution_major_version == "7"
4. Execute the playbook
[root@docker02 ~]# ansible-playbook host.yml
[root@docker02 ~]# hostname
k8s-master
[root@slavedb tmp]# hostname
k8s-node3
5. Write the host name to /etc/hosts
Server: 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
Server: 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. Execute the 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. Check the 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
Related Reading:
1. Write Playbook to deploy Etcd cluster
2. Deploy Docker in batches on Playbook
3. Playbook distributes Nginx configuration files