Ansible Tasks: Create symbolic links for NGINX / Apache sites-enabled directory

Submitted by nigel on Sunday 1st July 2018
Introduction

My first blog on Ansible, and it's here because it took me so long to figure it out. Ansible documentation is excellent - but of course like everything in life, if you aren't aware of all the concepts, it's difficult to know where to look first. 

My requirement was to create symbolic links to the /etc/nginx/sites-enabled directory by looping through all the conf files in /etc/nginx/sites-available. This is equally valid for Apache servers which support the same mechanism for defining virtual hosts. I am currently building a VM for Drupal development and I am using Ansible for the configuration. 

So my solution uses the find module to capture a list of conf files in /etc/nginx/sites-available and those are then saved in register for future usage. The file module is then invoked which will use the registered conf files. Note the placeholder on the destination directory - I need to access the item path but then filter it through basename to get the value I need. The force option is required because the nginx role I use already to build out the nginx configuration creates a default link which already exists and could choke my attempt to create a link for everything in /etc/nginx/sites-available.

Code Snippet
  tasks: 
 
    # Set symlinks to nginx sites-available directory
    - name: Get a list of all vhosts
      find:
        paths: /etc/nginx/sites-available
        patterns: "*.conf"
        file_type: file
      register: find

    - name: Apply symlinks in sites-enabled
      file:
        dest: /etc/nginx/sites-enabled/{{ item.path | basename }}
        src: "{{ item.path }}"
        state: link
        force: yes
      with_items: "{{ find.files }}"
blog terms
Ansible devops nginx Apache