sorin
sorin

Reputation: 170440

How to pass variables from one role downstream to other dependency roles with ansible?

I have a generic webserver role that is using another nginx role to spawn new vservers.

webserver/meta/main.yml looks like:

allow_duplicates: yes
dependencies:
  - role: nginx
    name: api vserver
    frontend_port: "{{ frontend_port }}"
    domain: "{{ api_domain }}"
    backend_host: 127.0.0.1
  - role: nginx
    name: portal vserver
    domain: "{{ portal_domain }}"
    backend_host: 127.0.0.1

The problem is that these variables are supposed to be defined inside the webserver-role/vars/(test|staging).yml

Is seems that Ansible will try to load the dependencies before loading the variables.

How can I solve this problem? I don't want to put any configuration specifics inside the low level roles.

Also, I do not want to put configurations inside the playbook itself because these configurations are shared across multiple playbooks.

Upvotes: 14

Views: 9175

Answers (2)

senjoux
senjoux

Reputation: 314

A "vars" can be provided :

    # roles/myapp/meta/main.yml
---
dependencies:
  - role: common
    vars:
      some_parameter: 3
  - role: apache
    vars:
      apache_port: 80
  - role: postgres
    vars:
      dbname: blarg
      other_parameter: 12

please refer to Using role dependencies, here

Upvotes: 1

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

This scenario works with Ansible 2.2.
Vars for dependent roles are specified in main role's vars files:

./roles/role1/tasks/main.yml:

- debug: msg="{{ role_param }}"

./roles/role2/meta/main.yml:

allow_duplicates: yes
dependencies:
  - role: role1
    role_param: "{{ param1 }}"
  - role: role1
    role_param: "{{ param2 }}"

./roles/role2/tasks/main.yml:

- debug: msg=role2

./roles/role2/vars/main.yml:

param1: hello1
param2: hello2

Result:

PLAY [localhost] ***************************************************************

TASK [role1 : debug] ***********************************************************
ok: [localhost] => {
    "msg": "hello1"
}

TASK [role1 : debug] ***********************************************************
ok: [localhost] => {
    "msg": "hello2"
}

TASK [role2 : debug] ***********************************************************
ok: [localhost] => {
    "msg": "role2"
}

Upvotes: 12

Related Questions