使用Ansible community.general.xml模块的XPath配置问题求助
问题分析与修正方案
你的XML文件包含命名空间(xmlns="http://www.pulseway.com/linuxconfig"),这是导致XPath匹配失败的核心原因;另外添加子节点的语法也不符合Ansible xml模块的要求。下面是针对三个任务的修正:
1. 填充Account的Password属性
原XPath未包含根节点config,也未处理命名空间。修正后:
- name: 设置Account的Password属性 community.general.xml: path: /etc/pulseway/config.xml namespaces: pw: http://www.pulseway.com/linuxconfig xpath: /pw:config/pw:Account attribute: Password value: "SecretSquirrel" state: present
- 用
namespaces参数定义命名空间前缀pw,XPath中所有节点都要加上这个前缀 - 直接匹配唯一的
Account节点即可,无需额外过滤条件(若存在多个Account节点,再用[@Username='']筛选)
2. 删除MonitoredServices下的所有子节点
同样需要处理命名空间,修正后:
- name: 删除MonitoredServices下的所有子节点 community.general.xml: path: /etc/pulseway/config.xml namespaces: pw: http://www.pulseway.com/linuxconfig xpath: /pw:config/pw:MonitoredServices/* state: absent
- 用
pw:前缀匹配所有节点,*代表MonitoredServices下的所有子节点
3. 添加自定义Service子节点
原add_children的写法错误,不能将属性拼接成字符串,需按字典格式定义每个元素及其属性:
- name: 向MonitoredServices添加自定义Service节点 community.general.xml: path: /etc/pulseway/config.xml namespaces: pw: http://www.pulseway.com/linuxconfig xpath: /pw:config/pw:MonitoredServices add_children: - Service: Name: "chronyd.service" DisplayName: "ChronyD" IsDaemon: "true" DaemonType: "SYSTEMD" Path: "" StartParameters: "" CanBeStopped: "true" Enabled: "true" - Service: Name: "firewalld.service" DisplayName: "FirewallD" IsDaemon: "true" DaemonType: "SYSTEMD" Path: "" StartParameters: "" CanBeStopped: "true" Enabled: "true" - Service: Name: "postfix.service" DisplayName: "Postfix" IsDaemon: "true" DaemonType: "SYSTEMD" Path: "" StartParameters: "" CanBeStopped: "true" Enabled: "true" - Service: Name: "sshd.service" DisplayName: "SSHD" IsDaemon: "true" DaemonType: "SYSTEMD" Path: "" StartParameters: "" CanBeStopped: "true" Enabled: "true"
- 每个
Service是一个字典,key为元素名,value为该元素的属性键值对 - 确保所有属性值的引号格式正确,无需额外嵌套引号
关键知识点补充
- XML命名空间:当XML根节点有
xmlns属性时,所有子节点都属于这个命名空间,XPath必须通过前缀指定,否则无法匹配 - Ansible xml模块的
add_children要求每个子节点用字典结构定义,元素名为key,属性为嵌套字典
内容的提问来源于stack exchange,提问作者S. Kent
相关产品推荐
相关产品推荐

