what s the use of % set with ansible

Hi team,

can i know the actual usage of % set with ansible

Could you please provide more context, examples, error logs, or use case? The amount of information you provided is too little to answer anything.

I am assuming you want to split a string and set the value of that to a variable, then no need to use jinja templates

---
- hosts: localhost
gather_facts: no
vars:
name: "ab:hi:je:ee"
tasks:
- name: Print variable
set_fact:
my_var: "{{ (name.split(':') | default(''))[2] }}"
- debug:
msg: "{{ my_var }}"

To further explain, {% set var =value %} will only have an effect
within that template, that does not create/update ansible variables.
So while it does 'work' , you should really only use it inside a full
jinja2 template.

@abhijeet and @brian …thanks for ur responses

@abhijeet- I was trying to remove a nth element from the array…so I have tried with popup

@brian : this is my understanding from ur tips…correct me if I am wrong
{% set var =value %}
should we consider var is used only once if we use %.?

if we use {{ set var = value }} jinja syntax, we can use it through the playbook.

can u plz give me examples for both ?

You can remove nth element like - like in following case I am removing 2nd element

  • name: Print variable
    set_fact:
    my_new_list: |
    {% set result = name.split(‘:’) %}
    {% set _ = result.pop(2) %}
    {{ result }}

Another easy solution - but you need to know value to drop before hand

  • name: Print variable
    set_fact:
    new_name: “{{ name.split(‘:’) | reject(‘search’, ‘hi’) }}”
    vars:
    name: “ab:hi:je:et”