问题描述
如果没有安装 (rpm) 包,如何让 Ansible 执行 shell 脚本?是否可以以某种方式利用 yum 模块?
How can I make Ansible execute a shell script if a (rpm) package is not installed? Is it somehow possible to leverage the yum module?
推荐答案
我不认为 yum 模块在这种情况下会有所帮助.它目前有 3 个状态:不存在、存在和最新.由于听起来您不想实际安装或删除软件包(至少在此时),因此您需要通过两个手动步骤执行此操作.第一个任务将检查包是否存在,然后第二个任务将根据第一个命令的输出调用一个命令.
I don't think the yum module would help in this case. It currently has 3 states: absent, present, and latest. Since it sounds like you don't want to actually install or remove the package (at least at this point) then you would need to do this in two manual steps. The first task would check to see if the package exists, then the second task would invoke a command based on the output of the first command.
如果您使用rpm -q"来检查包是否存在,那么对于存在的包,输出将如下所示:
If you use "rpm -q" to check if a package exists then the output would look like this for a package that exists:
# rpm -q httpd
httpd-2.2.15-15.el6.centos.1.x86_64
如果包不存在,就这样:
and like this if the package doesn't exist:
# rpm -q httpdfoo
package httpdfoo is not installed
所以你的 ansible 任务看起来像这样:
So your ansible tasks would look something like this:
- name: Check if foo.rpm is installed
command: rpm -q foo.rpm
register: rpm_check
- name: Execute script if foo.rpm is not installed
command: somescript
when: rpm_check.stdout.find('is not installed') != -1
如果包存在,rpm 命令也会以 0 退出,如果没有找到包则以 1 退出,所以另一种可能是使用:
The rpm command will also exit with a 0 if the package exists, or a 1 if the package isn't found, so another possibility is to use:
when: rpm_check.rc == 1
这篇关于如果未安装包,如何让 Ansible 执行 shell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!