Ansible - passing JSON string in environment to shell module

后端 未结 2 2054
谎友^
谎友^ 2020-12-10 19:20

I am trying to pass JSON string in environment.

- name: Start {{service_name}}
  shell: \"<> --server.port={{service_por         


        
相关标签:
2条回答
  • 2020-12-10 20:14

    There is a thing about Ansible template engine.
    If a string seems like an object (starts with { or [) Ansible converts it into object. See code.

    To prevent this, you may use one of STRING_TYPE_FILTERS:

    - SPRING_APPLICATION_JSON: "{{ {'test-host.1':test_host_1,'test-host.2':test_host_2} | to_json }}"
    

    P.S. this is why hack with space character from @techraf's answer works: Ansible misses startswith("{") comparison and don't convert string to object.

    0 讨论(0)
  • 2020-12-10 20:18

    Quick hack: add a space to the variable definition (after the first single quote) - a single space doesn't influence the actual variable value (space will be ignored):

    - name: Start {{service_name}}
      shell: "<<starting springboot jar>> --server.port={{service_port}}\""
      environment:
        - SPRING_APPLICATION_JSON: ' {"test-host.1":"{{test_host_1}}","test-host.2":"{{test_host_2}}"}'
    

    With the space Ansible passes to shell (test1, test2 are values I set):

    SPRING_APPLICATION_JSON='"'"' {"test-host.1":"test1","test-host.2":"test2"}'"'"'
    

    Without the space:

    SPRING_APPLICATION_JSON='"'"'{'"'"'"'"'"'"'"'"'test-host.2'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'test2'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'test-host.1'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'test1'"'"'"'"'"'"'"'"'}'"'"'
    

    Order is reversed too. Seems like without a space it interprets the JSON, with the space as string.

    I don't really get why it happens so...

    0 讨论(0)
提交回复
热议问题