Ansible quirks: Delegating a task with a unique remote user

I’ve spent a few hours banging my head against something that – in retrospect – is pretty obvious: “delegate_to” does not respect the “ansible_user” inventory variable.

Challenge

delegate_to is used to execute a task on a host other than the one targeted for playbook execution.  Compare these three tasks:

- command: echo Hello World

- command: echo Hello World
  delegate_to: localhost

- command: echo Hello World
  delegate_to: random.example.com

The first task will execute “echo Hello World” on the system in the inventory that this playbook is being called for.

The second task will simply execute the ‘echo’ on the system running the ansible playbook.

The third task will connect to “random.example.com” to execute the echo.  But, notably, “random.example.com” doesn’t even need to be in your inventory, and so the connection to “random.example.com” does not use any inventory variables, such as “ansible_user”.

“delegate_to” will respect the global “remote_user”, but I often use different non-root user accounts for Ansible connections.  So, if “delegate_to” doesn’t respect “ansible_user”, and if I can’t set a useful global “remote_user”, what can I do?

Solution

Once I figured this out, it’s pretty obvious in hindsight:

- command: echo Hello World
  delegate_to: my_remote_user@random.example.com

“delegate_to” allows the user to be part of the connection string.  In this example, I will connect to ‘random.example.com’ as the ‘my_remote_user’ id.  This could also be replaced with an inventory variable for the host the playbook is run for.

Leave a Reply

Your email address will not be published. Required fields are marked *