Ansible task executed if file not exists condition

In this post, I will share an ansible task that is executed only if a condition is matched, the condition here is to check if file NOT exists on the system.

---
- name: run the playbook tasks on the localhost
  hosts: 127.0.0.1
  connection: local
  become: yes

  vars:
    vhost_domain: "wpdemo.com"

  tasks:

  - name: ensure aptitude is installed
    command: echo "Hello World"

  - name: Nginx wordpress vhosts
    template:
      src: "templates/wp-vhost.conf.j2"
      dest: "/etc/nginx/sites-enabled/{{ vhost_domain }}.conf"

  - name: Mkdir directory /var/www/{{ vhost_domain }}
    file:
      path: "/var/www/{{ vhost_domain }}"
      state: directory

  - name: Is wp installed by checking wp-config.php
    stat: path="/var/www/{{ vhost_domain }}/wp-config.php"
    register: wp_installed

  - name: Download WP
    shell: cd "/var/www/{{ vhost_domain }}/" && rm -f latest.tar.gz && wget https://wordpress.org/latest.tar.gz && tar -xzvf latest.tar.gz && mv wordpress/* . && rm -Rf wordpress/ && chown -R www-data:www-data ../{{ vhost_domain }}
    when: wp_installed.stat.exists == False

Ansible playbook create a new nginx vhost by template for wp at nginx proxy, then install wordpress latest if wp-config.php is not exists

if wp-config.php exists, the task Download WP is skipping.

Happy reading!


Also published on Medium.

Leave a Reply

Your email address will not be published. Required fields are marked *