0

I have a variable that is very specific to a playbook, not necessarily tied to a host or host group.

I would like to declare this variable in the playbook itself, and have it shared between plays without having to redeclare.

Example below is a simple 2 play actions in a playbook. The variable "foo" isn't really related to the host or the host group, it's specific to the playbook internally, so I would like that var to stay local to the playbook.

- name: "Test1"
  hosts: localhost
  vars:
    foo: bar
  tasks:
    - name: "Debug1"
      ansible.builtin.debug:
        msg: " {{ foo }} "


- name: "Test2 - this will fail"
  hosts: localhost
  tasks:
    - name: "Debug2"
      ansible.builtin.debug:
        msg: "{{ foo }}"

I realize this example doesn't make logical sense to build like this split across plays for a single host. It's an ultra-simplified version of the actual problem I'm facing to demonstrate what I would like to do.

My question is this: Without creating new group_vars/host_vars files for "localhost", combining tasks to the single play, and without re-declaring the foo variable for each play, is there a way to make these plays share the foo variable?

1 Answer 1

0

Figured this out a few minutes after asking of course!

This works, using set_fact to make the variables persistent. This will only work if each play has a matching hosts: value

- name: "Test1"
  hosts: localhost
  vars:
    foo: bar
    zoo: zar
  tasks:
    - name: "Make host play variables persistent"
      ansible.builtin.set_fact:
        foo: "{{ foo }}"
        zoo: "{{ zoo }}"

- name: "Test2 - variables now exist in this play"
  hosts: localhost
  tasks:
    - name: "DebugFoo"
      ansible.builtin.debug:
        msg: "{{ foo }}"
    - name: "DebugZoo"
      ansible.builtin.debug:
        msg: "{{ zoo }}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.