I am new to Ansible(1.9.2). I want to check the current zlib version. If it is not 1.2.8 then Ansible need to install it from source.
The command which check the current zlib version is
root@node2 zlib-1.2.8]# cat /usr/local/include/zlib.h | grep "#define ZLIB_VERSION" | awk '{print $3}'
"1.2.8
My Ansible code
- name: "Check zlib version "
shell: "cat /usr/local/include/zlib.h | grep \"#define ZLIB_VERSION\" | awk '{print $3}'"
register: zlib_version
- name: "Debug result"
debug: result
- name: "Build zlib "
command: "{{ item }} chdir=/home/zlib-1.2.8"
with_items:
- "./configure --prefix=/usr/local --shared"
- make
- make install
when: "zlib_version!=1.2.8"
The debug prints "hello world"!!!
TASK: [Debug result] **********************************************************
ok: [192.168.111.81] => {
"msg": "Hello world!"
}
How do I check the shell output and run command accordingly.
I have changed debug: var=zlib_version.stdout
. It prints
TASK: [Debug result] **********************************************************
ok: [192.168.111.81] => {
"var": {
"zlib_version.stdout": "\"1.2.8\""
}
}
However, now I need to write zlib_version.stdout.find ("\"1.2.8\"") == -1
, twice. Is there an easy way so that Ansible skip all command,shell and unarchive when it matches zlib_version.stdout.find ("\"1.2.8\"") == -1
?
- name: "Check zlib version "
shell: "cat /usr/local/include/zlib.h | grep \"#define ZLIB_VERSION\" | awk '{print $3}'"
ignore_errors: true
register: zlib_version
- unarchive: src=/home/files/nigex/zlib-1.2.8.tar.gz dest=/home/
when: zlib_version.stdout.find ("\"1.2.8\"") == -1
- name: "Debug result"
debug: var=zlib_version.stdout
- name: "Build zlib "
command: "{{ item }} chdir=/home/zlib-1.2.8"
with_items:
- "./configure --prefix=/usr/local --shared"
- make
- make install
when: zlib_version.stdout.find ("\"1.2.8\"") == -1
The output of shell command is available through stdout
property. So zlib_version.stdout
will give you the output of the command.
- name: "Debug result"
debug: var=zlib_version.stdout
A simple role can be created to avoid writing the condition twice. Something like this:
# file roles/zlib/tasks/main.yml
---
- unarchive: src=/home/files/nigex/zlib-1.2.8.tar.gz dest=/home/
- name: "Build zlib "
command: "{{ item }} chdir=/home/zlib-1.2.8"
with_items:
- "./configure --prefix=/usr/local --shared"
- make
- make install
Then include the role only when the condition is true.
# pre_tasks is needed instead of tasks since this needs to be run before the role is included
pre_tasks:
- name: "Check zlib version "
shell: "cat /usr/local/include/zlib.h | grep \"#define ZLIB_VERSION\" | awk '{print $3}'"
ignore_errors: true
register: zlib_version
roles:
- { role: zlib, when: "zlib_version.stdout.find ('\"1.2.8\"') == -1" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With