Home > database >  Add Single Quotes around a list in Ansible
Add Single Quotes around a list in Ansible

Time:04-22

I have a list of items services and each needs to be wrapped in single quotes to configure some parameters.

The simplest solution I saw posted was:

"{{services | match('quote') | join(' OR ')}}"

This only wrapped the first element in the list in a single quote but not the remaining.

I also tried some variations of match regex.

Finally I tried adding the single quote manually in the data source, then joining. The first element retained the single quotes but subsequent were stripped off? What is going on here?

Right now they are static from the inventory i.e.:

---
inventory:
  hosts:
    host1:
      procs:
      - splunkd.*
      services:
      - 'some service name'
      - 'another service name'
      - 'SplunkForwarder'

I need the end result to be

"Name='some service name' OR Name='another service name'"

Currently with the services single quoted in variable the quotes are stripped or ignored.

Result

Name=some service or Name=another service

CodePudding user response:

you could cut your problem by using loop:

  tasks:
    - name: set var
      set_fact:
        result: "{{ result | d('')   _i   _o }}"
      loop: "{{ services }}"
      loop_control:
        extended: yes
      vars:
        _i: "Name='{{ item }}'"
        _o: "{{ '' if  ansible_loop.last else ' OR ' }}"

    - name: display result
      debug:
        var: result

result:

ok: [localhost] => {
    "result": "Name='some service name' OR Name='another service name' OR Name='SplunkForwarder'"
}

with your vars:

- name: Join services   
  set_fact:     
    joined_services: "{{ joined_services | d('')   service   serviceAppend }}"     
  loop: "{{ services }}"     
  loop_control:       
    extended: yes     
  vars:
    service: "'{{ item }}'"
    serviceAppend: "{{ '' if  ansible_loop.last else ' OR ' }}"
  • Related