Use variable only if defined in Ansible

Use variable only if defined in Ansible

My colleague and I use Ansible to manage a group of servers.
We use the .ansible.cfg file in our local home directories to setup our local environments and keep our playbooks in a git repo.
When authenticating to servers, I use user1, and he uses user2. 95% of of our servers have these accounts, but historically reasons, a few servers only have a "user" account.
We're using host_vars to set the remote_user variable for the minority of servers in question.
However, in our playbooks, we generally user "all" to stipulate what servers we want to hit, and use the --limit parameter on the command line to specify exactly which servers should get the update. Our server farm is a legacy of mis-mash poorly engineered servers that have to be kept online until they are retired in a few years, and we've found that this approach best suits our needs.
Our issue is that our remote_user parameter is set in our .ansible.cfg file, where it is exposed as environment variable rather than a script variable.
That means if our task contains:
remote_user: "{{ remote_user }}"

It will only work for hosts for which that variable is defined
For the 95% of hosts for which we don't define this variable, the task fails.
Is there a way to only use the variable if it is defined?
If remote_user is defined, use it, if not, use the environment variable set in .ansible.cfg
Note: I know I can use:
- name: Do something 
  remote_user: "{{ remote_user }}"
  when: remote_user is defined

In a task definition, but that will only apply to that task, and I don't want to have to update all task
When I really need is for that condition to be available at the hosts definition, ie:
- hosts: all
    remote_user: "{{ remote_user }}"
    when: remote_user is defined

But that is illegal in Ansible


Answer 1:

As usual, after spending 2 hours postponing asking the question here, I find the answer 5 mins after I post the question!

Its really simple. To set a different remote_user for individual systems without having to apply loads of hacks to existing playbooks, just add the var to the host in your inventory:

server1 ansible_ssh_user=user

In this instance, any time a play incldues server1, “user” will be used as the ssh user. For server2, the value of remote_user from your ansible.cfg file will be used (eg user1, user2 etc depending on the local environment).