Search code examples
ansiblejinja2

Ansible Jinja split on backslash fails


I have a ansible play that tries to split a string in the format of domain\user into its parts:

This is the task

tasks:
    - name: do something which requires domain and user
      win_shell: echo "{{ lookup('aws_ssm', 'service_user-account-2921', decrypt=True, region='eu-central-1' )}}.split('\\')[0] }}"

This results in:

ERROR! failed at splitting arguments, either an unbalanced jinja2 block or quotes: {{'DOMAIN\USER'.split('\')[0]}}

if I change the task to remove the lookup it still fails as long as I use \ as delimiter

      #win_shell: echo "{{ 'test,strings'.split(',')[0] }}" #WORKS
      win_shell: echo "{{ 'DOMAIN\\USER'.split('\\')[0]}}" #FAILS

how to split on a backslash in ansible / jinja?


Solution

  • Q: "How to split on a backslash in ansible/jinja?"

    A: Put the separator into a variable. For example

          vars:
    
            separator: '\'
            text: 'domain\user'
    
          tasks:
    
            - debug:
                msg: "{{ text.split(separator) }}"
    

    gives

        msg:
        - domain
        - user