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.
If you gather_facts , which is enabled by default for playbooks, there is a built-in variable that is set called ansible_user_id that provides the user name that the tasks are being run as. You can then use this variable in other tasks or templates with {{ ansible_user_id }} .
The user input is hidden by default but it can be made visible by setting private: no . Prompts for individual vars_prompt variables will be skipped for any variable that is already defined through the command line --extra-vars option, or when running from a non-interactive session (such as cron or Ansible AWX).
If the remote user needs to provide a password in order to run sudo commands, you can include the option --ask-become-pass to your Ansible command. This will prompt you to provide the remote user sudo password: ansible all -m ping --ask-become-pass.
Setting a remote user You can set the connection user in a playbook: --- - name: update webservers hosts: webservers remote_user: admin tasks: - name: thing to do first in this playbook . . . Details on the remote_user keyword and ansible_user variable. Details on Ansible precedence rules.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With