Pages

Friday 10 December 2021

Ansible best practices

 Here are a few best practices I found useful to follow always when writing Ansible playbooks. 

Tools

Ansible-lint (with Yamllint)

https://github.com/ansible-community/ansible-lint

A lint for ansible. Its main goal is to promote proven practices, patterns, and behaviors while avoiding common pitfalls that can easily lead to bugs or make code harder to maintain.

Install:

# Assuming you already installed Ansible and you also want the optional
# yamllint support:
pip3 install "ansible-lint[yamllint]"

# If you want to install and use the latest Ansible (w/o community collections)
pip3 install "ansible-lint[core,yamllint]"

# If you want to install and use the latest Ansible with community collections
pip3 install "ansible-lint[community,yamllint]"

# If you want to install an older version of Ansible 2.9
pip3 install ansible-lint "ansible>=2.9,<2.10"


Example:

$ ansible-lint -p examples/playbooks/example.yml


Best practices on writing playbooks

Using command rather than the module

Executing a command when there is an Ansible module is generally a bad idea. Eg: using 'kubectl' to apply the K8s descriptors rather than using the ansible K8s core module.

But there can be exceptions when we have to use command or shell, when such a module is not available or is buggy.

Use shell only when shell functionality is required

The shell module should only be used when piping, redirecting, or chaining commands (and Ansible would be preferred for some of those!)


No comments:

Post a Comment