May 12, 2018

Ansible naming conventions

When using Ansible, it’s important to define naming conventions and to apply them for all your roles and playbooks. Here are mine.

All variables should be snake_case

The easiest rule:

myappBindIp: "" # not good
myapp_bin_Ip: "" # not good
myapp_bind_ip: "" # good

Roles and groups names

I use kebab-case for my roles and groups names (haproxy, kafka-manager…​).

Variables defined in a role

All variables defined in a role (defaults/main.yml, vars/main.yml) should be prefixed with the role name. It prevents collisions between variables and also allows to instantly know at what role a variable belongs to. For example, a role installing HAProxy will probably need a variable specifying the version in defaults/main.yml:

version: "1.8" # not good
haproxy_version: "1.8" # good

Sometimes, it’s tempting to use the same variable name in two roles if the variables should always have the same value (because being overrided somewhere). I think it’s better to create one variable per role no matter what. For example, if we have role-a and role-b, and each one need to know a (common) database name, we could do:

role_a_database_name: "foo"
role_b_database_name: "foo"
database_name: "foo"
role_a_database_name: "{{ database_name }}"
role_b_database_name: "{{ database_name }}"



Here, each role has a specific variable defined for the database name. If the database name should always be the same, i can define a parent group (app) and two child groups (one for each role, role-a and role-b). I can now share a variable between groups in the group_vars files.

This approach avoids side effects between roles, and simplifies future refactoring.

Registered variables

I usually prefix registered variables by _<rolename>, to differentiate them from defaults variables.

Handlers names

It’s also important to name correctly your handlers. My convention is: <target> | <action>:

- name: haproxy | reload
  become: true
    name: haproxy
    state: reloaded

- name: apt | update cache
  become: true
    update_cache: yes


Naming is super important. This will greatly simplify the maintenance of your Ansible projects.

Tags: devops

Add a comment

If you have a bug/issue with the commenting system, please send me an email (my email is in the "About" section).

Top of page