Ansible Playbook for setting up Nginx Virtual Hosts in Azure with multiple virtual directories in Cent OS

Here is an example ansible playbook which can be used to deploy websites with different virtual directories. When running the playbook (example – ansible-playbook nginx.yml) , the user will be prompted for entering the directory name. While finishing the plays, the website will eb able to browse like http://<ip address>/dir_name

---
- name: Prompt user to enter the website name
  hosts: all
  become: true
  vars_prompt:
   - name: "website"
     prompt: "enter the website name"
     private: no #show typed value
  tasks:
   - name: Install nginx - add repo
     yum:
      name: epel-release
      state: present
   - name: Install nginx package
     yum:
      name: nginx
      state: present
   - name: Start NGiNX
     service:
      name: nginx
      state: started
   - name: create all folders for the website
     file:
      path: "{{ item }}"
      owner: root
      mode: 0755
      state: directory
     loop:
        - '/etc/nginx/sites-available'
        - '/etc/nginx/sites-enabled/'
        - '/var/www'
        - '/var/www/{{website}}'
        - '/var/www/{{website}}/html'
   - name: create config file
     file:
      path: "{{ item }}"
      owner: root
      mode: 0755
      state: touch
     loop:
        - '/etc/nginx/sites-available/{{website}}'
        - '/var/www/{{website}}/html/index.html'
   - name: copy contents
     copy:
      content: |
                 <html>
                 <head>
                 <title>Welcome to test1.com</title>
                 </head>
                 <body>
                 <h1>This is a test page for the domain {{website}} </h1>
                 </body>
                 </html>
      dest: /var/www/{{website}}/html/index.html
   - name: copy contents
     copy:
      content: |
                 server {
                 listen 80;
                 listen [::]:80;
                 root /var/www/{{website}}/html; # The path to the website files
                 index index.html index.htm;
                 server_name {{website}};
                 location / {
                 try_files $uri $uri/ =404;
                 }
                 }
      dest: /etc/nginx/sites-available/{{website}}
   - name: Enable virtual host
     shell: ln -s /etc/nginx/sites-available/{{website}} /etc/nginx/sites-enabled/
   - name: Start Nginx
     service: name=nginx state=restarted enabled=yes

No responses yet

Leave a Reply

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

Recent Comments