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 thevagrantuser 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 thevagrantuser - on
ubuntu1- we will run the command as therootuser since we instructed Ansible to use thebecomedirective
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_keysof 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.inifile by addingansible_password=vagrantto the line describingcentos1. Before executing the command install thesshpassprogram on the provisioner.sudo yum install -y sshpass