Giter Club home page Giter Club logo

ansible-best-practices's Introduction

Ansible Best Practices

A collection of notes on Ansible best practices…​

Version Control

Use git version control for your playbooks, roles, and inventory.

YAML

Ansible playbooks are first parsed as YAML and then processed. This is important to keep in mind as errors may occur both during YAML parsing or during playbook execution.

Use Block Quotes

Block quotes help avoid long lines. The >- operator converts line breaks to spaces. The |- operator keeps newlines.

# Need a better example... this should use lineinfile...
- name: Add envirnoment variables
  blockinfile:
    block: |-
      MYAPP_DOMAIN=example.com
      MYAPP_DIR=/opt/myapp
- name: Run Installer Script
  command: >-
    installer.sh
    --config=example/config/path
    --domain=app23.example.com
    --enable-advanced-features
    --admin-password={{ admin_password | quote }}
  args:
    creates: /etc/example/install.log
- name: Deployment for MyApp
  k8s:
    state: present
    definition: "{{ myapp_deployment }}"
  when: >-
    myapp_install_k8s|bool or
    myapp_install_openshift|bool

Idempotence

Levels of code quality:

  • Ansible code works once, cannot re-run

  • Check if code has run, avoids reconfiguring

  • Checks can reset, reconfigure

  • Reconfiguration properly indicates changes

Inventory

Use an inventory directory

Ansible may be pointed to an inventory directory and will load all inventories found within the inventory directory.

Use group_vars

Avoid host_vars

Hosts should normally be grouped to specify the purpose assigned to each host. Even if there is only one host in a group, use of groups still provides clarity.

Separate inventories for similar environments with common group_vars

This provides a simple way to separate environment specific variables from the common variables.

Separate environments by inventory.

Group Naming

Name groups with obvious names that describe the function of the groups.

Playbook

Name your plays

Naming everything is best practice because it lets you track down errors faster.

Avoid group_vars and host_vars?

Using group_vars and host_vars in a playbook requires strict rules of ansible group naming which are best avoided. It is better practice to have variables for host and group names when a playbook needs different handling depending on the host or host group. If sets of variables need to be set based on group, try using include_vars instead using a check on the hosts groups (group_names special variable).

- name: Include Database Host Vars
  when: myplaybook_database_group_name in group_names
  include_vars:
    dir: vars/database/

Roles

Start structuring your playbooks around use of Ansible roles early in your development process. Role directory structure provides a standard for tasks, files, templates, modules, etc.

Tasks

Name your tasks

On every task, always include name.

User verbosity with debug tasks

Error Handling

Do not ignore_errors. Using ignore_errors still reports an error and is often confusing.

Use failed_when instead. Using failed_when allows you to give your own error conditions.

Fail early with assert and fail

Using fail:

- name: Check for valid url
  fail:
    msg: Invalid url: {{ myapp_url }}
  when: >-
    not myapp_url.startswith('https://') or
    not myapp_url is search('/myapp/')

Using assert:

- name: Assert valid url
  assert:
  - myapp_url.startswith('https://') or
  - myapp_url is search('/myapp/')

command module

  • Use sparingly

  • Use quote filter with variables

  • Calling shell scripts from command?

    • Template shell script and copy to host

  • Don’t call ansible or ansible-playbook from command

  • Use args:

    • chdir Set working directory for command

    • creates Only run if file does not exist

    • removes Only run if file exists

    • warn Use to disable warnings when needed

shell module

Only use shell if you cannot use command

Avoid echo to pass input to commands, the command and shell modules both have built-in support for passing standard input.

Variables

Avoid set_fact unless it is a fact about the host

Set vars on include_tasks or include_role instead.

Include all variables for configuration in defaults/main.yml

Process variables in vars/main.yml

Prefix Variable Names

myapp_version: latest
myapp_openshift_image: quay.io/myorg/myapp:{{ myapp_version }}
myapp_openshift_dev_nampsace: mapp-dev

When registering variables, use r_ prefix.

Testing

Lookup Plugins

Use env for environment variables

Disable use of dangerous lookups

For example, pipe

FIXME - I believe you can provide a custom do-nothing version of plugins, but need to verify.

Filters

Ansible provides a number of filters in addition to the core jinja2 filters.

Use bool to evaluate boolean expressions

Use default filter if a value may not be set

Use json_query filter to process complex data structures

The json_query filter uses the powerful JMESPath query language:

Use quote filter on commands

Use to_json filter in generated YAML

Custom Modules

Custom modules are faster than running multiple tasks and are often easier. Python programming for modules is not as hard as you may think. To start, you can add a library folder to your module, then create your python code. Should follow this document. The name of the python file, can then be utilized within your ansible-playbook.

Templating with Jinja2

Ansible lets you use jinja2 templating anywhere. Ansible Jinja2 Templating.

Template indentation

Render a new format from data structure

{{ some_variable | to_nice_json(indent=2) }}
{{ some_variable | to_nice_yaml(indent=8) }}

ansible-best-practices's People

Contributors

jkupferer avatar swarred avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.