0
votes

How Can I reset an overriden variable in a playbook back to the value that is defined in group_vars for that variable

So for example, If I have variable name: "Hello from group_vars" defined in group vars, but during the executin playbook I override it base on some condition with set fact

  • set_fact: name: "Overriden somewhere in playbook only for the next task" when: << some condition that is ture >>

  • name: Next task debug: msg: "Name is {{ name }}" # This will show value from the set_fact

but for the next task I would want to reset the name to the value to the one that has beeen set in group_vars while still in the same playbook execution

  • set_fact: name: << How to reset it to group_vars value logic >>

  • Name: Show the value debug: msg: "Nanme is {{ namne }}" # This now should show the value set in group_vars "Hello from group vars"

Any ideas on how to achieve this. Thanks

1

1 Answers

0
votes

Generally, once you set_fact for a host, you can't go back, unless you store a copy of the original value and set_fact again later, or re-gather the facts layer (by using a different play in your play book, for example).

If you can, use a specialized fact (and maybe defaults) to achieve a similar goal.

For example:

- name: conditionally set fact
  set_fact: 
     special_name: "overridden value"
  when: my_condition 
- name: use fact or default
  debug: 
     msg: "Name is {{ special_name | default(name)}}"

If you want to use your overridden value more frequently, you might use a second variable to handle the assignment:

- name: conditionally set fact
  set_fact: 
     special_name: "overridden value"
  when: my_condition 
- name: use default globally
  set_fact:
     special_name: "{{ special_name | default(name) }}"
- name: use fact or default
  debug: 
     msg: "Name is {{ special_name }}"

It's a little longer, but it gets you a value you can count on in multiple locations without having to put the default in multiple places.