Playbook文件详解
1、基本概念
- Play:play是针对清单中选定的主机运行的一组有序任务。playbook是一个文本文件,其中包含由一个或多个按特定顺序运行的play组成的列表。
Playbook:playbook是以YAML格式编写的文本文件,通常使用扩展名yml保存。Playbook使用空格字符缩进来表示结构。
- 处于层次结构中的一级别的数据元素必须具有相同的缩进量。
- 如果项目属于其他项目的子项,其缩进量必须大于父项。
- 使用空格字符进行缩进,不用Tab。如下方式可以用Tab缩进。
autocmd FileType yaml setlocal ai ts=2 sw=2 et
2、Playbook示例解析
# 开始字符,可以省略
- name: just an example
hosts: web
tasks:
- name: web server is enabled
service:
name: httpd
enabled: true
- name: vsftpd is enabled
service:
name: vsftpd
enabled: true
# 结束字符,可以省略
- name:第一个name是对剧本的描述,hosts是要对哪些机器进行任务的操作,tasks后面所跟的就是实际的执行操作。
- playbook会按照任务文件中的顺序进行执行。
- tasks后面的name是对任务的描述,可以不写,我们建议要写。
- service是该剧本中用到的模块。
- service后面的name和enabled是该模块的子项、参数。
3、YAML注释
注释可以用于提高可读性。在YAML中,井号或井号符号(#)右侧的所有内容都是注释。如果注释在数据的左侧内容,请在该编号符号的前面加一个空格。
# This is a YAML comment
some data # This is also a YAML comment
4、YAML字符串
YAML中的字符串通常不需要放在引号里,即使字符串中包含空格。字符串可以用双引号或单引号括起。
this is a string
'this is another string'
"this is yet another string"
编写多行字符串有两种方式。可以使用竖线(|)符号表示要保留字符串中的换行符。
include_newlines: |
Example Company
123 Main Street
Atlanta, GA 30303
要编写多行字符串,您也可以使用大于号(>)字符来表示换行符转换成空格并且行内的引导空白将被删除。这种方法通常用于将很长的字符串在空格字符处断行,使它们跨多行来提高可读性。
fold_newlines: >
This is an example
of a long string,
that will become
a single sentence once folded.
5、YAML字典
以缩进块的形式编写的键值对集合,如下所示:
name: svcrole
svcservice: httpd
svcport: 80
字典也可以使用包括号括起的内联格式编写,如下所示:
{name: svcrole, svcservice: httpd, svcport: 80}
6、YAML列表
普通单破折号语法编写的列表:
hosts:
- servera
- serverb
- serverc
列表也有以方括号括起的内联格式,如下所示:
hosts: [servera, serverb, serverc]
您应该避免使用此语法,因为它通常更难阅读。
例子1:安装和启动Apache服务
- name: Install and start Apache service
hosts: webservers
tasks:
- name: Install httpd package
yum:
name: httpd
state: present
- name: Start httpd service
service:
name: httpd
state: started
enabled: true
例子2:安装和启动MySQL服务
- name: Install and start MySQL service
hosts: databases
tasks:
- name: Install MySQL server
yum:
name: mysql-server
state: present
- name: Start MySQL service
service:
name: mysqld
state: started
enabled: true
本文由mdnice多平台发布
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。