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):

                    ansible_port: 11111
                    ansible_user: user_foo

And I have the following playbook:

- name: Test
  hosts: test
          backup_ansible_port: "{{ ansible_port }}"
          backup_ansible_user: "{{ ansible_user }}"
          ansible_port: "{{ tmp_port }}"
          ansible_user: root
          - name: foo
                    - "{{ 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": [

Expected output:

TASK [foo] *********************************
  ok: [test] => {
      "msg": [

Why is this not the case?

1 Answer 1


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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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