1

Attempting to save a variable's value for backup before modifying it doesn't work.

I have the following inventory file (note the custom ansible_port and user):

all:
    hosts:
            test:
                    ansible_port: 11111
                    ansible_user: user_foo
                    ansible_host: 192.168.56.101 

And I have the following playbook:

- name: Test
  hosts: test
  vars:
          backup_ansible_port: "{{ ansible_port }}"
          backup_ansible_user: "{{ ansible_user }}"
          ansible_port: "{{ tmp_port }}"
          ansible_user: root
  tasks:
          - name: foo
            debug:
                    msg: 
                    - "{{ backup_ansible_port }}"
                    - "{{ backup_ansible_user }}"
                    - "{{ ansible_port }}"
                    - "{{ ansible_user }}"

Running the following command:

ansible-playbook bootstrap_ssh.yml --ask-pass -e 'target=test tmp_port=22'

The output is the following:

...
TASK [foo] *********************************
  ok: [test] => {
      "msg": [
          "22", 
          "root", 
          "22", 
          "root"
      ]
  }
...

Expected output:

...
TASK [foo] *********************************
  ok: [test] => {
      "msg": [
          "11111", 
          "user_foo", 
          "22", 
          "root"
      ]
  }
...

Why is this not the case?

2

It is a totally expected result. You define the same variables in different places and ansible applies its variable precedence

First of all, remember that variables passed as extra vars always win: you can never change them in any other place or during the run (i.e. set_fact).

Now let's decompose what happens. The schema is basically the same for all vars where you don't get the expected result. I'll only give the example for backup_ansible_port. You can follow the spaghetti yourself for the others once you got it.

When you hit the debug task to display "{{ backup_ansible_port }}"

  1. The first jinja2 template pass finds it should be an expansion of ansible_port as defined in your play vars.
  2. ansible_port is defined with value "11111" directly in your inventory as a host var (see #8 in above precedence doc) But it is also defined as an expansion of tmp_port in your play vars (see #12 in above precedence doc). Higher precedence wins, so the second jinja2 template pass finds it should expand tmp_port
  3. tmp_port has value "22" in your extra vars which will be the final value returned.
| improve this answer | |

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.