centos 为什么Ansible任务失败而没有给出任何错误?

t3psigkw  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(172)

我有一个Ansible任务在RHEL和CentOS机器上运行。

- name: Git version (Fedora)
  command: rpm -qi git
  args:
    warn: no
  register: fedora_git
  tags:
    - git

但是这个任务失败了,没有任何错误。

FAILED! => {"changed": true, "cmd": ["rpm", "-qi", "git"], "delta": "0:00:00.066596", "end": "2023-05-23 01:28:16.302918", "msg": "non-zero return code", "rc": 1, "start": "2023-05-23 01:28:16.236322", "stderr": "", "stderr_lines": [], "stdout": "package git is not installed", "stdout_lines": ["package git is not installed"]}

尝试使用shell模块,但得到相同的错误。

xzv2uavs

xzv2uavs1#

在Ansible中,通常建议使用任务特定模块,而不是commandshell(如果可用且可能)。在您的情况下,package_facts module,以获得包信息作为事实。
最小化示例剧本

---
- hosts: test
  become: false
  gather_facts: false

  tasks:

  - name: Gather the package facts
    ansible.builtin.package_facts:
      manager: auto

  - name: Show Facts
    ansible.builtin.debug:
      msg: "{{ ansible_facts.packages }}"

  - name: Print the package names only
    ansible.builtin.debug:
      msg: "{{ ansible_facts.packages | dict2items | map(attribute='key') }}"

将导致已安装软件包的列表输出,或类似

- name: Show Git Facts
    ansible.builtin.debug:
      msg: "{{ ansible_facts.packages.git }}"
    when: ansible_facts.packages.git is defined # means installed

将导致输出

TASK [Show Git Facts] ******
ok: [localhost] =>
  msg:
  - arch: x86_64
    epoch: null
    name: git
    release: 24.el7_9
    source: rpm
    version: 1.8.3.1

对于其他格式和信息,您需要做进一步的调整。

  • 但是这个任务是在没有任何错误的情况下获取FAILED。...尝试使用shell模块,但得到相同的错误。*

正确,这是查询本地包数据库以获取未安装的包和caused by Return Code (RC)信息的预期行为和结果。
其中一个命令像

rpm -qi git; echo $?
Name        : git
Version     : 1.8.3.1
Release     : 24.el7_9
Architecture: x86_64
Install Date: Fri 14 Apr 2023 11:04:29 AM CEST
Group       : Development/Tools
Size        : 23265551
License     : GPLv2
Signature   : RSA/SHA256, Wed 22 Feb 2023 09:30:47 AM CET, Key ID 199e2f91fd431d51
Source RPM  : git-1.8.3.1-24.el7_9.src.rpm
Build Date  : Tue 21 Feb 2023 05:26:24 PM CET
Build Host  : x86-vm-37.build.eng.bos.redhat.com
Relocations : (not relocatable)
Packager    : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla>
Vendor      : Red Hat, Inc.
URL         : http://git-scm.com/
Summary     : Fast Version Control System
Description :
Git is a fast, scalable, distributed revision control system with an
unusually rich command set that provides both high-level operations
and full access to internals.

The git rpm installs the core tools with minimal dependencies.  To
install all git packages, including tools for integrating with other
SCMs, install the git-all meta-package.
0

将提供软件包信息和一个"rc": 0,类似于

rpm -qi not-installed; echo $?
package not-installed is not installed
1

不会并提供"rc": 1

进一步阅读

相关问题