how to use variables from one role in another role

5,408 views
Skip to first unread message

Stri}{

unread,
Aug 5, 2015, 9:27:57 AM8/5/15
to Ansible Project
Hi,
How to set a variable inside role A and use it inside role B ? Role B is listed in dependencies sections in meta/main.yml of role A and I see its output then call role A. 
I have tried to use set_fact module or register variable, but no luck.

role A:


- name: Print test var from another role
  debug
: msg="{{ test_var }}"


role B:


- name: Save some vars in register
  shell
: echo "BLAH"
 
register: test_var


- name: Save some vars in facts
  set_fact
:

    test_var
: BLAH


ansible-playbook's Output:

fatal: [localhost] => One or more undefined variables: 'test_var' is undefined
FATAL: all hosts have already failed -- aborting

If I set test_var via role's parameter in site.yml, all works fine:

site.yml

---
- hosts: all



  roles
:

   
- { role: ntpd, test_var: "BLAH" }


ansible-playbook's Output:
TASK: [runit | Print test var from another role] **********************************************
ok: [localhost] => {
    "msg": "BLAH"
}
  

I want to write wrapper for runit service supervisor, so I need from service roles (ntpd, sshd, etc) some variables (service_name, run_script, log_script, service_status, etc).




Dick Davies

unread,
Aug 5, 2015, 10:10:56 AM8/5/15
to ansible list
On 5 August 2015 at 12:22, Stri}{ <stri...@googlemail.com> wrote:
> Hi,
> How to set a variable inside role A and use it inside role B ? Role B is
> listed in dependencies sections in meta/main.yml of role A and I see its
> output then call role A.

If role A depends on B, then B will get handled first, _then_ A.

Any vars you set in B are visible in A, but not the other way round
(since B happens 'before' A and you haven't had a chance to set those vars).

Stri}{

unread,
Aug 6, 2015, 4:50:19 AM8/6/15
to Ansible Project, di...@hellooperator.net
If I use var/main.yml for storing variables, all works fine (variables from Role A and B seen in each role).
I want to symplify code in my roles and move generic code to separate role or playbook. Then I want to pass some variables from roles to this playbook (for creating directory structure, for example). I can't save output from modules inside role A in variable and pass it to role B (even with set_fact module inside one server I see facts onle inside the role, where I create fact.)

среда, 5 августа 2015 г., 19:10:56 UTC+5 пользователь Dick Davies написал:
Reply all
Reply to author
Forward
0 new messages