Programmatically changing ansible_ssh_user during a play

I'm currently creating a common ansible playbook for Ubuntu.

During the hardening process I disable the root user and create a new sudo user for running future playbooks (called ansible).

The first time I run this playbook I have ansible_ssh_user set as root the second time I have to manually change the ansible_ssh_user var to ansible.

Is there a way for ansible to track which hosts have had this step completed and connect with the newly created ansible user or even to fallback to a second username attempt. I would like this process to be unattended if at all possible.

Edit: I'm trying to correct the user when establishing a new connection. For example. I ran the hardening playbook one one server. Now I want to run it to provision a new server and make some updates to the existing ones. Therefore I have two usernames root and ansible. I would like the script to try both instead of setting a host var, are host vars my only option here?


Solution 1:

Use metadata that your inventory script can query and then select the user based on the group of the target box.

For instance, using AWS, set a hardened tag after you set up the ansible user, then when you run other plays, you can use the ansible user on hosts that have the hardened tag set. This will appear automatically as a group using the AWS inventory.