Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

How to POST Json file with arguments using Ansible

All

I am using Ansible to POST data on a website. I have taken a very simple example of the JSON content

{
  "test2":"{{test}}"
}

Below is snippet for ansible task responsible to POST data:

  vars:
    test: "somerandomtest"
  
  tasks:

  - name: Test
    register: json_output
    uri:
      url: "http://localhost:3000"
      validate_certs: no
      follow_redirects: none
      headers:
       Authorization: Bearer 12344
       Content-Type: application/json
      method: POST
      body_format: json
      body: " {{ lookup('file','test.json') | from_json }} "
      #body: '{"test2":" {{test}} "}'
      timeout: 600

But on the web service I see the below data, where "test" is not replaced with "somerandomtest".

{'test2': '{{test}}'}

Not sure what I am doing wrong, or maybe I am using lookup the wrong way. If I replace the body with the content everything is fine, but the real JSON I work with is 400 lines, and I want to keep it separate.

Can anyone please let me know what can I do to change the JSON data using Ansible?

question from:https://stackoverflow.com/questions/65865542/how-to-post-json-file-with-arguments-using-ansible

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The file lookup doesn't evaluate file content for Jinja template markers (which would lead to unexpected behavior if a document just happened to contain {{).

If you want to read in a template, use the template lookup instead:

- hosts: localhost
  gather_facts: false
  tasks:
  vars:
    test: "somerandomtest"
  
  tasks:

    - name: Test
      register: json_output
      uri:
        url: "https://httpbin.org/post"
        validate_certs: no
        follow_redirects: none
        headers:
          Content-Type: application/json
        method: POST
        body_format: json
        body: " {{ lookup('template','test.json') }} "
        return_content: true
        timeout: 600

    - debug:
        var: json_output

This shows that the content sent to the remote server is:

{'test2': 'somerandomtest'}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...