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

Ansible从文本文件读取软件包名称执行yum安装失败问题求助

Why Your Playbook Isn't Installing Packages & How to Fix It

Let's walk through what's going wrong with your current setup and get it working properly:

The Root Cause

Your playbook has a critical filter mistake: using | list on result.stdout splits the entire file content into individual characters instead of splitting it by lines. For example, your packages.txt content:

nginx
vim
grafana

Gets turned into a list like ['n','g','i','n','x','\n','v','i','m','\n','g','r','a','f','a','n','a'] when you use | list. That's why your debug and install tasks are being skipped—you're trying to install single characters as package names, which yum can't process.

On top of that, using shell: cat to read a file is overkill when Ansible has built-in modules designed for this job, which are more reliable and platform-agnostic.

Corrected Playbook

Here's the fixed version that will properly read your package list and install the software:

- hosts: localhost
  tasks:
    - name: Read the package list file
      ansible.builtin.read_file:
        path: /home/packages.txt
      register: package_file

    - name: Install packages from the list
      ansible.builtin.yum:
        name: "{{ item }}"
        state: present
      loop: "{{ package_file.content | b64decode | splitlines | reject('equalto', '') | list }}"

Breakdown of the Fixes

  1. Replace shell: cat with read_file:

    • The read_file module reads files directly and returns content as base64-encoded text (we use b64decode to get plain text). This avoids relying on shell commands like cat, which might not behave consistently across systems.
  2. Split content into valid package lines:

    • splitlines splits the file content into a list of actual lines (each line is a package name).
    • reject('equalto', '') filters out any empty lines in your file, so you don't waste time trying to install "nothing" if there are blank lines in packages.txt.
  3. Use the yum module instead of shell:

    • The yum module is idempotent—it only installs packages that aren't already present, and handles dependencies automatically. Using shell: yum install would run the command every time, even if the package is already installed, which is inefficient.

What to Expect After Running

When you execute this playbook, you'll see the install task run for each package in your list. The play recap will show changed for packages that were installed, and ok for packages that were already on your system.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:07:30