Example 2
hosts.ini
[centos]
provisioner ansible_connection=local
centos1 ansible_host=192.168.77.22 ansible_user=root
[ubuntu]
ubuntu1 ansible_host=192.168.77.23 ansible_become=true
Tip
Many variables including the become
directive and the SSH user name can be specified as hostvars
, which are simply put a group of variables that describe a single host.
Try to execute the whoami
command on all hosts.
ansible all -m command -a "whoami"
What is the expected output of the command ?
The command will generate a different output on every host
- on
provisioner
- we will be identified as thevagrant
user since we did not explicitly instruct Ansible to act otherwise - on
centos1
- we will get an error since our SSH authentication method (public key) is valid only for thevagrant
user - on
ubuntu1
- we will run the command as theroot
user since we instructed Ansible to use thebecome
directive
Bonus round
Fix the problem with centos1
. Use one of the following methods or come up one with one on your own
- copy the provisioner's SSH public key to the
authorized_keys
of the root user oncentos1
(when prompted for the root password typevagrant
)ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.77.22
- modify the
hosts.ini
file by addingansible_password=vagrant
to the line describingcentos1
. Before executing the command install thesshpass
program on the provisioner.sudo yum install -y sshpass