Rich Tier
Rich Tier

Reputation: 9441

Ansible get the username from the command line

In my playbooks I reference username (exclusively its "ubuntu") a lot.

Is there a built in way to say "get it from the value passed in the command line"?

I know I can do

ansible-playbook <task> -u <user> -K --extra-vars "user=<user>"

and then I can use {{user}} in the playbook, but it feels odd defining the user twice.

Upvotes: 27

Views: 31760

Answers (2)

Ramon de la Fuente
Ramon de la Fuente

Reputation: 8343

As Woodham stated, the ansible variable that represents the connecting user is

{{ ansible_user }} (Ansible < 2.0 was {{ ansible_ssh_user }} )

But you don't have to define it in the inventory file per se.

You can define it in:

1. Your play, if you use ansible-playbook: See the manual on Playbooks

- name: Some play
  hosts: all
  remote_user: ubuntu

2. In the inventory file: See the manual on inventory

[all]
other1.example.com     ansible_user=ubuntu (Ansible < 2.0 was ansible_ssh_user)

3. As you stated, on the commandline:

ansible-playbook -i inventory -u ubuntu playbook.yml

4. An ansible config file as a remote_user directive. See the manual on a config file

The ansible config file can be placed in the current folder ansible.cfg, your homedir .ansible.cfg or /etc/ansible/ansbile.cfg.

[defaults]
remote_user=ubuntu

Upvotes: 42

Woodham
Woodham

Reputation: 4263

I believe the standard way to do this would be define ansible_ssh_user in the inventory file and you can then reference it as {{ ansible_ssh_user }} in the playbook.

Upvotes: 1

Related Questions