cydia
cydia

Reputation: 113

How to use variables between different roles in ansible

my playbook structure looks like:

- hosts: all
  name: all
  roles:
  - roles1
  - roles2

In tasks of roles1, I define such a variable

   ---
   # tasks for roles1
   - name: Get the zookeeper image tag # rel3.0
     run_once: true
     shell: echo '{{item.split(":")[-1]}}' # Here can get the string rel3.0 normally
     with_items: "{{ret.stdout.split('\n')}}"
     when: "'zookeeper' in item"
     register: zk_tag

ret.stdout:

Loaded image: test/old/kafka:latest
Loaded image: test/new/mysql:v5.7
Loaded image: test/old/zookeeper:rel3.0

In tasks of roles2, I want to use the zk_tag variable

- name: Test if the variable zk_tag can be used in roles2
  debug: var={{ zk_tag.stdout }}

Error :

The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout'

I think I encountered the following 2 problems:

  1. When registering a variable with register, when condition is added, this variable cannot be used in all groups. How to solve this problem? How to make this variable available to all groups?

  2. is my title, How to use variables between different roles in ansible?

Upvotes: 0

Views: 2850

Answers (2)

Kevin C
Kevin C

Reputation: 5760

You're most likely starting a new playbook for a new host. Meaning all previous collected vars are lost.

What you can do is pass a var to another host with the add_host module.

- name: Pass variable from this play to the other host in the same play
  add_host:
    name: hostname2
    var_in_play_2: "{{ var_in_play_1 }}"

--- EDIT ---

It's a bit unclear. Why do you use the when statement in the first place if you want every host in the play for it to be available? You might want to use the group_vars/all.yml file to place vars in.

Also, using add_host should be the way to go as how I read it. Can you post your playbook, and the outcome of your playbook on a site, e.g. pastebin?

Upvotes: 1

Zeitounator
Zeitounator

Reputation: 44799

If there is any chance the var is not defined because of a when condition, you should use a default value to force the var to be defined when using it. While you are at it, use the debug module for your tests rather than echoing something in a shell

- name: Debug my var
  debug:
    msg: "{{ docker_exists | default(false) }}"

Upvotes: 0

Related Questions