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

如何让Ansible lineinfile模块对所有主机生效并写入主机信息?

问题分析与修复方案

你的Playbook仅对单台主机生效,是几个细节错误导致的,以下是具体问题点和修正后的实现:

核心问题

  • 主机名变量错误:ansible_host_var不是Ansible内置变量,无法正确获取主机标识,需替换为inventory_hostname(清单中定义的主机名)或ansible_host(实际连接的主机地址)。
  • Debug消息逻辑颠倒:当2023不存在时,输出的消息却是“2023 exist”,完全不符合判定逻辑。
  • 文件创建缺失:若output.txt不存在,lineinfile模块会直接报错,需添加create: yes参数确保文件不存在时自动创建。

修正后的Playbook

---
- name: Check for 2023 in zdump output
  hosts: all
  tasks:
    - name: Run zdump command
      command: zdump -v Asia/Tehran
      register: zdump_output
      ignore_errors: yes 

    - name: Check if 2023 exists in the output
      set_fact:
        is_2023_exists: "{{ '2023' in zdump_output.stdout }}"

    - name: Display message if 2023 does not exist
      debug:
        msg: "2023 does NOT exist in zdump output on {{ inventory_hostname }}."
      when: not is_2023_exists

    - name: Save host info to output.txt on localhost
      lineinfile:
        path: /home/fshamsian/output.txt
        line: "{{ inventory_hostname }}: 2023 did not exist"
        create: yes  # 文件不存在时自动创建
      delegate_to: localhost
      when: not is_2023_exists

额外说明

  • inventory_hostname直接对应你Ansible清单里定义的主机名称,确保写入文件的主机标识和清单一致。
  • ignore_errors: yes会忽略zdump命令的执行错误(如时区不存在、命令未找到等),若需要排查这类问题,可移除该参数或添加针对性错误处理。
  • lineinfile模块会自动确保每台符合条件的主机仅写入一行,不会重复添加相同内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 13:00:11