Ansible Setup by Project

Setting Up an Ansible Project

Once Ansible is installed, the next step is to tell Ansible which hosts to talk to. This is accomplished by creating an Ansible hosts file. The Ansible hosts file contains groups of hosts, which we refer to when running Ansible commands. By default Ansible expects this to be located in /etc/ansible/hosts. However, the results of a host file in that location are applied globally across your system. Instead, to make things simpler, we need to tell Ansible to use a local project hosts file. This is also better for keeping track of your project requirements in git. Enter the Ansible configuration file. Oddly enough, it is named ansible.cnf.

Ansible Project Configuration File

Ansible will always look for a file named, $> ansible.cfg , starting in the root of the project directory.That said, use the ansible.cnf file to setup Ansible for an individual project. Simply create the ansible.cnf file in the root of the project directory.

Then use Ansible’s config file to tell Ansible to look in the local project directory for the host inventory file rather than the global inventory file located at /etc/ansible/hosts.

To accomplish this, place the following code within the ansible.cfg file.

hostfile = hosts

The ‘hostfile = hosts’ directive tells Ansible where to look relative to the local root of your project.

Ansible Hosts File

The hosts file is a simple text file that has group names within brackets followed by lists of hosts in the form of DNS names or IPs.  See the Ansible documentation to learn how you can create groups of groups if you like.

[webservers] ansible_ssh_user=ubuntu ansible_ssh_private_key_file=~/yourpemkey.pem
( ansible_ssh_private_key_file is NOT SECURE USE SSH KEYS )

Command Line Test

$> ansible webservers -m ping


$> ansible webservers -m ping --private-key="~/AWS_pems/practice01.pem"
( private key flag not needed if key is spc’d elsewhere like hosts file or SSH keys)

output looks like this: | success {
    "changed": false,
    "ping": "pong"

Ansible Playbook

An Ansible playbook is simply a yaml file that specifies tasks to be run on a group of hosts. The playbook is easy to read and write.

Create a playbook file named site.yml
Enter the following text:

- hosts: webservers ←- arbitrary group name defined in the hosts file
    - name: run a command echo out something ←- arbitrary text
      command: /bin/echo hello world! This command was run by Ansible.

The module invoked here is the ‘command’ module. This is the Ansible command module. See how it is used to simply run a command as if you were in the terminal of the remote server?

From within our project’s directory, run the Ansible playbook by doing the following:

ansible-playbook site.yml


ansible-playbook site.yml --private-key="~/AWS_pems/practice01.pem"

Leave a Reply

Your email address will not be published. Required fields are marked *