Ansible之playbook语法

Ansible playbook语法

一、playbook中的yml文件语法

  1. 第一行以3个减号开头,作为文档开始的标记,末尾可能使用3个圆点作为文档结束标记(一般都省略)
---
  1. 使用空格来缩进,处于同一级别的缩进空格数量相等,子项目缩进量大于父项,对缩进几个没有要求,一般2个即可

  2. yml列表中的项目以一个破折号加空格开头

- list1
- list2
- list3

list1,list2,list3代表3个不同的项目,而每个项目下可以定义具体的任务。

  1. play本身是一个键值对集合,同一play中的键应该使用相同的缩进量

  2. 一个键可以有多个值对应,以1个减号加空格以列表形式存在

tasks: 
  - first
  - second
  - third

二、playbook示例

  1. 单个play单个任务

    为定义好的远程web主机或主机组安装Apache httpd

---
- name: Install and start Apache HTTPD
  hosts: web
  tasks: 
    - name: httpd package is present
      yum: 
        name: httpd
        state: present

解释说明

  • 第一行:3个减号,表明文档开始
  • 第二行:- name:空格Install and start Apache HTTPD 表明这是一个play列表中第一项,name是键,后面的字符串是值。这行的作用是标识了该play的用途,当执行访play的时候会在终端有提示,此行可以省略,但是建议使用。
  • 第三行:此行开始有缩进直到结尾,表明此行开始到结束都是第一个play列表的子项目。hosts用来指定要操作的远程主机。
  • 第四行:指明要在此远程主机或主机组要执行的任务,可以是单个任务,也可以是多个任务
  • 第五行:缩进2个空格(以tasks为参考)表明这是tasks列表中的第1项要执行的任务,name属性表明要执行任务的说明,同第二行。
  • 第六行:相对第5行缩进2个空格,表明是第1个任务列表下的子项目,使用Ansible中的yum模块。
  • 第七行:相对yum缩进2个空格,此时name属性是yum模块中字段,表明要安装的软件包的名称。
  • 第八行:和第七行name对齐,state也是yum模块中的字段,表明安装状态、
  1. 单个play多个任务

    为定义好的远程web主机或主机组安装Apache httpd同时启动httpd服务并加入开机启动

---
- name: Install and start Apache HTTPD
  hosts: web
  tasks: 
   - name: httpd package is present
     yum: 
       name: httpd
       state: present
   - name: httpd is enabled and running
     service:
       name: httpd
       enabled: true
       state: started

这里tasks下以2个任务列表,注意缩进关系和对齐。

  1. 多个play多个任务
---
- name: Install and start Apache HTTPD
  hosts: web
  tasks: 
   - name: httpd package is present
     yum: 
       name: httpd
       state: present
   - name: httpd is enabled and running
     service:
       name: httpd
       enabled: true
       state: started
- name: Install and start mariadb-server
  hosts: database
  tasks: 
   - name: mariadb-server is present
     yum: 
       name: mariadb-server
       state: latest
   - name: mariadb enabled and running
     service: 
       name: mariadb
       enabled: true
       state: started

三、总结

yaml文件有严格的语法要求,一定要用空格来缩进,打死不能按tab键,还有一点一般冒号后面和减号后面要有一个空格。一定要注意缩进与对齐,子项相对父项要有缩进,平级关系保持机同缩进。

posted @ 2021-08-19 13:44  mfyang  阅读(670)  评论(0编辑  收藏  举报