Variable introspection

A common set of problems that are encountered when developing Ansible playbooks is the improper use, or invalid assumption, of the value of variables. This is particularly common when registering the results of one task in a variable, and later using that variable in a task or template. If the desired element of the result is not accessed properly, the end result will be unexpected, or perhaps even harmful.

To troubleshoot improper variable usage, inspection of the variable value is the key. The easiest way to inspect a variable's value is with the debug module. The debug module allows for displaying free form text on screen, and like with other tasks, the arguments to the module can take advantage of the Jinja2 template syntax as well. Let's demonstrate this usage by creating a sample play that executes a task, registers the result, and then shows the result in a debug statement using the Jinja2 syntax to render the variable:

--- 
- name: variable introspection demo 
  hosts: localhost 
  gather_facts: false 
 
  tasks: 
    - name: do a thing 
      uri: 
        url: https://derpops.bike 
      register: derpops 
 
    - name: show derpops 
      debug: 
        msg: "derpops value is {{ derpops }}" 

When we run this play, we'll see a displayed value for derpops, as shown in the following screenshot:

The debug module has a different option that may be useful as well. Instead of printing a free form string to debug template usage, the module can simply print the value of any variable. This is done using the var argument instead of the msg argument. Let's repeat our example, but this time, we'll use the var argument, and we'll access just the server subelement of the derpops variable, as follows:

--- 
- name: variable introspection demo 
  hosts: localhost 
  gather_facts: false 
 
  tasks: 
    - name: do a thing 
      uri: 
        url: https://derpops.bike 
      register: derpops 
 
    - name: show derpops 
      debug: 
        var: derpops.server 

Running this modified play will show just the server portion of the derpops variable, as shown in the following screenshot:

In our example that used the msg argument to debug, the variable needed to be expressed inside curly brackets, but when using var, it did not. This is because msg expects a string, and so Ansible needs to render the variable as a string via the template engine. However, var expects a single unrendered variable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.105.114