【发布时间】:2021-03-30 01:23:57
【问题描述】:
我正在通过 URI 模块提取 JSON,并希望将接收到的内容写入文件。我能够获取内容并将其输出到调试器,因此我知道已收到内容,但我不知道编写文件的最佳做法。
【问题讨论】:
标签: file ansible-playbook
我正在通过 URI 模块提取 JSON,并希望将接收到的内容写入文件。我能够获取内容并将其输出到调试器,因此我知道已收到内容,但我不知道编写文件的最佳做法。
【问题讨论】:
标签: file ansible-playbook
来自tmoschou的重要评论:
As of Ansible 2.10, The documentation for ansible.builtin.copy says:
If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content
field will result in unpredictable output.
有关更多详细信息,请参阅 this 和 explanation
原答案:
您可以使用copy 模块,带有content 参数:
- copy: content="{{ your_json_feed }}" dest=/path/to/destination/file
这里的文档:copy module
【讨论】:
template: 模块并用运行时注册的变量填充它。
shahash /path/to/file 形式的 sha256 总和文件时效果更好(注意之间有 2 个空格),然后从命令行(通过 sha256sum -c shafile )验证您通过 Ansible 生成的内容.
ansible.builtin.copy 的文档说:如果您需要在复制的文件中进行变量插值,请使用 ansible.builtin.template 模块。在content 字段中使用变量将导致不可预知的输出。 有关更多详细信息,请参阅github.com/ansible/ansible/issues/50580 和github.com/ansible/ansible/issues/34595#issuecomment-356091161 的解释
根据 Ramon 的回答,我遇到了一个错误。我尝试编写的 JSON 中的空格问题通过将 playbook 中的任务更改为如下所示来解决:
- copy:
content: "{{ your_json_feed }}"
dest: "/path/to/destination/file"
到目前为止,我不确定为什么需要这样做。我最好的猜测是它与如何在 Ansible 中替换变量以及解析结果文件有关。
【讨论】:
除非您要编写非常小的文件,否则您可能应该使用templates。
例子:
- name: copy upstart script
template:
src: myCompany-service.conf.j2
dest: "/etc/init/myCompany-service.conf"
【讨论】:
我们现在可以使用dest 选项直接指定目标文件。在下面的示例中,输出的 json 存储在 /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
【讨论】: