3-1 基于Roles的Playbook
最后更新于:2022-04-02 07:37:58
#### 目录框架
```
inventory/ # Server清单
testenv
productenv
roles/ # 任务列表
testbox/ # 项目名称orAPP名称
tasks/
main.yml # 任务主文件
deploy.yml # 任务入口,调度roles任务
```
#### 目录约定
```shell
# 主配置文件
tasks - contains the main list of tasks to be executed by the role.
# 处理任务
handlers - contains handlers, which may be used by this role or even anywhere outside this role.
# 默认变量,我理解是全局
defaults - default variables for the role (see Variables for more information).
# 自定义变量,我理解是临时
vars - other variables for the role (see Variables for more information).
# 要拷贝的文件(不需要更改)
files - contains files which can be deployed via this role.
# 要使用的模版(需要更改)
templates - contains templates which can be deployed via this role.
# 元数据(待研究)
meta - defines some meta data for this role. See below for more details.
```
#### 基础语法(多行缩进)
```
对齐很重要,不要混用tab和空格
建议用2个空格分级
字符串不一定需要双引号
允许空行,增加可读性
连续项目使用"-"
map结构中的key/value用":"分割,:后面有空格
"---"开头,顶行首写
k/v值大小写敏感
最少需要name:task,一个name只能有一个task
```
#### 在Playbook中设置变量
```yaml
---
- hosts: all
gather_facts: no
vars:
user: "ding1"
tasks:
- name: create user
user: name="{{user}}"
- name: echo user
debug: msg="{{user}}"
```
在调用文件中的变量
vars.yml
```yaml
---
- hosts: all
gather_facts: no
vars_files:
- var.yml
tasks:
- name: create user
user: name="{{user}}"
- name: echo user
debug: msg="{{user}}---->{{sex}}"
```
var.yml
```yaml
---
user: ding
sex: man
```
在Roles的vars和defaults中设置变量
使用一个在playbook中注册的变量
```yaml
---
- hosts: all
gather_facts: no
tasks:
- name: register vars
shell: hostname
register: info
- name: display vars
debug: msg="{{info.stdout}}"
```
';