Ansible structure layout – the best approach

This is called Ansible structure layout – the best approach that we used to use it as a template for our projects. This may be not the best but you can customized it as to fit your own.

Directory Layout

The top level of the directory would contain files and directories like so:

How to Arrange Inventory, Stage vs Production

  • production.ini: contains the inventory of all production hosts
  • stage.ini: contains the inventory of all staging hosts

It is suggested that you define groups based on the purpose of the host (roles) and also geography or data center location (if applicable):

Group And Host Variables

We can also assign variables to all hosts in a group or specific group or specific hosts. Let’s set those now:

If we had any default values or values that were universally true, we would put them in a file called group_vars/all:

We can define specific hardware variance in systems in a host_vars file, but avoid doing this unless you need to:

Playbooks Are Separated By Role

Playbook webservers.yml is used for all hosts in group webservers with roles common, nginx

Task And Handler Organization For A Role

Below is an example tasks file that explains how a role works. Our common role here just sets up NTP, but it could do more if we wanted:

Here is an example handlers file. As a review, handlers are only fired when certain tasks report changes and are run at the end of each play:

Let’s run your playbook

What about just reconfiguring NTP on everything? Easy.:


What about just reconfiguring my webservers?:


What about just my webservers in Boston?:


What about just the first 10, and then the next 10?:

And of course, just basic ad-hoc stuff is also possible.:

Stage vs Production

As also mentioned above, a good way to keep your stage (or testing) and production environments separate is to use a separate inventory file for stage and production. This way you pick with -i what you are targeting. Keeping them all in one file can lead to surprises!


Also published on Medium.

Leave a Reply

avatar
  Subscribe  
Notify of