Ansible Best Practices: Streamlining Automation for Success

Ansible Best Practices: Streamlining Automation for Success
6 min read
14 February

In the evolving realm of DevOps and automation Ansible has emerged as a tool, for efficiently managing infrastructure and orchestrating tasks. To ensure execution of your Ansible code simplify troubleshooting and make an impact on your automation journey it is essential to follow best practices. This comprehensive guide delves into the practices for Ansible encompassing everything from code formatting to security considerations.

1. Effective Use of Whitespaces

Maintaining an easily understandable codebase is crucial for Ansible playbooks. It is advisable to use spaces of tabs, in your YAML code. Additionally enhancing readability can be achieved by adding a line before each block or task. Lets consider an example;

Wrong:

---
- hosts: all
  tasks:
    - ansible.builtin.yum:
        name: httpd
        state: latest
- ansible.builtin.debug:
        msg: "httpd successfully installed"

Correct:

---
- hosts: all
  tasks:
    - ansible.builtin.yum:
        name: httpd
        state: latest

    - ansible.builtin.debug:
        msg: "httpd successfully installed"

2. Assign a "Name" to Every Step

Ensure that every Ansible statement, whether it's a play, task, or block, has a descriptive name. Adding a name parameter provides clarity and makes your code more understandable. For instance:

Wrong:

---
- hosts: all
  tasks:
    - ansible.builtin.yum:
        state: latest
        name: httpd

Correct:

---
- name: install apache
  hosts: all
  tasks:
    - name: install apache packages
      ansible.builtin.yum:
        name: httpd
        state: latest

3. Use Human-Readable and Meaningful Names for Variables

Variables play a crucial role in Ansible for storing parameters or saving task results. Opt for human-readable and meaningful variable names to enhance code reuse and readability within your team. For example:

Wrong:

httpkeepalive: 25
webpo: 80
aaaa: 8080

Correct:

apache_max_keepalive: 25
apache_port: 80
tomcat_port: 8080

4. Use Native YAML

Utilize native YAML syntax for improved code readability. This approach facilitates error detection and allows the use of YAML linters and parsers for validation. Compare the following examples:

Wrong:

- name: install apache
  ansible.builtin.yum: apache-{{ apache_version }}
  state: present
  update_cache: yes
  disable_gpg_check: yes
  enablerepo: apache
  notify: restart apache

Correct:

- name: install apache
  ansible.builtin.yum: apache-{{ apache_version }}
  state: present
  update_cache: yes
  disable_gpg_check: yes
  enablerepo: apache
  notify: restart apache

5. Use Native Modules Against Run Commands

Prioritize native modules over command modules for increased idempotency and built-in parameter validation. While command modules (e.g., ‘shell'‘command’‘raw’, and ‘script’) are useful, they should be employed as a last resort. Consider the following transformation:

Wrong:

- name: Add repository into repo.d list
  become: true
  ansible.builtin.shell: 'echo -e "[google-chrome]\nname=google-chrome\nbaseurl=http://dl.google.com/linux/chrome/\rpm/stable/x86_64\nenabled=1\ngpgcheck=1\ngpgkey=https://dl.google.com/linux/linux_signing_key.pub" > /etc/yum.repos.d/google-chrome.repo'
  args:
  creates: /etc/yum.repos.d/google-chrome.repo
  when: ansible_os_family == 'RedHat'

Correct:

- name: Add repository into repo.d list
  ansible.builtin.yum_repository:
    name: google-chrome
    description: google-chrome repository
    baseurl: http://dl.google.com/linux/chrome/rpm/stable/x86_64
    enabled: true
    gpgcheck: true
    gpgkey: https://dl.google.com/linux/linux_signing_key.pub

6. Configure Debug Messages

When developing Ansible code, leverage ‘debug’ tasks for outputting variable content. However, to avoid excessive information at the production level, set the ‘verbosity’ parameter to ‘2’. This ensures that debug messages are visible only when explicitly needed. Consider the following example:

Wrong:

- name: message output
  ansible.builtin.debug:
    msg: "This text always displays"

Correct:

- name: message output
  ansible.builtin.debug:
    msg: "This text displays with ansible-playbook -vv"
  verbosity: 2

7. Execute Your Task with the Least Possible Privilege

Adhere to security best practices by executing tasks with the least possible privilege. Implement this by specifying ‘become: true’ at the task level rather than for the entire playbook, especially if not all tasks require root/administrator privileges. For instance:

Wrong:

---
- name: install apache
  hosts: all
  become: true
  tasks:
    - name: message output
      ansible.builtin.debug:
        msg: "This text always displays"

    - name: install apache packages
      ansible.builtin.yum:
        name: httpd
        state: latest

Correct:

---
- name: install apache
  hosts: all
  tasks:
    - name: message output
      ansible.builtin.debug:
 msg: "This text always displays"
- name: install apache packages
      ansible.builtin.yum:
        name: httpd
        state: latest
      become: true

8. Use Version Control

Implement version control using Source Code Management (SCM) platforms like GitHub, GitLab, or Bitbucket. This practice allows you to track modifications, collaborate with team members, and ensure that your execution nodes are always up-to-date.

9. Always Mention the "State" Parameter

Many Ansible modules have optional "state" parameters with implicit values. To enhance clarity in your playbooks and roles, explicitly set ‘state: present’ or ‘state: absent’ where applicable. This ensures that the intended state is explicitly defined.

10. Use Comments

Include comments (lines starting with ‘#’) to provide context and explanations for your Ansible code. Comments help others (and even your future self) understand the purpose, methodology, and significance of each statement, play, task, or variable setting.

Conclusion:

Following these Ansible command best practices sets the foundation for successful automation, ensuring code maintainability, readability, and security. By incorporating these practices into your Ansible workflows, you streamline your automation journey, making it more efficient and resilient. As you embrace the power of Ansible, a commitment to best practices empowers you to build robust and scalable automation solutions.

For any  it services, software development agency solutions visit our websites.

In case you have found a mistake in the text, please send a message to the author by selecting the mistake and pressing Ctrl-Enter.
Aman 2
Joined: 2 months ago
Comments (0)

    No comments yet

You must be logged in to comment.

Sign In / Sign Up