Search code examples
ansiblejinja2ansible-2.xansible-template

Ansible postgresql_query: how can I insert list variable as json type?


I have a table with the column name contacts (format Json) and the contacts API call returns the object in list format as below.

contacts: ["[email protected]", "[email protected]" ]

PSQl query code I am trying:

- name: Insert to db
  postgresql_query:
    db: xxx
    login_user: xxx
    login_password: xxx
    query: INSERT INTO test_table (id, contacts) VALUES (%s, %s)

    positional_args:
    - 1
    - '{{ contacts }}'

Error:

Invalid input syntax for type json\n LINE 1:... Token \"'\" is invalid

I believe it's some quotes issue but I couldn't figure out exactly how to pass list value to JSON type.


Solution

  • Using ascii filter along with json worked for me.

     '{{ contacts|to_json(ensure_ascii=False) }}'