This tutorial explores the split function in Ansible and understands its workings using real-world examples.
Prerequisites:
To follow along with this post, ensure that you have the following:
- Familiarity with Ansible playbooks and tasks
- Installed Ansible on your machine
Ansible Split Function
In Ansible, the split() function allows us to divide or split a string into a list using a specified delimiter.
The function accepts two main parameters:
- The string that you wish to split
- The delimiter on which you wish to split the string
The syntax is as follows:
Examples:
Let us cover some basic examples of using this function in a real-world playbook.
Example 1: Basic Splitting
Suppose we have a “MySQL, PostgreSQL, SQL Server,” string and we want to split it into a list of databases. We can run the playbook as follows:
- hosts: localhost
tasks:
- name: Basic split example
debug:
msg: "{{ 'MySQL, PostgreSQL, SQL Server' | split(',') }}"
Output:
"msg": [
"MySQL",
" PostgreSQL",
" SQL Server"
]
}
Example 2: Dynamic Variable Splitting
Often, we might need to split a variable value rather than a hard-coded string. This is where we can use the dynamic variable splitting as demonstrated in the following:
- hosts: localhost
vars:
users: "user1,user2,user3"
tasks:
- name: Splitting variable value
debug:
msg: "{{ users | split(',') }}"
Result:
"msg": [
"user1",
"user2",
"user3"
]
}
Example 3: Splitting File Paths
Another use of the split function is in the processing of file paths. An example demonstration is as follows:
- hosts: localhost
vars:
path: "/home/ubuntu/documents/report.txt"
tasks:
- name: Extract filename from path using the 'last' filter
debug:
msg: "{{ (path | split('/')) | last }}"
Output:
"msg": "report.txt"
}
This extracts the “report.txt” from the given path.
Example 4: Using Split in Loop
Let’s take an example where we want to create multiple directories that are named after different databases:
- hosts: localhost
vars:
databases: "MySQL, PostgreSQL, SQL Server"
tasks:
- name: Create directories for each database
file:
path: "/tmp/{{ item }}"
state: directory
loop: "{{ databases | split(',') }}"
Output:
changed: [localhost] => (item=MySQL)
changed: [localhost] => (item= PostgreSQL)
changed: [localhost] => (item= SQL Server)</strong>
Conclusion
You learned about the split function in Ansible. This function provides a clean way of processing and manipulating the string data.