ansible:如何在角色之间共享变量

时间:2017-11-16 10:16:01

标签: ansible ansible-role

我需要在同一主机上执行少量任务,但希望将任务分组到需要彼此共享某些输出的不同角色。请考虑以下示例

│── hosts
├── playbooks
│   ├── Playbook1.yml
│
├── roles
│   └── role1
│       ├── files
│       │   └── project1.conf
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml [Creates variable role1_a, role1_b]
│       ├── templates
│       └── vars
│           └── main.yml
│   └── role2
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml [uses variable from role1 role1_a and creates variable role2_c]
│       ├── templates
│       └── vars
│           └── main.yml
│   └── role3
│       ├── handlers
│       │   └── main.yml
│       ├── meta
│       │   └── main.yml
│       ├── tasks
│       │   └── main.yml [uses variable from role1 role1_b and role2 role2_c]
│       ├── templates
│       └── vars
│           └── main.yml
│

有没有办法收集role1的输出并将其传递给role2和role3,如

- hosts: localhost
  roles:
    - role: role1_a, role1_b = {role1}
    - role: role2_c = {role2 role1_a: role1_a, role1_b: role1_b}
    - role: {role2 role1_b: role1_b role2_c: role2_c}

或在角色之间共享变量的任何其他机制?

1 个答案:

答案 0 :(得分:0)

通过将local_actionlineinfile

组合,将role1中的任务包含在role1_a和role1_b的值中,将{1}}和/ {
- name: Copy value of role1_a to var definition of role2
  local_action:
    module: lineinfile
    path: ~/ansible/roles/role2/vars/main.yml
    regexp: '^role1_a'
    line: "role1_a: {{ role1_a }}"

- name: Copy value of role1_b to var definition of role3
  local_action:
    module: lineinfile
    dest: ~/ansible/roles/role3/vars/main.yml
    regexp: '^role1_b'
    line: "role1_b: {{ role1_b }}"