unable to use set_fact in ansible

61 Views Asked by At

unable to use set_fact in ansible. please help me out

"msg": [
    "nilaj 15",
    "ajin 15"
]

- set_fact:
     name_list: "{{ name_list + item.split() | first }}" 
     priv_list: "{{ name_list + item.split() | last }}"      
  loop: "{{ user_list }}"

expected output:
name_list = [ "nilamj","ajitn" ]
priv_list = [ "15","15" ]
2

There are 2 best solutions below

0
On

If I understand correctly, you want to split an array of strings at the space character and divide it into different lists.

I would advise against implementing this as an Ansible loop and use Jinja functionality instead.

You can use the map function to apply the respective filter to each element of the entered list.

Your set_fact task would then look like this (without loop):

- set_fact:
    name_list: "{{ user_list | map('split') | map('first') }}"
    priv_list: "{{ user_list | map('split') | map('last') }}"
  1. the filter split is applied using map
  2. the first or last element of the sub-lists is extracted using map and the filter first or last.

The input:

user_list:
  - 'nilaj 15'
  - 'ajin 15'

results in this output:

name_list: ['nilaj', 'ajin']
priv_list: ['15', '15']
0
On
---
- hosts: localhost
  gather_facts: false
  vars:
    user_list:
      - 'nilaj 15'
      - 'ajin 15'
  tasks:
    - set_fact:
         name_list: "{{ name_list | d([]) + [item.split() | first] }}"
         priv_list: "{{ priv_list | d([]) + [item.split() | last] }}"
      loop: "{{ user_list }}"

    - debug: var=name_list
    - debug: var=priv_list
...

produces:

    "name_list": [
        "nilaj",
        "ajin"
    ]

    "priv_list": [
        "15",
        "15"
    ]