Reputation: 87
I'm working on my first Ansible module and I decided to automate a simple task I had a bash script for. This module looks at the kernel running vs kernel installed and lets me know to reboot in the case there is a mismatch. I've tested the code sans Ansible stuff and it should work, but the code always returns true (even if I swap the != with ==):
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()
I don't expect to take any args (well I don't think I do). Can someone give me some hints on what I'm doing wrong here?
UPDATE
I modified the basic logic flaw per that was pointed out. I'm still getting the != condition all the time even though I've tested against two machines that I know should A) REBOOT B) DO NOT REBOOT. I thought perhaps the string had extra characters so I tried stripping them. However, testing using OS I see this:
>>> 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
>>>
So I would expect the same behavior in module.run_command(). Any thoughts?
Upvotes: 0
Views: 1136
Reputation:
changed = False is always the last statement executed whether rpm_os != (or ==) uname_os --> as is "out =" and "module.exit" which you possibly don't want here either. I assume you return "changed" and not some other variable from the function. Try:
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, output=out)
Upvotes: 1