Skip to content

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 the vagrant 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 the vagrant user
  • on ubuntu1 - we will run the command as the root user since we instructed Ansible to use the become 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 on centos1 (when prompted for the root password type vagrant)
    ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.77.22
    
  • modify the hosts.ini file by adding ansible_password=vagrant to the line describing centos1. Before executing the command install the sshpass program on the provisioner.
    sudo yum install -y sshpass