Use "register" local to a playbook (or unset a variable)

640 views
Skip to first unread message

Serdyn du Toit

unread,
May 29, 2016, 10:09:13 AM5/29/16
to Ansible Development
Hi,


How can I "register" a variable in a playbook - but in a way that it will no longer be set in subsequent playbooks that get executed.


It seems that if I declare the variable at the top of the playbook, as in this example:
---
- name: test playbook
  hosts: all
  vars:
      testVariable: 
then the variable only exists in the context of that playbook.


If I register a variable using Ansible's "register" command - it is still set in subsequent playbooks.
I guess this is the required behavior - because Ansible's documentation says:
"Registered variables are valid on the host the remainder of the playbook run, which is the same as the lifetime of “facts” in Ansible. Effectively registered variables are just like facts."


So variable defined at the top of the playbook = local
Registered variables and facts = global, valid over all playbooks


Now in my playbook I'm registering a variable but I don't really need it in subsequent playbooks:
---
- name: prepare environment
  hosts: all
   
  tasks:

  - # Sanity check that {{ deploy_dir }} doesn't exist as it should be unique
    # per deploy
    name: confirm that {{ deploy_dir }} doesn't exist
    stat: path={{ deploy_dir }}
    register: p
     
    fail: msg="Deploy directory already exists! Deploy directory{{ ":" }} {{ deploy_dir }}"
    when: p.stat.exists == true


Is there a way to either
1) use "register" so that the variable will only be local to the playbook, or
2) set the registered variable to NULL at the end of my playbook?


Its not killing me now - I'm just thinking of scalability.  That I don't want this "p" variable of mine to be global because it unnecessarily reduces the namespace of variables that other developers can use, and now its something that they need to know about - that if they try to use the "p" variable in subsequent playbooks they might encounter problems because its something that was used before and now remains set for all future playbooks that get executed during the current run.


Thank you for any help or insights :)

Serdyn du Toit

unread,
May 29, 2016, 5:05:23 PM5/29/16
to Ansible Development
Actually - I'm going to rename the variable to "tmp" and just use it every time if I need to "register" something that's actually only local to the playbook.
So basically recycling the variable - knowing that its value will be re-set (or fail to be re-set) each time I call a task using "register".  And having the coding convention of always using "tmp" for variables for these - I retain the full variable namespace for proper code.

Still, curious if there are a way to unset variables or maybe even use "register" in a way that is local to a playbook - but my code is working, so I'm happy :)
Reply all
Reply to author
Forward
0 new messages