Variables, task variables and set_fact

270 views
Skip to first unread message

Alexander Jensen

unread,
Mar 9, 2022, 9:23:02 AM3/9/22
to Ansible Project

Hello,

can someone help me to understand the behavior?

Playbook:
---
- name: Play Vars
  hosts: all
  gather_facts: false
  vars:
    foo: a
  tasks:
    - name: debug foo 1
      debug:
        var: foo
    - name: Include tasks
      include_tasks: tasks/tasks-vars.yml
      vars:
        foo: b
    - name: Import tasks
      import_tasks: tasks/tasks-vars.yml
      vars:
        foo: b
    - name: debug foo 2
      debug:
        var: foo

Tasks file:
---
- name: Output 1
  debug:
    var: foo

- name: set fact
  set_fact:
    foo: c

- name: Output 2
  debug:
    var: foo


Output:
$ ansible-playbook -i inventories/test/hosts.ini play-vars.yml

PLAY [Play Vars] *********************************************

TASK [debug foo 1] *******************************************
ok: [localhost] => {
    "foo": "a"
}

TASK [Include tasks] *****************************************
included: /.../tasks/tasks-vars.yml for localhost

TASK [Output 1] **********************************************
ok: [localhost] => {
    "foo": "b"
}

TASK [set fact] **********************************************
ok: [localhost]

TASK [Output 2] **********************************************
ok: [localhost] => {
    "foo": "b"
}

TASK [Output 1] **********************************************
ok: [localhost] => {
    "foo": "c"
}

TASK [set fact] **********************************************
ok: [localhost]

TASK [Output 2] **********************************************
ok: [localhost] => {
    "foo": "c"
}

TASK [debug foo 2] *******************************************
ok: [localhost] => {
    "foo": "c"
}


I don't unterstand why the vars attribute with the modules include_tasks and import_tasks works different.
Why the set_fact inside the include_tasks has no effect?

Thanks for you explanation.

Best regards
Alexander

Matt Martz

unread,
Mar 9, 2022, 9:31:01 AM3/9/22
to ansible...@googlegroups.com
`vars` on `include_tasks` are considered "include params" which is 21 on the precedence chart.  `set_fact` is 19 on that list, and `vars` on `import_tasks` are considered "task vars" which are 17.


--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/4c25f87e-4949-4836-8ee2-1d526b735058n%40googlegroups.com.


--
Matt Martz
@sivel
sivel.net
Reply all
Reply to author
Forward
0 new messages