Introduction to Ansible-playbook (theory + example)

What is a playbook

  • The playbook is ansible used to configure, deploy and manage the managed host script. Through the detailed description of the playbook, execute a series of tasks in it, so that the remote host can reach the expected state.

  • It can also be said that playbook literally means a script.In reality, actors perform according to the script. In ansible, the computer installs, deploys applications, provides external services, and organizes computers to handle various things.

Why use a playbook
  • To perform some simple tasks, using the ad-hoc command can easily solve the problem, but sometimes when a facility is too complicated, it is not appropriate to execute the ad-hoc command. It is best to use a playbook
  • The playbook can use the written code repeatedly, and it can be placed on different machines, like a function, to maximize the use of the code. In the process of using ansible, most of the operations processed are written in the playbook.

Grammar basis of playbook

Playbook syntax format
- playbook由YAML语言编写,遵循YAML标准
- 在同一行中,#之后的内容表示注释
- 同一个列表中的元素应该保持相同的缩进
- playbook由一个或多个play组成
- play中hosts,variables,roles.tasks等对象的表示方法都是键值中间的" : " 分隔表示
- YAML还有一个小的怪癖,它的文件开始行都应该是 ---, 这是YAML格式的一部分,表明一个文件的开始
playbook composition
- hosts:定义将要执行playbook的远程主机组
- vars:定义playbook运行时需要使用的变量
- tasks:定义将要在远程主机上执行的任务列表
- handlers:定义task执行完成以后需要调用的任务
Playbook execution result
  • Use ansible-playbook to run the playbook file, the output content is in JSON format, which is composed of different colors for easy identification
    -green represents successful execution
    -*** represents the system on behalf of the system state has changed
    -red represents execution failure
  • The first playbook
---
- name: test ping
  hosts: all
  tasks: 
    - name: 1 ping
      ping:

]# ansible-playbook myping.yml -f 5
--f The number of concurrent processes, the default is 5
-The content of the hosts line is the patterns of one (multiple) groups or hosts, with a comma as the separator

  • tasks
    -a collection of commands
    -each play contains a task list (task list)
    -after a task is executed on all its corresponding hosts (matching all hosts by host pattern), the next task will be executed.
  • hosts
    -a collection of hosts -
    define hosts to perform tasks

Playbook execution command (example 1)

-Add user x1 to the web host
-Set the default password 123, and add the x1 user to the users group

---
- hosts: web
  tasks:
    - name: create user x1
      user:
        name: x1
        group: users
    - name: set password
      shell: echo 123 | passwd --stdin x1

Guess you like

Origin blog.csdn.net/weixin_45942735/article/details/104288641