Variables not consumed from delegated host

In delegation docs it’s stated that:

All variables except inventory_hostname will now be consumed from this host and not the original task host.

However, this playbook seems to still use variables from original host as illustrated below.

- hosts: all
  become: false
  gather_facts: true
  tasks:

    - ansible.builtin.shell:
        cmd: echo "{{ ansible_hostname }}"
      delegate_to: localhost
      register: local_hostname

    - ansible.builtin.debug:
        msg: "{{ local_hostname.stdout }}"
TASK [ansible.builtin.shell] *****************************
changed: [webserver-1 -> localhost]
changed: [webserver-2 -> localhost]
changed: [db -> localhost]

TASK [ansible.builtin.debug] *****************************
ok: [webserver-1] => {
    "msg": "webserver-1"
}
ok: [webserver-2] => {
    "msg": "webserver-2"
}
ok: [db] => {
    "msg": "db"
}

Am I misunderstanding the documentation or is there docs/ansible issue?

It looks like a documentation issue that needs to be resolved.

delegation really only impacts connection related variables.

The task definition itself is templated under the actual host, but connection related vars are pulled from the delegated host.

Digged a bit deeper and this is actually partially true.

When task executor resolves connection options it templates them using delegated variables (cvars and templar both contain delegated variables)

Few lines below, original variables are restored and it will only update connection variables that are not set , due to check in ConnectionBase.update_vars(). These variables are listed in COMMON_CONNECTION_VARS

So given following inventory:

db ansible_host=127.0.0.1 ansible_port=2201 ansible_user='vagrant' ansible_ssh_private_key_file='/home/kristian/projects/ansible-playground/.vagrant/machines/db/virtualbox/private_key'
webserver-1 ansible_host=127.0.0.1 ansible_port=2222 ansible_user='vagrant' ansible_ssh_private_key_file='/home/kristian/projects/ansible-playground/.vagrant/machines/webserver-1/virtualbox/private_key'
webserver-2 ansible_host=127.0.0.1 ansible_port=2200 ansible_user='vagrant' ansible_ssh_private_key_file='/home/kristian/projects/ansible-playground/.vagrant/machines/webserver-2/virtualbox/private_key'
  • ansible_port will remain as-is, since it’s already defined
  • ansible_private_key_file gets set from delegated host, since it’s set as ansible_ssh_private_key_file alias in the inventory.

Will see a bit later if i can come up with some concise description of this to update the docs.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.