Search code examples
listjoinansiblejinja2

Ansible join list items into string including the quotation marks


this is probably easy but i cant figure it out

I have a simple list which i need to convert to string but i need each item in the final string to contain quotation marks

vars:
  servers:
    - ServerA
    - ServerB
    - ServerC

tasks:
  - name: Join into string
    debug:
      msg: "{{ servers | join(,) }}"

result looks like this
   "msg": "ServerA,ServerB,ServerC"

but i need to get the format

msg: '"ServerA","ServerB","ServerC"'

Solution

  • Join the items

      result: >-
        "{{ servers|join('","') }}"
    

    The debug

        - debug:
            msg: "{{ result }}"
    

    gives the expected result

     msg: '"ServerA","ServerB","ServerC"'
    

    You can write it into a file

      - copy:
          dest: /tmp/result.txt
          content: >
            "{{ servers|join('","') }}"
    

    gives

    shell> cat /tmp/result.txt 
    "ServerA","ServerB","ServerC"
    

    Example of a complete playbook for testing

    - hosts: localhost
    
      vars:
    
        servers:
          - ServerA
          - ServerB
          - ServerC
    
        result: >-
          "{{ servers|join('","') }}"
    
      tasks:
    
        - debug:
            msg: "{{ result }}"
        - copy:
            dest: /tmp/result.txt
            content: >
              "{{ servers|join('","') }}"