I noticed many users are using different and wrong methods to convert a list
data to string
format. You can use existing filters and functions in Ansible to achieve the same.
Here is our list
vars:
my_list:
- "apple"
- "mango"
- "orange"
Now we need to convert this to a single string with comma separated (or separated by any other character). I found users are using loops and adding to a string value but there is a simple way to do this as shown below.
- name: Concatenate a list to string
set_fact:
my_string: "{{ my_list | join(',') }}"
Find the full playbook below.
---
- name: List to String Conversion
hosts: localhost
vars:
my_list:
- "apple"
- "mango"
- "orange"
tasks:
- name: Print the List
debug:
msg: "{{ my_list }}"
- name: Concatenate a list to string
set_fact:
my_string: "{{ my_list | join(',') }}"
- name: Print the String
debug:
msg: "{{ my_string }}"
Sample execution
$ ansible-playbook site.yml
PLAY [List to String Conversion] *********************************************************************************
TASK [Gathering Facts] *******************************************************************************************
ok: [localhost]
TASK [Print the List] ********************************************************************************************
ok: [localhost] => {
"msg": [
"apple",
"mango",
"orange"
]
}
TASK [Concatenate a list to string] ******************************************************************************
ok: [localhost]
TASK [Print the String] ******************************************************************************************
ok: [localhost] => {
"msg": "apple,mango,orange"
}
PLAY RECAP *******************************************************************************************************
localhost : ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Check Ansible Real Life GitHub repository for all use cases.
Want to learn Ansible from scratch ? Check you YouTube Playlist.
Disclaimer: The views expressed and the content shared are those of the author and do not reflect the views of the author’s employer or techbeatly platform.
Gineesh Madapparambath
Gineesh Madapparambath is the founder of techbeatly and he is the author of the book - ๐๐ป๐๐ถ๐ฏ๐น๐ฒ ๐ณ๐ผ๐ฟ ๐ฅ๐ฒ๐ฎ๐น-๐๐ถ๐ณ๐ฒ ๐๐๐๐ผ๐บ๐ฎ๐๐ถ๐ผ๐ป.
He has worked as a Systems Engineer, Automation Specialist, and content author. His primary focus is on Ansible Automation, Containerisation (OpenShift & Kubernetes), and Infrastructure as Code (Terraform).
(aka Gini Gangadharan - iamgini.com)
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Leave a Reply