Ansible从文本文件读取软件包名称执行yum安装失败问题求助
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
Replace
shell: catwithread_file:- The
read_filemodule reads files directly and returns content as base64-encoded text (we useb64decodeto get plain text). This avoids relying on shell commands likecat, which might not behave consistently across systems.
- The
Split content into valid package lines:
splitlinessplits 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 inpackages.txt.
Use the
yummodule instead ofshell:- The
yummodule is idempotent—it only installs packages that aren't already present, and handles dependencies automatically. Usingshell: yum installwould run the command every time, even if the package is already installed, which is inefficient.
- The
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

