Introduction

In the realm of Ansible automation, managing variables effectively can save time and reduce errors. A lesser-known but powerful feature is using JSON files with the --extra-vars option to pass parameters to your playbooks. This approach is particularly handy when testing multiple parameters without altering global configurations, such as those stored in group_vars or host_vars.

This article explains how to define --extra-vars as JSON, streamlining your workflow and maintaining version control hygiene.


The Basics: --extra-vars

Ansible allows variables to be overridden on the command line using the --extra-vars option. The most common method is passing a space-separated list of key=value pairs. However, for extensive variables, this can become unwieldy and error-prone. JSON files provide a clean and structured alternative.


Example Playbook

Consider the following simple playbook, main.yml:

---
- hosts: localhost
  connection: local
  vars:
    var1: "var1 set in playbook"
    var2: "var2 set in playbook"
    var3: "var3 set in playbook"

  tasks:
  - name: Print var1
    debug:
      var: var1

  - name: Print var2
    debug:
      var: var2

  - name: Print var3
    debug:
      var: var3

When executed, the variables output their default values:

$ ansible-playbook -i localhost, -v main.yml

Overriding Variables

To override variables, use --extra-vars:

$ ansible-playbook -i localhost, -v main.yml --extra-vars "var2='new value' var3='another new value'"

The output reflects the overridden values. However, this method becomes cumbersome with many variables.


Using JSON for --extra-vars

Instead of typing variables inline, create a JSON file, params.json:

{
  "var1": "value from JSON",
  "var2": "another value from JSON",
  "var3": "final value from JSON"
}

Run the playbook with:

$ ansible-playbook -i localhost, -v main.yml --extra-vars "@params.json"

Here, @params.json tells Ansible to load the variables from the specified file.

Output Example

The playbook uses the values defined in params.json, ensuring consistency and readability:

TASK [Print var1] ********************************
ok: [localhost] => {
    "var1": "value from JSON"
}

Advantages of JSON --extra-vars

  • Readability: Clearly organized parameters.
  • Reusability: Easily switch parameter sets by swapping JSON files.
  • Error Reduction: Minimizes typos and formatting issues.
  • Version Control: Exclude JSON files from commits using .gitignore.

Best Practices

  1. Default to group_vars: Use playbooks' default variables for standard operations.
  2. Isolate Edge Cases: Use --extra-vars for testing or temporary changes.
  3. Secure Sensitive Data: Encrypt JSON files with ansible-vault when containing credentials.

Conclusion

Leveraging JSON for --extra-vars simplifies testing and enhances Ansible’s versatility. Adopt this practice to maintain clean version control and focus on developing robust automation solutions.

Happy Automating!