在Ansible中,可以使用xml module来解析XML并按XPath读取属性。下面是一个示例代码,展示了如何使用Ansible和xml module来读取XML中的属性:
- name: Read XML attribute using XPath
hosts: localhost
gather_facts: false
tasks:
- name: Read XML file
xml:
path: /path/to/xml/file.xml
content: "{{ lookup('file', '/path/to/xml/file.xml') }}"
xpath: "/root/element/@attribute"
register: xml_result
- name: Print attribute value
debug:
var: xml_result.matches[0].attrib
在上面的示例中,我们使用xml module的xml
动作来读取XML文件,并通过xpath
参数指定需要读取的属性。register
参数将结果保存到xml_result
变量中。
在最后一个任务中,我们使用debug模块来打印读取到的属性值。
请注意,你需要将/path/to/xml/file.xml
替换为你实际的XML文件路径,并根据需要调整XPath表达式和输出结果的打印方式。