Ansible Automation is really powerful with its filters and functions. Information technology does provide various string manipulation and formatting filters from Jinja and Python.

In this article, nosotros are going to see how to Split strings in Ansible.

Every bit you might have already guessed, Ansible provides filters/functions to ease our job.

Ansible split up  is a filter based on Python Split to split based on a character (separator)

We will encounter examples of Ansible Carve up filters with different datasets like Simple strings, Lists, Dictionaries etc.

Ansible Separate Examples

When it comes to string formatting, Splitting the cord into multiple parts based on the separator position has always been a key chemical element.

Let'southward say yous have a CSV file and yous want to convert the CSV(comma separated values) into a list of values like sequence or array like this

sarav,9876543210,[email protected] =>to=> ['sarav','9876543210','[electronic mail protected]']

Now you tin can simply use their index value to get the value like proper name, mobile or electronic mail id

Or let's imagine y'all accept a lot of business organization email IDs and you are interested in merely the domain names

[email protected] [email protected] [email protected] [email protected]

With python, you lot can simply practise information technology like this

Ansible Split

Let usa see how to do the same with Ansible at present.

Not simply ane, There are multiple ways to practice this in Ansible. hither is one more

Ansible Split

Let us go through the source lawmaking of these items and much more,  to understand the Ansible Split filter better.

Example1:  Ansible Separate Simple String

Splitting a simple string in Ansible with a Dissever filter is no big job.

All you need to use is a uncomplicated split up followed past the cord. Here is a quick example

--- - proper name: Ansible Divide Examples   hosts: localhost   tasks:     - name: Split Simple String Example       debug: msg={{ '[electronic mail protected]'|split('@')}}

Here is the execution and the output

I know this is a really elementary example. Move on to some real-fourth dimension examples down beneath.

Example2:  Ansible Divide with loop – To process list of strings

In this example, we have a list of e-mail IDs stored in a variable called emails  which is beingness sent to the loop iteration

For those who are familiar with with_items you tin use that too. Each element on the list can exist accessed past the variable particular

the detailvariable is existence used within the debug msgstatement where we are applying the splitbeyond each email ID

The result of the split would be a list with 2 items.  which can exist accessed using Ansible special filters beginning and concluding

  • starting time is to get the first element of the list more similar list[0]
  • last is to get the last element of the list more like list[-1] or list[len(list)-1]

In our instance, we know prior that in that location would exist only 2 values in the returned list of split. so nosotros tin can apply the last here to get the domain names every bit our seperator is @

--- - name: Ansible Split Examples   hosts: localhost   vars:     - emails: ['[email protected]', '[e-mail protected]', '[email protected]', '[e-mail protected]', '[email protected]']   tasks:     - name: print simply domain Names from Email IDs with Split       debug: msg="{{ item | split('@') | last }}"       loop: "{{emails}}"              

Example3:  Ansible Split with Map – To process Nested Lists

Here is the source lawmaking of the second playbook

--- - name: Ansible Split up Examples   hosts: localhost   vars:     - emails: ['[e-mail protected]', '[electronic mail protected]', '[email protected]', '[email protected]', '[electronic mail protected]']   tasks:     - proper name: print simply domain names from Email IDs with Split       debug: msg={{ emails | map('split','@') | flatten | select('friction match','.+\..+$') }}

The reason we are using the map filter hither is that we want to utilise the split office on the elements of the list.  not on the list itself.

If it is a simple string that nosotros desire to split we can just do it like this

msg: "{{ '[email protected]' | split('@') | last }}"

merely our email ids are stored inside the list and in our terminal example, we have iterated over the listing emails and passed each email id to for the split processing with item

Now instead of using loop we are using Ansible Map filter

To know more almost the Ansible map refer to our dedicated article here.

flatten is used here to catechumen the list of lists ( nested lists ) into a single listing.

Ideally, the event of the map and split would exist like this, [[],[],[],[]]a Nested list/array

                "msg": [ [ "hello", "gritfy.com" ], [ "steve", "google.com" ], [ "mark", "ibm.com" ], [ "dave", "meta.com" ], [ "admin", "gritfy.in" ] ] }

and with flatten it would become similar this, A single listing with multiple values.

"msg": [ "hi", "gritfy.com", "steve", "google.com", "mark", "ibm.com", "dave", "meta.com", "admin", "gritfy.in" ]

At present our job is to get the elements matching a regex pattern *.[org|com] etc. That's, where nosotros are using select

select  is a jinja2 filter that helps usa to select the matching item from the list, with select we are going to employ another filter named match to perform the regular expression pattern matching.

Our regular expression is this .+\..+$  to select the domain from the listing. you can endeavor this pattern in regex101.com to find out what it does ( if you are new to regex)

The consequence of this second playbook would exist like this

Ansible Split

Much simpler and slap-up. everything is washed in a single line with no loop.

Example4:  Ansible Divide – With File Content

Every bit part of this example, we are going to read a file named /etc/passwd from the filesystem and process it line by line and split based on separator

--- - name: Ansible Split Examples   hosts: localhost   vars:      - usernames : []   tasks:     - proper noun: impress just domain names from Electronic mail IDs with Split       set_fact:                 usernames: '{{ usernames + [ particular | split(":") | starting time ] }}'       loop: "{{ lookup('file', '/etc/passwd').splitlines() | select('match','^(?!#)')}}"            - debug: var=usernames

we have used a few functions/filters here, allow us decode each one of them

to begin with, let us start with loop expression

"{{ lookup('file', '/etc/passwd').splitlines() | select('match','^(?!#)')}}"

Here the

  • lookup filter is used to read the content of the files
  • splitlines is to split the file content line past line
  • select filter to execute another filter to select a matching element from the sequence. ( it is different from selectattr)
  • match a filter existence executed by select. to perform regular expression matching

Hither is the output of this playbook.

Ansible Split

Conclusion

In this detailed article nearly Ansible Split. I tried to encompass not just the simple split up but also to cover how tin can you lot utilize it with dist, List etc

we take also talked about various other filters and topics like

  • How to read a file content into Ansible split into lines
  • Selecting elements from the LIST using select
  • Regular expression pattern matching using match
  • How to use loop and iteration statements
  • How to use expressions with loop etc.

Hope y'all would find this article helpful.

gritfy

Cheers
Sarav AK

Buy Me a Coffee at ko-fi.com

Follow us on Facebook or Twitter
For more than practical videos and tutorials. Subscribe to our channel
Find me on Linkedin My Profile
For whatever Consultation or to hire u.s.a. [email protected]
If yous similar this article. Testify your Support! Buy me a Coffee.

Signup for Exclusive "Subscriber-only" Content