You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible多主机文件压缩脚本条件判断报错求助

Fix: Ansible 'items is undefined' Error in Conditional with with_items

你遇到的这个错误其实是个很常见的小疏忽——with_items循环里的单个变量是单数的item,不是复数的items,这就是Ansible提示'items' is undefined的根本原因。我帮你修正了代码,同时调整了几个容易踩坑的细节:

tasks:
  - name: Create a tar.gz archive of target files
    community.general.archive:
      path: "{{ item.path }}"
      dest: "{{ item.dest }}"
      format: gz
      owner: ubuntu
    become: true
    when: item.key in inventory_hostname
    with_items:
      - {path: "/var/log/adobe/adobe.log", dest: "/tmp/adobe.log.gz", key: "adobe"}
      - {path: "/usr/local/app/applc.log", dest: "/tmp/applc.log.gz", key: "applc"}

关键修改点说明:

  1. 循环变量名修正:把所有items改成item——with_items会遍历列表里的每一项,每一次循环的当前项都是item(单数),复数的items代表整个列表,不是当前循环的元素。
  2. 简化when条件:Ansible的when参数本身支持Jinja2表达式,不需要额外套{{}},直接写item.key in inventory_hostname即可。你之前加引号的写法会把items.key当成字符串字面量去匹配,自然不会生效。
  3. 修正dest参数格式:archive模块的dest是单个输出路径,不需要写成列表(去掉前面的-),否则模块会识别错误。
  4. 规范become位置:become: true是任务级的权限提升参数,应该和name、when同级,而不是缩进在模块参数里(虽然旧写法可能不报错,但不符合Ansible的最佳实践)。

验证逻辑:

  • 对于主机vm-stg-adobe-201/vm-stg-adobe-202,inventory_hostname包含adobe,会执行第一个循环项的压缩任务;
  • 对于主机vm-stg-applc-101,inventory_hostname包含applc,会执行第二个循环项的压缩任务;
  • 没有匹配key的主机(如果有的话)会跳过这个任务。

内容的提问来源于stack exchange,提问作者Techiescorner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:12:40