问题描述: 在使用Ansible的from_json过滤器时,无法使用{{ inventory_hostname }}。
解决方法:
- name: 从 JSON 文件加载数据
set_fact:
json_data: "{{ lookup('file', '/path/to/json/file.json') | from_json }}"
- name: 使用 inventory_hostname 访问主机名
debug:
msg: "主机名为 {{ inventory_hostname }}"
- name: 设置 inventory_hostname 变量
set_fact:
current_host: "{{ inventory_hostname }}"
- name: 使用 from_json 过滤器
set_fact:
json_data: "{{ json_string | from_json }}"
vars:
json_string: "{\"host\": \"{{ current_host }}\"}"
- name: 输出主机名
debug:
var: json_data.host
这样,你就可以在 JSON 字符串中使用 inventory_hostname 变量,并从中提取所需的数据。
希望以上解决方法能够帮助到你!