Score:0

How to register a variable in one role and use it in another one in Ansible?

np flag

I am trying to register a variable in a role and then use it in another one.

Here are the different files I'm using :

playbook.yml

---
- hosts: hostsgroup1
  [...]
  roles:
    - role1
- hosts: 127.0.0.1
  connection: local
  roles:
    - role2

role1/tasks/main.yml

- name: Example 1
  [...]
- name: Example 2
  shell:
    qm agent {{ VM_id }} network-get-interfaces |grep ip-address |grep '172.20' |grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])'
  register: var_role1

role2/tasks/main.yml

- name: Adding server to bastion
  ansible.builtin.debug:
    msg : Test {{ var_role1.stdout }}

For the information, the qm agent command gives me an IP address and I want to use it in the second role. But obviously, for now it displays an error when I execute the playbook :

fatal: [127.0.0.1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: \"hostvars['proxmoxhosts']\" is undefined\n\nThe error appears to be in '/root/ansible/roles/bastion_add/tasks/main.yml': line 3, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n# tasks file for bastion_add\n- name: Adding server to bastion\n  ^ here\n"}

To summarize, I want to use var_role1, registered in role1, in role2.

Score:1
in flag

set_fact should do the trick.

- name: Example 2
  shell:
    qm agent {{ VM_id }} network-get-interfaces |grep ip-address |grep '172.20' |grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])'
  register: var_role1
- set_fact:
    var_role1: "{{ var_role1.stdout }}"
Milos Vé avatar
np flag
Do I have to call the variable differently than "{{ var_role1.stdout }}" in the second role ? Because it's still not working with your tips
in flag
TBH I didn't really test it. `var_role1` was of course not correct, `var_role1.stdout` should be correct
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.