Ansible Role

Ansible Role用于维护大型的playbooks,下面为具体一个实际例子。

目录结构

.
└── roles
    ├── demo
    │   ├── tasks
    │   │   └── main.yml
    │   ├── templates
    │   │   └── hello_world.txt.j2
    │   └── vars
    │       └── main.yml
    ├── setup.yml
    └── version
        ├── 1.0.yml
        └── 2.0.yml

其中demo为创建的role,在role目录下包含tasks/templates/vars子目录, 默认读取tasks和vars中的main.yml文件。

  • tasks的main.yml放置需要执行的任务;
  • vars的main.yml放置变量集;
  • templates为模板文件
  • tasks会引用模板文件+vars,执行特定task任务。

Role=demo下的主要文件

roles/demo/tasks/main.yml

---
    - name: generation the hello_world.txt file
      template:
        src: templates/hello_world.txt.j2
        dest: /tmp/hello_world.txt
    - name: show file context
      command: cat /tmp/hello_world.txt
      register: result
    - name: print stdout
      debug: msg={{ result.stdout}}

roles/demo/vars/main.yml

dynamic_word: "main"

roles/demo/templates/hello_world.txt.j2

start
Hello "{{ dynamic_word }}"
version "{{ version_num }}"
end

Ansible主Playbook: roles/setup.yml

--- 
- name: Play the template module
  hosts: localhost
  roles:
  - demo

附加变量定义文件:roles/version/2.0.yml

version_num: 2.0

检查语法

ansible-playbook setup.yml  --syntax-check

执行Playbook

ansible-playbook setup.yml  -e @version/2.0.yml

其中-e后的为参数文件,并加上@前缀特殊符号。返回结果。


PLAY [Play the template module] **************************************************************************

TASK [Gathering Facts] ***********************************************************************************
ok: [localhost]

TASK [demo : generation the hello_world.txt file] ********************************************************
ok: [localhost]

TASK [demo : show file context] **************************************************************************
changed: [localhost]

TASK [demo : print stdout] *******************************************************************************
ok: [localhost] => {
    "msg": "start\nHello \"main\"\nversion \"2.0\"\nend"
}

PLAY RECAP ***********************************************************************************************
localhost                  : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值