如何使用Ansible的lineinfile模块生成JSON格式内容?
解决方案
要生成标准JSON格式的进度文件,你可以替换原来的lineinfile模块用法,改用copy模块配合Ansible的JSON处理能力,以下是两种可行的修改方案:
方案1:直接构造JSON字符串写入文件
替换你playbook中的Save progress任务为以下内容:
- name: Save progress as JSON delegate_to: localhost copy: content: | {"progress":"{{ progress_result.stdout }}","step":"{{ message_result.stdout }}"} dest: "{{ playbook_dir }}/scheduler/plan.json" force: yes
force: yes确保每次执行都会覆盖现有文件,更新最新进度信息- 建议将文件名从
plan.yaml改为plan.json,匹配文件实际格式
方案2:使用Ansible的to_json过滤器(更易扩展)
如果后续需要增加更多字段,用字典构造数据再转JSON的方式更易维护:
- name: Save progress as JSON delegate_to: localhost copy: content: "{{ {'progress': progress_result.stdout, 'step': message_result.stdout} | to_json }}" dest: "{{ playbook_dir }}/scheduler/plan.json" force: yes
这种方式通过字典定义结构,再转为标准JSON格式,避免手动拼接字符串可能出现的格式错误。
额外优化:简化变量设置
你原来的两个shell任务只是输出固定值,完全可以用set_fact直接设置变量,无需调用shell:
- name: Set progress and step variables delegate_to: localhost set_fact: progress_value: "10" step_message: "update docker script"
之后在保存任务中直接引用{{ progress_value }}和{{ step_message }}即可。
完整修改后的Playbook
- name: The module that Set the progress and details block: - name: Set progress and step variables delegate_to: localhost set_fact: progress_value: "10" step_message: "update docker script" - name: Save progress as JSON delegate_to: localhost copy: content: "{{ {'progress': progress_value, 'step': step_message} | to_json }}" dest: "{{ playbook_dir }}/scheduler/plan.json" force: yes
执行后,你会得到符合要求的JSON文件:
{"progress":"10","step":"update docker script"}
内容的提问来源于stack exchange,提问作者zccharts
相关产品推荐
相关产品推荐

