为什么我的Ansible模块不会返回正确的结果

时间:2015-10-15 23:22:52

标签: python ansible

我正在开发我的第一个Ansible模块,我决定自动执行一个简单的任务,我有一个bash脚本。这个模块查看内核运行vs内核安装,让我知道在不匹配的情况下重启。我已经测试了代码没有Ansible的东西,它应该工作,但代码总是返回true(即使我交换!=与==):

import os

def main():
        module = AnsibleModule(
                argument_spec = dict()
        )

        (rc, uname_os, stderr) = module.run_command("uname -r")
        (rc, rpm_os, stderr) = module.run_command("rpm -q --last kernel | perl -pe 's/^kernel-(\S+).*/$1/' | head -1 | sed -e 's/^[ \t]*//' | sed 's/ //g'")

        if rpm_os.rstrip() != uname_os.rstrip():
                out = "REBOOT"
                changed = True     ## now changed is changed to True
        else:   
                out = "DO NOT REBOOT"
                changed = False

        module.exit_json(changed=changed, output=out)

from ansible.module_utils.basic import *
main()

我不希望采取任何args(我不认为我这样做)。有人能给我一些关于我在这里做错的提示吗?

更新

我修改了指出的基本逻辑缺陷。我仍然一直得到!=条件,即使我已经测试了两台机器,我知道应该A)重新启动B)不要重新启动。我想也许字符串有额外的字符所以我试图剥离它们。但是,使用操作系统测试我看到了:

>>> import os
>>> a = os.system("uname -r")
2.6.18-406.el5.centos.plus
>>> b = os.system("rpm -q --last kernel | perl -pe 's/^kernel-(\S+).*/$1/' | head -1 | sed -e 's/^[ \t]*//' | sed 's/ //g'")
2.6.18-406.el5.centos.plus
>>> a == b
True
>>> 

所以我期望在module.run_command()中有相同的行为。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

更改= False始终是执行的最后一个语句,无论是rpm_os!=(或==)uname_os - >你可能也不想要“out =”和“module.exit”。我假设您返回“已更改”而不是函数中的其他变量。尝试:

    changed = False   ## default
    out = "DO NOT REBOOT"
    if rpm_os != uname_os:
            out = "REBOOT"
            changed = True     ## now changed is changed to True
    module.exit_json(changed=changed, ouput=out)