In this article, we are going to learn about Ansible List. and How to create Ansible List and append items to it.
The LIST is a type in data structure and is widely used in all programming languages. It is to store a group of heterogeneous elements.
We are NOT going to talk about data structures don't worry. Our Objective is that you understand what is List before we move on to, How to use LIST in ansible.
Here is the simple image representation of a list. In this case, I have taken a list of continents
The list is easily identified with square brackets []
the data inside it can be any type like numbers, strings, objects (dictionary) etc.
If you are not new to DataStructures you might already know what index means if not do not worry. The index is simply a location of a single element in the list and it starts with zero
For example, If you want to get Australia
from the Continents list we have given above. you need to call it with its index number 6
to be specific Continents[6]
That's all with the basics.
Now let us move on to see how to use List in Ansible
How to Create List in Ansible
To create a List in Ansible. we have different ways, let us go through them with examples.
Using set_fact to create an Ansible list
As you might know, Ansible has a special directive called set_fact
to create facts. In Ansible parlance facts are variables too.
You might have seen Gathering facts
while starting the playing and this is the same fact we are talking about.
If you are new to facts and variables read this article
- name: Create a List variable and print it set_fact: Continents: ["Asia","Africa","Europe","North America","South America","Antarctica","Australia"] Countries : ['India','Japan', 'Norway', 'Netherlands', 'Switzerland', 'Germany', 'United States of America']
here we are creating new lists using set_fact
named Continents and Countries
Here is the ansible-playbook with set_fact
--- - name: Ansible List Examples hosts: localhost tasks: - name: Create a List variable and print it set_fact: Continents: ["Asia","Africa","Europe","North America","South America","Antarctica","Australia"] Countries : ['India','Japan', 'Norway', 'Netherlands', 'Switzerland', 'Germany', 'United States of America'] - name: Print the Continents debug: var=Continents - name: Print the Countries debug: var=countries
Using vars to create an Ansible list
vars are another way to create variables and the easiest way too.
--- - name: Ansible List Examples hosts: localhost vars: Continents: ["Asia","Africa","Europe","North America","South America","Antarctica","Australia"] Countries : ['India','Japan', 'Norway', 'Netherlands', 'Switzerland', 'Germany', 'United States of America']
Here is the execution output
Here is the full ansible playbook to create a list using vars
--- - name: Ansible List Examples hosts: localhost vars: Continents: ["Asia","Africa","Europe","North America","South America","Antarctica","Australia"] Countries : ['India','Japan', 'Norway', 'Netherlands', 'Switzerland', 'Germany', 'United States of America'] tasks: - name: Print the Continents debug: var=Continents - name: Print the Countries debug: var=countries
How to append new elements to Ansible List - Append
Now let us see how to add or append new elements to a List.
In the previous examples, you have seen how to create a new list and we have also created two new lists named countries
and continents
Now let us see how to append a new item to the existing list. Adding country to the existing countries variable.
Here is the Ansible playbook, to append elements to the list.
--- - name: Ansible List Examples hosts: localhost tasks: - name: Create a List variable and print it set_fact: Countries : ['India','Japan', 'Norway', 'Netherlands', 'Switzerland', 'Germany', 'United States of America'] - name: Print the Countries before adding element debug: var=Countries - name: Add new element to Countries set_fact: Countries: "{{ Countries + ['United Kingdom', 'Russia'] }}" - name: Print the Countries after adding element debug: var=Countries
We are adding two countries UnitedKingdom
and Russia
to the list
Countries: "{{ Countries + ['United Kingdom', 'Russia'] }}"
What we are basically doing here is a merge of two lists. Something like this
NewCountries = ['United Kingdom', 'Russia'] Countries = Countries + NewCountries
You can relate this with combining two python lists.
here is the output of his playbook
You can see the difference between the debug output before and after appending two new countries to the list.
Irrespective of the type of data you want to append, you are going to use the same
merge
orcombine
strategy with+ [ <data> ]
to append new elements to list
Here is one more example where we are declaring an empty list and adding a Dictionary/map to it
How to append a Dictionary or Map to an ansible List
Let's suppose we want to add these user-specific records to the list
{ "MobileNo": "9876543210", "name": "Sarav" }, { "MobileNo": "9879896210", "name": "Hanu" }
We are going to follow the +
method to add a new element to the list
In the last example, we have kept the list of strings inside the [ ]
square brackets and merged it with an existing ansible list
Now we are going to do the same, this time the data we are going to add is a dictionary/map
Here is the playbook
--- - name: Ansible List Examples hosts: localhost tasks: - name: Create a List variable and print it set_fact: UserRecords: [] - name: Print the userRecords debug: var=UserRecords - name: Add new user Records set_fact: UserRecords: '{{ UserRecords + [ {"name" : "Sarav", "MobileNo" : "9876543210" }, {"name" : "Hanu", "MobileNo" : "9879896210" } ] }}' - name: Print the userRecords after adding element debug: var=UserRecords
As you can see we are adding a dictionary of data into the userRecords
after declaring it with empty []
at the first play/task
The result of this playbook would be like this
For creating a new ansible list you can either use vars
or set_fact
as we have discussed earlier
How to append Numbers to an ansible List
As said earlier you can append any element to the ansible list with + [ <data> ]
syntax. Here is the example where we are appending numbers to a list
If you want the data you are appending to be interpreted as a number. you should not enquote it.
Just to prove that these values are taken as numbers, not as a string. we are going to use some ansible numeric filters max
and min
on them once they are added.
Here is the playbook
--- - name: Ansible List Examples hosts: localhost tasks: - name: Create a List variable and print it set_fact: Numbers: [] - name: Print the Numbers debug: var=UserRecords - name: Add new Numbers to Ansible list set_fact: Numbers: '{{ Numbers + [ 1, 2, 3, 4] }}' - name: Print the Numbers after appending debug: var=Numbers - name: find the max value debug: msg: "Biggest Number in this list is : {{ Numbers | max }}" - name: find the min value debug: msg: "Smallest Number in this list is : {{ Numbers | min }}"
Here is the execution output of this playbook for your reference
you can see the min
and max
filters are perceiving them as numbers and the Max and Min values are printed.
How to merge two Lists
As I have mentioned to append a new item to the Ansible list. we have to put the values inside the empty list with [ ]
and use +
sign to merge them
If you refer to the previous examples we have been doing the same.
In the following ansible playbook we are merging three lists together
--- - name: Ansible List Examples hosts: localhost tasks: - name: Create a Lists with Numbers, Strings and Dictionary set_fact: Numbers: [1,2,3,4] UserRecords: [ {"name" : "Sarav", "MobileNo" : "9876543210" }, {"name" : "Hanu", "MobileNo" : "9879896210" } ] Strings: ['test1','test2','test3'] - name: Merging Ansible Lists debug: msg: "{{ Numbers + Strings + UserRecords }}"
Here is the execution output of the playbook
as you can see we just used the +
to merge three lists together.
How to access items from Ansible List
Ansible List is more like a python list as I have mentioned earlier. to access items from the list you can use their positional index numbers like listname[<indexnumber>]
Here is the playbook where we are trying to use Ansible filters and the positional index numbers to access elements from the list
--- - name: Ansible List Examples hosts: localhost tasks: - name: Create a List variable and print it set_fact: Countries : ['India','Japan', 'Norway', 'Netherlands', 'Switzerland', 'Germany', 'United States of America'] - name: Print the Countries Ansible list debug: var=Countries - name: Print the first element using Index Number debug: msg: "{{Countries[0]}}" - name: Print the first element using Ansible filter debug: msg: "{{ Countries | first }}" - name: Print the third element using Index Number debug: msg: "{{Countries[2]}}" - name: Print the last element using Ansible filter - last debug: msg: "{{ Countries | last }}" - name: Print the last element using length and Index Number debug: msg: "{{ Countries [Countries | length - 1 ] }}"
Here is the execution output of this playbook
How to Apply Jinja2 Filters and Ansible Filters to List
Sometimes we might need to apply complicated filters like map
, selectattr
etc to choose the right element from our ansible list.
we have dedicated articles for each of these filters with a lot of examples, you can refer
Besides these complicated and useful filters.
There are some common filters that you can use with Ansible lists.
I have compiled some of them here for your reference
Here is the playbook
--- - name: Ansible List Examples hosts: localhost tasks: - name: Create a Lists with Numbers, Strings and Dictionary set_fact: Numbers: [1,2,3,4] Numbers2: [4,5,6,7,8] NestedList: [1,2,[3,4],5,6] UserRecords: [ {"name" : "Sarav", "MobileNo" : "9876543210", "age": "32" }, {"name" : "Hanu", "MobileNo" : "9879896210", "age" : "31" } ] Strings: ['test1','test1','test3'] - name: Ansible Min filter to find smallest number debug: msg: "{{ Numbers | min }}" - name: Ansible Max filter to find Biggest number debug: msg: "{{ Numbers | max }}" # To get the smallest value using Attribute on the list of dictionary # Finding the Youngest person - name: Filtering using Attribute and finding the Min value debug: msg: "{{ UserRecords | min(attribute='age') }}" # iterate through the list elements and get their power of 2! - name: Ansible pow filter to get the power of Number debug: msg: "{{ item | pow(2) }}" with_items: - "{{ Numbers }}" # iterate through the list elements and get their Square root - name: Ansible root filter to get the Square root debug: msg: "{{ item | root }}" with_items: - "{{ Numbers }}" # test1 duplicate be removed from the output - name: Ansible Get Unique value from the list debug: msg: "{{ Strings | unique }}" # Union of two lists, Duplicates would be removed - name: Union of two lists debug: msg: "{{ Numbers | union(Numbers2) }}" # Intersection of two lists ( finding common items present in both, unique) - name: Intersect of two lists debug: msg: "{{ Numbers | intersect(Numbers2) }}" # To get the difference of 2 lists (items in 1 that don’t exist in 2): - name: Intersect of two lists debug: msg: "{{ Numbers | difference(Numbers2) }}" # Flatten Nested List - name: Flatten the Nested Ansible List debug: msg: "{{ NestedList | flatten }}" # Shuffling the List - name: Shuffling the List to change the order debug: msg: - "{{ NestedList | shuffle }}" - "{{ Strings | shuffle }}"
Here is the output of this playbook
PLAY [Ansible List Examples] **************************************************************************************** TASK [Gathering Facts] ********************************************************************************************** ok: [localhost] TASK [Create a Lists with Numbers, Strings and Dictionary] ********************************************************** ok: [localhost] TASK [Ansible Min filter to find smallest number] ******************************************************************* ok: [localhost] => { "msg": "1" } TASK [Ansible Max filter to find Biggest number] ******************************************************************** ok: [localhost] => { "msg": "4" } TASK [Filtering using Attribute and finding the Min value] ****************************************************************************** ok: [localhost] => { "msg": { "MobileNo": "9879896210", "age": "31", "name": "Hanu" } } TASK [Ansible pow filter to get the power of Number] **************************************************************** ok: [localhost] => (item=1) => { "msg": "1.0" } ok: [localhost] => (item=2) => { "msg": "4.0" } ok: [localhost] => (item=3) => { "msg": "9.0" } ok: [localhost] => (item=4) => { "msg": "16.0" } TASK [Ansible root filter to get the Square root] ******************************************************************* ok: [localhost] => (item=1) => { "msg": "1.0" } ok: [localhost] => (item=2) => { "msg": "1.4142135623730951" } ok: [localhost] => (item=3) => { "msg": "1.7320508075688772" } ok: [localhost] => (item=4) => { "msg": "2.0" } TASK [Ansible Get Unique value from the list] *********************************************************************** ok: [localhost] => { "msg": [ "test1", "test3" ] } TASK [Union of two lists] ******************************************************************************************* ok: [localhost] => { "msg": [ 1, 2, 3, 4, 5, 6, 7, 8 ] } TASK [Intersect of two lists] *************************************************************************************** ok: [localhost] => { "msg": [ 4 ] } TASK [Intersect of two lists] *************************************************************************************** ok: [localhost] => { "msg": [ 1, 2, 3 ] } TASK [Flatten the Nested Ansible List] ****************************************************************************** ok: [localhost] => { "msg": [ 1, 2, 3, 4, 5, 6 ] } TASK [Shuffling the Ansible List to change the order] *************************************************************** ok: [localhost] => { "msg": [ [ 5, 2, 6, [ 3, 4 ], 1 ], [ "test1", "test3", "test1" ] ] } PLAY RECAP ********************************************************************************************************** localhost : ok=13 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
How to validate if the variable is a list
After learning various things about the Ansible list, we should also learn how to validate if the variable is in fact a list.
Ansible has a filter for the same type_debug
you can use it like this and it should result list
if it is a valid list.
{{ <the variable name> | type_debug }}
How to use the lists in our Ansible Playbook
As part of Playbook creation and Ansible automation, you would be working with lots and lots of ansible facts and variables and they vary in a format like dictionary
, list
etc
I have written a dedicated article that covers the list of Ansible facts and variables that you can use in your playbook and how to use them right in your playbooks
You can refer to that article for further reference.
Hope this post helps you understand the Ansible List better. Please comment if you have any questions or feedback.
If you are looking for professional support in your Ansible Automation. we are here to help you
Cheers
Sarav AK
Follow me on Linkedin My Profile Follow DevopsJunction onFacebook orTwitter For more practical videos and tutorials. Subscribe to our channel
Signup for Exclusive "Subscriber-only" Content