stringansibledata-manipulationsingle-quotes

How to enclose a string within single quotes in Ansible


Below is the string

ORACLE_THIN PTEST1 my$pass myhost-SCA.mybank.com:1521/OLTP445

Desired output with password enclosed in single quotes:

ORACLE_THIN PTEST1 'my$pass' myhost-SCA.mybank.com:1521/OLTP445

Below is my ansible playbook:

   - debug:
       msg: "utils.dbping string is {{ item.split()[0] ~ ' ' ~ item.split()[1] ~ ' \'' ~  item.split()[2] ~ '\' ' ~ item.split()[3] | trim }}"
     loop: 
       - ORACLE_THIN PTEST1 my$pass myhost-SCA.mybank.com:1521/OLTP445

However, i get syntax error while executing:

The offending line appears to be:

       - debug:
           msg: "utils.dbping string is {{ item.split()[0] ~ ' ' ~ item.split()[1] ~ ' \'' ~  item.split()[2] ~ '\' ' ~ item.split()[3] | trim }}"
                                                                                       ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:

Can you please suggest?


Solution

  • Since no use case description and no explanation is given, it looks just like a syntax error. You may have a look into the following example

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      tasks:
    
       - name: Quote in input
         debug:
           msg: "utils.dbping string is {{ item.split()[0] ~ ' ' ~ item.split()[1] ~ ' ' ~  item.split()[2] ~ ' ' ~ item.split()[3] | trim }}"
         loop:
           - ORACLE_THIN PTEST1 'my$pass' myhost-SCA.mybank.com:1521/OLTP445
    
       - name: Quote in output
         debug:
           msg: "utils.dbping string is {{ item.split()[0] ~ ' ' ~ item.split()[1] ~ ' ' ~  item.split()[2] | quote ~ ' ' ~ item.split()[3] | trim }}"
         loop:
           - ORACLE_THIN PTEST1 my$pass myhost-SCA.mybank.com:1521/OLTP445
    

    resulting into an output of

    TASK [Quote in input] ************************************************************************
    ok: [localhost] => (item=ORACLE_THIN PTEST1 'my$pass' myhost-SCA.mybank.com:1521/OLTP445) =>
      msg: utils.dbping string is ORACLE_THIN PTEST1 'my$pass' myhost-SCA.mybank.com:1521/OLTP445
    
    TASK [Quote in output] ************************************************************************
    ok: [localhost] => (item=ORACLE_THIN PTEST1 my$pass myhost-SCA.mybank.com:1521/OLTP445) =>
      msg: utils.dbping string is ORACLE_THIN PTEST1 'my$pass' myhost-SCA.mybank.com:1521/OLTP445
    

    In both cases the desired one.

    Further Documentation