Nginx setup on Windows using Ansible

This post shows how to setup Nginx on Windows using Ansible. I created a new role nginx for Nginx. Nginx is installed using Chocolatey. Please refer to this post about how to install Chocolatey on Windows using user data. NSSM is also required to configure Nginx as a Windows service, which is also installed using Chocolatey.

The version of Nginx on Chocolatey is 1.12.1. Below is the file tasks/main.yml for role nginx. I used win_chocolatey to install Nginx and NSSM first, then copied Nginx config file to the server, and finally set up the Windows service for Nginx using win_nssm.

Here I used a handler to start Nginx after the service is created. Below is the file handlers/main.yml. This is because even I configured win_nssm to start the service using state: started, the service is not started, so I have to start it manually.

1

2

3

4

5

6

---

- name:startnginx

win_service:

name:nginx

start_mode:auto

state:started

Bind on port 80

Nginx should listen on port 80. However, this is not easy on Windows. Windows has IIS running on port 80 by default, so it needs to be stopped first. This should be possible using win_service. Nginx service also needs to be started using the administrator account. This can be done using the options user and password of win_nssm. I used an easy approach which lets Nginx listens on port 8080 and configures firewall rules to forward traffic of port 80 to 8080. See below for the Powershell script to configure the port forwarding using user data.