Ansible: check_mode

One of those cool tricks: Checking if string exists in file and then decide whether to run a command or not

- name: Check if ldap.example.com is configured
  lineinfile: 
    dest: /etc/openldap/ldap.conf
    line: "URI ldap://ldap.example.com/"
  check_mode: yes
  register: presence
  # failed_when: presence.changed # if you just want to fail/end/exit

- name: Enable LDAP PAM modules
  command: "/usr/sbin/authconfig --enableldapauth --ldapserver=ldap.example.com --ldapbasedn=ou=people,dc=example,dc=com --update"
  when: presence.changed
  register: authconfig
- debug:
    var: authconfig
  when: authconfig.changed

lineinfile will check if the string (URI ldap://ldap.example.com/) exist in the file, and if it does, nothing will happen.

But if the strings doesn't exist in the file, it will try to insert it, but because of check_mode: yes, it won't edit the file, but it will report a "changed" status and the second part will run (when: presence.changed) since a "change" was reported previously.

Here's another example: Check if firewalld is installed. If it is, then open port 22, if not, skip.

- name: Check if firewalld is installed
  package:
    name: firewalld
    state: present
  check_mode: yes
  register: is_firewalld

- name: open port 22
  firewalld:
    port: "22/tcp"
    permanent: true
    state: enabled
    immediate: yes
  when: is_firewalld is not changed

Comments:

For comments, please visit https://plus.google.com/u/0/+JefferyBagirimvano/posts/SUdP9sSFMs7