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
--- - name: install nginx win_chocolatey: name: nginx state: present - name: install nssm win_chocolatey: name: nssm state: present - name: copy nginx conf file win_template: src: nginx.conf.j2 dest: C:\ProgramData\chocolatey\lib\nginx\tools\nginx-1.12.1\conf\nginx.conf - name: install nginx as service win_nssm: name: nginx application: C:\ProgramData\chocolatey\lib\nginx\tools\nginx-1.12.1\nginx.exe app_parameters_free_form: -c C:\ProgramData\chocolatey\lib\nginx\tools\nginx-1.12.1\conf\nginx.conf -p C:\ProgramData\chocolatey\lib\nginx\tools\nginx-1.12.1 stdout_file: C:\nginx_out.txt stderr_file: C:\nginx_error.txt start_mode: auto state: started notify: - start nginx
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.
--- - name: start nginx 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
win_nssm. I used an easy approach which lets Nginx listens on port
8080 and configures firewall rules to forward traffic of port
8080. See below for the Powershell script to configure the port forwarding using user data.
<powershell> $ipAddress = (invoke-restmethod -uri http://169.254.169.254/latest/meta-data/local-ipv4) "Setting up port forwarding" netsh interface portproxy add v4tov4 listenport=80 connectport=8080 connectaddress=$ipAddress </powershell>