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: "127.0.0.1" # not good
myapp_bin_Ip: "127.0.0.1" # not good
myapp_bind_ip: "127.0.0.1" # 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/defaults/main.yml
role_a_database_name: "foo"
role-b/defaults/main.yml
role_b_database_name: "foo"
group_vars/app.yml
database_name: "foo"
group_vars/role-a.yml
role_a_database_name: "{{ database_name }}"
group_vars/role-b.yml
role_b_database_name: "{{ database_name }}"
inventories/hosts
[app:children]
role-a
role-b

[role-a]
host1

[role-b]
host2

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
  service:
    name: haproxy
    state: reloaded

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

Conclusion

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