Ansible

Ansible Dictionary

Ansible is a powerful configuration management, deployment, and orchestration tool that simplifies complex DevOps tasks. One of the critical features of Ansible is its use of YAML to express configurations, playbooks, and data structures including dictionaries.

In the development world, a dictionary is a collection of key-value pairs where each key must be unique. Ansible offers a similar feature that allows us to define the dictionary data for organized and structural formatting.

In this tutorial, we will learn how to create and use the Ansible dictionaries to define the data within Ansible playbooks.

What Is an Ansible Dictionary?

An Ansible dictionary is analogous to dictionaries in programming languages like Python. It’s a way to store the data where a unique key identifies each piece of the data. The key-value pairs are represented in the “key:value” format.

An example of an Ansible dictionary is as follows:

server:
  identifier: node1
  tag: database
  endpoint: us-east-1

Here, the server is a dictionary that contains three key-value pairs: identifier, tag, and endpoint.

Working with Ansible Dictionaries

Declaring the Ansible Dictionaries

The previous example quickly demonstrated how to declare an Ansible dictionary in a simple format.

Another example is as follows:

servers:
  web: 192.168.1.10
  db: 192.168.1.11
  cache: 192.168.1.12

Accessing the Dictionary Values

Once we define a dictionary in Ansible, we can access the dictionary’s values using the associated key names.

An example is as follows:

---
- hosts: localhost
  vars:
    server:
      name: node1
      tag: database
      endpoint: us-east-1
  tasks:
    - debug:
        msg: "Server environment is {{ server.endpoint }}"

Nested Dictionaries

As you can guess, we can also create nested dictionaries which are dictionaries within other dictionaries. Consider the following example demonstration:

servers:
  node1:
    tag: database
    endpoint: us-east-1
  node2:
    tag: backup
    endpoint: eu-central-2

Creating a Dict Using the Dict Function

Ansible also allows us to define a dictionary using the dict function. This is similar to the Python dict function as demonstrated in the following example:

- name: Create a dictionary with the dict function
  debug:
    msg: "{{ dict([[1, 2], ['a', 'b']]) }}

Conclusion

Dictionaries are fundamental structures in Ansible which provides a way to organize and represent the data. Their flexibility and compatibility with various features make them critical to the Ansible playbook and role design.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list