Write variable to a file in Ansible

前端 未结 4 714
感动是毒
感动是毒 2020-12-24 04:34

I am pulling JSON via the URI module and want to write the received content out to a file. I am able to get the content and output it to the debugger so I know the content

相关标签:
4条回答
  • 2020-12-24 04:37

    You could use the copy module, with the content parameter:

    - copy: content="{{ your_json_feed }}" dest=/path/to/destination/file
    

    The docs here: copy module

    0 讨论(0)
  • 2020-12-24 04:51

    Unless you are writing very small files, you should probably use templates.

    Example:

    - name: copy upstart script
      template: 
        src: myCompany-service.conf.j2 
        dest: "/etc/init/myCompany-service.conf"
    
    0 讨论(0)
  • 2020-12-24 04:55

    Based on Ramon's answer I run into an error. The problem where spaces in the JSON I tried to write I got it fixed by changing the task in the playbook to look like:

    - copy:
        content: "{{ your_json_feed }}"
        dest: "/path/to/destination/file"
    

    As of now I am not sure why this was needed. My best guess is that it had something to do with how variables are replaced in Ansible and the resulting file is parsed.

    0 讨论(0)
  • 2020-12-24 04:55

    We can directly specify the destination file with the dest option now. In the below example, the output json is stored into the /tmp/repo_version_file

    - name: Get repository file repo_version model to set ambari_managed_repositories=false
      uri:
        url: 'http://<server IP>:8080/api/v1/stacks/HDP/versions/3.1/repository_versions/1?fields=operating_systems/*'
        method: GET
        force_basic_auth: yes
        user: xxxxx
        password: xxxxx
        headers:
          "X-Requested-By": "ambari"
          "Content-type": "Application/json"
        status_code: 200
        dest: /tmp/repo_version_file
    
    0 讨论(0)
提交回复
热议问题