Code Monkey home page Code Monkey logo

ansible-role-nginx's Introduction

nginx

This role installs and configures the nginx web server. The user can specify any http configuration parameters they wish to apply their site. Any number of sites can be added with configurations of your choice.

Build Status Ansible Galaxy

Requirements

This role requires Ansible 2.4 or higher and platform requirements are listed in the metadata file. (Some older version of the role support Ansible 1.4) For FreeBSD a working pkgng setup is required (see: https://www.freebsd.org/doc/handbook/pkgng-intro.html ) Installation of Nginx Amplify agent is only supported on CentOS, RedHat, Amazon, Debian and Ubuntu distributions.

Install

ansible-galaxy install jdauphant.nginx

Role Variables

The variables that can be passed to this role and a brief description about them are as follows. (For all variables, take a look at defaults/main.yml)

# The user to run nginx
nginx_user: "www-data"

# A list of directives for the events section.
nginx_events_params:
 - worker_connections 512
 - debug_connection 127.0.0.1
 - use epoll
 - multi_accept on

# A list of hashes that define the servers for nginx,
# as with http parameters. Any valid server parameters
# can be defined here.
nginx_sites:
 default:
     - listen 80
     - server_name _
     - root "/usr/share/nginx/html"
     - index index.html
 foo:
     - listen 8080
     - server_name localhost
     - root "/tmp/site1"
     - location / { try_files $uri $uri/ /index.html; }
     - location /images/ { try_files $uri $uri/ /index.html; }
 bar:
     - listen 9090
     - server_name ansible
     - root "/tmp/site2"
     - location / { try_files $uri $uri/ /index.html; }
     - location /images/ {
         try_files $uri $uri/ /index.html;
         allow 127.0.0.1;
         deny all;
       }

# A list of hashes that define additional configuration
nginx_configs:
  proxy:
      - proxy_set_header X-Real-IP  $remote_addr
      - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for
  upstream:
      - upstream foo { server 127.0.0.1:8080 weight=10; }
  geo:
      - geo $local {
          default 0;
          127.0.0.1 1;
        }
  gzip:
      - gzip on
      - gzip_disable msie6

# A list of hashes that define configuration snippets
nginx_snippets:
  error_pages:
    - error_page 500 /http_errors/500.html
    - error_page 502 /http_errors/502.html
    - error_page 503 /http_errors/503.html
    - error_page 504 /http_errors/504.html

# A list of hashes that define user/password files
nginx_auth_basic_files:
   demo:
     - foo:$apr1$mEJqnFmy$zioG2q1iDWvRxbHuNepIh0 # foo:demo , generated by : htpasswd -nb foo demo
     - bar:$apr1$H2GihkSo$PwBeV8cVWFFQlnAJtvVCQ. # bar:demo , generated by : htpasswd -nb bar demo

# Enable Real IP for CloudFlare requests
nginx_set_real_ip_from_cloudflare: True

# Enable Nginx Amplify
nginx_amplify: true
nginx_amplify_api_key: "your_api_key_goes_here"
nginx_amplify_update_agent: true

# Define modules to enable in configuration
#
# Nginx installed via EPEL and APT repos will also install some modules automatically.
# For official Nginx repo use you will need to install module packages manually.
#
# When using with EPEL and APT repos, specify this section as a list of configuration
# file names, minus the .conf file name extension.

# When using the official Nginx repo, specify this section as list of module file
# names, minus the .so file name extension.
#
# Available module config files in EPEL and APT repos:
# (APT actually has several more, see https://wiki.debian.org/Nginx/)
# - mod-http-geoip
# - mod-http-image-filter
# - mod-http-perl
# - mod-http-xslt-filter
# - mod-mail
# - mod-stream
#
# Available module filenames in Official NGINX repo:
# - ngx_http_geoip_module
# - ngx_http_image_filter_module
# - ngx_http_perl_module
# - ngx_http_xslt_filter_module
# - ngx_http_js_module
#
# Custom compiled modules are ok too if the .so file exists in same location as a packaged module would be:
# - ngx_http_modsecurity_module
#
nginx_module_configs:
  - mod-http-geoip

Examples

1) Install nginx with HTTP directives of choice, but with no sites configured and no additional configuration:

- hosts: all
  roles:
  - {role: nginx,
     nginx_http_params: ["sendfile on", "access_log /var/log/nginx/access.log"]
                          }

2) Install nginx with different HTTP directives than in the previous example, but no

sites configured and no additional configuration.

- hosts: all
  roles:
  - {role: nginx,
     nginx_http_params: ["tcp_nodelay on", "error_log /var/log/nginx/error.log"]}

Note: Please make sure the HTTP directives passed are valid, as this role won't check for the validity of the directives. See the nginx documentation for details.

3) Install nginx and add a site to the configuration.

- hosts: all

  roles:
  - role: nginx
    nginx_http_params:
      - sendfile "on"
      - access_log "/var/log/nginx/access.log"
    nginx_sites:
      bar:
        - listen 8080
        - location / { try_files $uri $uri/ /index.html; }
        - location /images/ { try_files $uri $uri/ /index.html; }
    nginx_configs:
      proxy:
        - proxy_set_header X-Real-IP  $remote_addr
        - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for

4) Install nginx and add extra variables to default config

-hosts: all
  vars:
    - my_extra_params:
      - client_max_body_size 200M
# retain defaults and add additional `client_max_body_size` param
  roles:
    - role: jdauphant.nginx
      nginx_http_params: "{{ nginx_http_default_params + my_extra_params }}"

Note: Each site added is represented by a list of hashes, and the configurations generated are populated in /etc/nginx/site-available/ and linked from /etc/nginx/site-enable/ to /etc/nginx/site-available.

The file name for the specific site configuration is specified in the hash with the key "file_name", any valid server directives can be added to the hash. Additional configurations are created in /etc/nginx/conf.d/

5) Install Nginx, add 2 sites (different method) and add additional configuration

---
- hosts: all
  roles:
    - role: nginx
      nginx_http_params:
        - sendfile on
        - access_log /var/log/nginx/access.log
      nginx_sites:
         foo:
           - listen 8080
           - server_name localhost
           - root /tmp/site1
           - location / { try_files $uri $uri/ /index.html; }
           - location /images/ { try_files $uri $uri/ /index.html; }
         bar:
           - listen 9090
           - server_name ansible
           - root /tmp/site2
           - location / { try_files $uri $uri/ /index.html; }
           - location /images/ { try_files $uri $uri/ /index.html; }
      nginx_configs:
         proxy:
            - proxy_set_header X-Real-IP  $remote_addr
            - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for

6) Install Nginx, add 2 sites, add additional configuration and an upstream configuration block

---
- hosts: all
  roles:
    - role: nginx
      nginx_error_log_level: info
      nginx_http_params:
        - sendfile on
        - access_log /var/log/nginx/access.log
      nginx_sites:
        foo:
           - listen 8080
           - server_name localhost
           - root /tmp/site1
           - location / { try_files $uri $uri/ /index.html; }
           - location /images/ { try_files $uri $uri/ /index.html; }
        bar:
           - listen 9090
           - server_name ansible
           - root /tmp/site2
           - if ( $host = example.com ) { rewrite ^(.*)$ http://www.example.com$1 permanent; }
           - location / {
             try_files $uri $uri/ /index.html;
             auth_basic            "Restricted";
             auth_basic_user_file  auth_basic/demo;
           }
           - location /images/ { try_files $uri $uri/ /index.html; }
      nginx_configs:
        proxy:
            - proxy_set_header X-Real-IP  $remote_addr
            - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for
        upstream:
            # Results in:
            # upstream foo_backend {
            #   server 127.0.0.1:8080 weight=10;
            # }
            - upstream foo_backend { server 127.0.0.1:8080 weight=10; }
      nginx_auth_basic_files:
        demo:
           - foo:$apr1$mEJqnFmy$zioG2q1iDWvRxbHuNepIh0 # foo:demo , generated by : htpasswd -nb foo demo
           - bar:$apr1$H2GihkSo$PwBeV8cVWFFQlnAJtvVCQ. # bar:demo , generated by : htpasswd -nb bar demo

7) Install Nginx, add a site and use special yaml syntax to make the location blocks multiline for clarity

---
- hosts: all
  roles:
    - role: nginx
      nginx_http_params:
        - sendfile on
        - access_log /var/log/nginx/access.log
      nginx_sites:
        foo:
           - listen 443 ssl
           - server_name foo.example.com
           - set $myhost foo.example.com
           - |
             location / {
               proxy_set_header Host foo.example.com;
             }
           - |
             location ~ /v2/users/.+?/organizations {
               if ($request_method = PUT) {
                 set $myhost bar.example.com;
               }
               if ($request_method = DELETE) {
                 set $myhost bar.example.com;
               }
               proxy_set_header Host $myhost;
             }

8) Example to use this role with my ssl-certs role to generate or copy ssl certificate ( https://galaxy.ansible.com/jdauphant/ssl-certs )

 - hosts: all
   roles:
     - jdauphant.ssl-certs
     - role: jdauphant.nginx
       nginx_configs:
          ssl:
               - ssl_certificate_key {{ssl_certs_privkey_path}}
               - ssl_certificate     {{ssl_certs_cert_path}}
       nginx_sites:
          default:
               - listen 443 ssl
               - server_name _
               - root "/usr/share/nginx/html"
               - index index.html

9) Site configuration using a custom template.

Instead of defining a site config file using a list of attributes, you may use a hash/dictionary that includes the filename of an alternate template. Additional values are accessible within the template via the item.value variable.

- hosts: all

  roles:
  - role: nginx
    nginx_sites:
      custom_bar:
        template: custom_bar.conf.j2
        server_name: custom_bar.example.com

Custom template: custom_bar.conf.j2:

# {{ ansible_managed }}
upstream backend {
  server 10.0.0.101;
}
server {
  server_name {{ item.value.server_name }};
  location / {
    proxy_pass http://backend;
  }
}

Using a custom template allows for unlimited flexibility in configuring the site config file. This example demonstrates the common practice of configuring a site server block in the same file as its complementary upstream block. If you use this option:

  • The hash must include a template: value, or the configuration task will fail.
  • This role cannot check tha validity of your custom template. If you use this method, the conf file formatting provided by this role is unavailable, and it is up to you to provide a template with valid content and formatting for NGINX.

10) Install Nginx, add 2 sites, use snippets to configure access controls

---
- hosts: all
  roles:
    - role: nginx
      nginx_http_params:
        - sendfile on
        - access_log /var/log/nginx/access.log
      nginx_snippets:
        accesslist_devel:
          - allow 192.168.0.0/24
          - deny all
      nginx_sites:
        foo:
           - listen 8080
           - server_name localhost
           - root /tmp/site1
           - include snippets/accesslist_devel.conf
           - location / { try_files $uri $uri/ /index.html; }
           - location /images/ { try_files $uri $uri/ /index.html; }
        bar:
           - listen 9090
           - server_name ansible
           - root /tmp/site2
           - location / { try_files $uri $uri/ /index.html; }
           - location /images/ { try_files $uri $uri/ /index.html; }

Dependencies

None

License

BSD

Author Information

  • Original : Benno Joy
  • Modified by : DAUPHANT Julien

ansible-role-nginx's People

Contributors

bbaassssiiee avatar bennojoy avatar billyrayvalentine avatar blackstar257 avatar br0ken- avatar dhutty avatar exploide avatar flatrocks avatar gnarf avatar ismagnu avatar jdauphant avatar jordiclariana avatar kagux avatar mrwacky42 avatar nbz4live avatar perryk avatar pieterlexis avatar popstas avatar q2digger avatar realloc avatar realmyst avatar ryanhughes avatar sethp-jive avatar shipilovds avatar siggyf avatar thesycamore avatar timorunge avatar tolbrino avatar wkielas avatar x-drum avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ansible-role-nginx's Issues

Add version numbers to releases

I'm specifying roles in a Role file, and it would be helpful to specify version numbers so we can install specific versions. Not doing so will potentially break playbooks that use this role in the future.

remove-unwanted fails before configuration.yml creates sites-enabled

Trying to install with nginx_official_repo: True, but "Remove the default configuration" fails because /etc/nginx/sites-enabled doesn't exist yet:

{"failed": true, "msg": "The conditional check ''default' not in nginx_configs.keys()
' failed. The error was: error while evaluating conditional ('default' not in nginx_configs.keys()
): 'dict object' has no attribute 'ansible_eth0'

The error appears to have been in '/home/ei-grad/repos/deal/devops/roles/nginx/tasks/remove-defaults.yml': line 8, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


- name: Remove the default configuration
  ^ here
"}

How add redirection http to https with role vars?

I need generate some nginx config to redirect http to https:

# ------ b-sitespeed -------
upstream vcbsitespeed {
  server vcmm.mydomain:40042;
}
# redirect http to https
server {
    listen 80;
    server_name vcbsitespeed.mydomain;
    return 301  https://$http_host$request_uri;
}
server {
  listen 443;
  client_max_body_size 8m;
  server_name vcbsitespeed.mydomain;
  #server_tokens off;
  ssl on;
  ssl_certificate /etc/nginx/ssl/certs/beee.crt;
  ssl_certificate_key /etc/nginx/ssl/private/beee.key;
  ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers HIGH:!aNULL:!MD5;

  try_files $uri $uri/index.html $uri.html @beee-sitespeed;

  location / {
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        CLIENT_IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto https;
    proxy_set_header        Host $host;

    proxy_connect_timeout   150;
    proxy_send_timeout      100;
    proxy_read_timeout      100;
    proxy_buffers           4 32k;

    proxy_redirect off;
    proxy_pass http://vcbsitespeed;
  }
}

events options

Hi,

What about adding epoll and multi_accept on the events section ?

events {
    worker_connections 2048;
    use epoll;
    multi_accept on; 
}

Today, only worker_connections is supported :-(
Thanks

How to use this role as a dependency ?

Hello,

I'm trying to create a phpmyadmin role which will install the package and create the nginx vhost using your nginx role.

The problem is when I call your role as a dependency, the role is called before the package install. So the path does not exist yet and nginx will fail as root path doesn't exist.

Any idea about this please ? Maybe a flag to not reload nginx and let my role manage nginx daemon with his own handler ?

If you think the flag is the good way to manage this usecase, I will do a PR with no breaking change.

Thanks

Attempting to start nginx fails with rc=1 on Ubuntu 16.04.1 (Xenial Xerus)

When this role attempts to start nginx by using Ansible's service module to start the service defined by the variable nginx_service_name, it fails, returning code 1, claiming that there is 'No such file or directory':

fatal: [default]: FAILED! => {"changed": false, "failed": true, "msg": "Error when trying to enable nginx: rc=1 Failed to execute operation: No such file or directory\n"}

nginx is not recognised as a service by service nor systemctl.

Idempotent

To be Idempotent role must delete configs that aren't in role.
Example: When I setup role i accidentally nginx_configs var to nginx_sites and this created broken config, later after i fix this provisioning still fails because nginx couldn't start.

Testing nginx_daemon_mode == "on" for start/restart/reload does not work as expected

In the default variables file, defaults/main.yml:
nginx_daemon_mode: on

However this is interpreted as a boolean when loading YAML and thus the test always fails since it compares a regular string ("on") to a boolean (True). Hence nginx is never started/reloaded/restarted as needed.

I'd suggest just reverting the last two commits but since you explicitly added the == "on" I suspect you had something else in mind :) Using nginx_daemon_mode: "on" would also work I suppose, but would lose the type information (i.e. the fact that this is actually a boolean variable).

Idempotency broken , creates and removes 'conf.d/stream' directory.

Every time I run Ansible, it creates a conf.d/stream directory.

TASK [nginx : Create the directories for site specific configurations] *********
ok: [agri.dev.ts-new] => (item=sites-available)
ok: [agri.dev.ts-new] => (item=sites-enabled)
ok: [agri.dev.ts-new] => (item=auth_basic)
ok: [agri.dev.ts-new] => (item=conf.d)
changed: [agri.dev.ts-new] => (item=conf.d/stream)

but then removes that same conf.d/stream directory as part of the 'Remove unmanaged config files' step on the same run.

I am using Ansible 2.2.2 and Ubuntu 14.04.

site name as variable

Is it possible to use the "site name" as a variable?

I'm trying to simplify certain configs for multiple vhosts, such as access_log and error_log directives.

I.E.:

          example.org:
            - listen 80
            - server_name {{ site_name }}
            - access_log  /var/log/nginx/{{ site_name }}-access.log
            - error_log   /var/log/nginx/{{ sitte_name }}-error.log

Something like that...

Thanks

ansible_processor _vcpus undifined on digital ocean FreeBSD box

TASK: [jdauphant.nginx | Copy the nginx configuration file] *******************
fatal: [www] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'ansible_processor
_vcpus' is undefined", 'failed': True}
fatal: [www] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'ansible_processor
_vcpus' is undefined", 'failed': True}

I'm using version 1.9.4 on my workstation and getting this error.

EDIT: also ansible -m setup is not returning it or anything similar, so I'm not sure if this actually is a ansible bug

Role doesn't ensure that nginx_sites exactly matches sites-enabled

Hello, maybe I am missing something (I am not an Ansible expert), but the behavior I expected from this role was that the configured nginx sites on the host would be exactly those configured under nginx_sites.

However, while working on a playbook using this role, at one point I decided to change the name of a site, and proceeded to make further changes. When those changes were not picked up, upon further investigation I realized that the site with the original name (which happened to be alphabetically before the new name) was still there from previous playbook runs. Presumably it was overriding the correct site, which still had the same server_name and was configured to listen on the same port.

support installation of nginx from different repo

I would like to install nginx from the phusion passenger repo. Right now, I do this manually and set

nginx_installation_type

to something invalid (packages_phusion). This avoids that ansible-role-nginx installs nginx from another repository.

Unfortunately, a side effect of this setting is that nginx is not properly restarted upon config change. The respective code from handlers/main.yml is

- name: reload nginx
  service: name={{ nginx_service_name }} state=reloaded
  when: nginx_installation_type in nginx_installation_types_using_service and nginx_daemon_mode == "on"

(Here, the condition nginx_installation_type in nginx_installation_types_using_service is false.)

What could be done to fix this?

Can't configure sites

Hi,

I'm using ansible 2.0.1.0 and v2.0.2 of the role. While I'm trying to deploy new config, I've got this messages:

TASK [jdauphant.nginx : Create the configurations for sites] *******************
[DEPRECATION WARNING]: Skipping task due to undefined Error, in the future this will be a fatal error.. This feature will be removed
 in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

TASK [jdauphant.nginx : Create links for sites-enabled] ************************
[DEPRECATION WARNING]: Skipping task due to undefined Error, in the future this will be a fatal error.. This feature will be removed
 in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

No sites can't be configured then. Any idea ?

Thanks

Suggestions for using stream config?

I'm using nginx as a reverse proxy, but I need to secure traffic to the upstream hosts. According to this document, it looks like I need a stream configuration. I've tried setting this up with this role, but I'm having difficulty. Can a kind soul please point me in the right direction?

Thanks.

Default site variables

Hi,
Maybe I just didn't find it but I can't find a way to set default site variables for all vhosts. How would I set this globally for all vhosts?

- index index.php
- location / { try_files $uri $uri/ /index.php; }
- location ~ \.php$ { fastcgi_pass unix:/var/run/php5-fpm.sock; .... etc.

Support for access type config files

Hello.
I want to add support for custom access config files, like:

allow from 123.123.123.123
deny from all

I cant use nginx_configs section, because this type of config will be autoloaded at nginx restart and can broke access to web server, so i think i must add another section like nginx_auth_basic_files. Which will be independent, will not load at start but can be used for includes.
I am right, or there is other way for this type of configs?

CentOS 7.1 can't resolve all deps for nginx install

os version: 7.1.1503 (OpenLogic)

You'll see that gperftools relies on libunwind and there is an error resolving the dep:

...
msg: Error: Package: gperftools-libs-2.4-5.el7.x86_64
Requires: libunwind.so.8

libunwind is currently in the CR repo. There's a thread that talks about it here:

https://www.centos.org/forums/viewtopic.php?f=47&t=55325

Enabling the "cr" repo resolves the problem for manual installs (e.g. yum-config-manager --enable cr), but this module still needs to enable the repo in the task (tasks/installation.packages.yml, line 13) to not fail:

- name: Install the nginx packages
  yum: name={{ item }} state=present disablerepo='*' enablerepo={{ "nginx," if nginx_official_repo else "" }}{{ yum_epel_repo }},{{ yum_base_repo }},cr
  with_items: nginx_redhat_pkg
  when:  nginx_is_el|bool
  tags: [packages,nginx]

upstream use with multitenant setup?

I've got one server with multiple projects running on it. Each project has an application server behind nginx, so each defines one site and one upstream. I'll call these site1/upstream1 and site2/upstream2.

It looks like the config deals properly with the multiple nginx_site definition, but clobbers the other upstream definition. If I run ansible for site1, then site2, I get output that looks like:

TASK: [jdauphant.nginx | Check nginx syntax of configuration files] ***********
failed: [...] => {"changed": true, "cmd": "nginx -t", "delta": "0:00:00.693414", "end": "2015-06-27 20:27:20.640370", "rc": 1, "start": "2015-06-27 20:27:19.946956", "stdout_lines": [], "warnings": []}
stderr: nginx: [emerg] host not found in upstream "upstream1" in /etc/nginx/sites-enabled/site1.conf:10
nginx: configuration file /etc/nginx/nginx.conf test failed

Is this expected? Or is there a better way to set up my configuration to avoid this? I'm pretty new to nginx in general.

Debian/Ubuntu: Add force=yes to avoid issues

Hi,

Can you please add "force=yes" in the Nginx installation package to avoid issues when installing nginx-extra package for example:

  - name: Install the nginx packages
    apt: name={{ item }} state=present force=yes
    with_items: nginx_ubuntu_pkg
    environment: env 
    when: ansible_os_family == "Debian"
    tags: [packages,nginx]

I got this kind of issues when not set:

    docker: TASK: [jdauphant.nginx | Install the nginx packages] **************************

    docker: failed: [127.0.0.1] => (item=nginx-extras) => {"failed": true, "item": "nginx-extras"}
    docker: stderr: E: There are problems and -y was used without --force-yes
    docker: 
    docker: stdout: Reading package lists...
    docker: Building dependency tree...
    docker: Reading state information...
    docker: The following extra packages will be installed:
    docker: fontconfig-config fonts-dejavu-core libfontconfig1 libfreetype6 libgd3
    docker: libjbig0 libjpeg62-turbo libluajit-5.1-2 libluajit-5.1-common libperl5.20
    docker: libpng12-0 libtiff5 libvpx1 libxpm4 nginx-common
    docker: Suggested packages:
    docker: libgd-tools fcgiwrap nginx-doc ssl-cert
    docker: The following NEW packages will be installed:
    docker: fontconfig-config fonts-dejavu-core libfontconfig1 libfreetype6 libgd3
    docker: libjbig0 libjpeg62-turbo libluajit-5.1-2 libluajit-5.1-common libperl5.20
    docker: libpng12-0 libtiff5 libvpx1 libxpm4 nginx-common nginx-extras
    docker: 0 upgraded, 16 newly installed, 0 to remove and 26 not upgraded.
    docker: Need to get 4368 kB of archives.
    docker: After this operation, 11.2 MB of additional disk space will be used.
    docker: WARNING: The following packages cannot be authenticated!
    docker: libpng12-0 libfreetype6 fonts-dejavu-core fontconfig-config libfontconfig1
    docker: libjpeg62-turbo libjbig0 libtiff5 libvpx1 libxpm4 libgd3
    docker: libluajit-5.1-common libluajit-5.1-2 libperl5.20 nginx-common nginx-extras
    docker: 
    docker: msg: 'apt-get install 'nginx-extras'' failed: E: There are problems and -y was used without --force-yes

Thanks

Yum install on el

When I use the nginx installer on EL the code disable all repo and the it can download the dependency packages like openssl... etc.

yum: name={{ item }} state=present disablerepo='*' enablerepo={{ "nginx," if nginx_official_repo else "" }}{{ yum_epel_repo }},{{ yum_base_repo }}

But if I allow him to use all repo it will work without problem:

yum: name={{ item }} state=present

defining sites_enabled file name via variable

I am wondering if defining the example.com.conf in sites enabled is definable via a variable.

Currently using:

- role: ansible-role-nginx
  nginx_sites:
  "{{ my_domain }}":                              <--- This line causes the error
    - server_name {{ my_domain }}
      root /home/admin/sites/{{ my_domain }}

The server name and root lines work perfectly fine. Defining the file name statically as per your examples also work fine. Is there anything I am missing here or is what I am trying to do not feasible in the current iteration. Thank you.

Configure the extension of sites-available config files

First of all thank you for this role, it is very useful.

Is it possible to add a variable allowing to configure the extension of site definition in sites-available ?
For the moment the role always add .conf extension.

- name: Create the configurations for sites
  template: src=site.conf.j2 dest={{nginx_conf_dir}}/sites-available/{{ item }}{{nginx_config_extension|default()}}
  with_items: nginx_sites.keys()
  notify: 
   - restart nginx
  tags: [configuration,nginx]

I can make a pull request if you want, let me know if your agree with my variable name.

should the generated config files be readable?

currently it looks like something like this:

$ cat conf.d/gzip.conf
#Ansible managed: ansible/vendor/roles/jdauphant.nginx/templates/config.conf.j2 modified on 2015-01-10 04:59:19 by johnny on falling

   gzip on ;   gzip_comp_level 5 ;   gzip_min_length 256 ;   gzip_proxied any ;   gzip_types application/atom+xml application/javascript application/json application/rss+xml application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/svg+xml image/x-icon text/css text/plain text/x-component ;

I think it should look more like this:

gzip on
gzip_comp_level 5; 
gzip_min_length 256;
gzip_proxied any;
gzip_types application/atom+xml application/javascript application/json application/rss+xml application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/svg+xml image/x-icon text/css text/plain text/x-component ;

Configured upstream does not appear in resulting config

I'm trying to setup nginx as load balancer using next set of variables:

   nginx_user: "www-data"
   nginx_sites:
    default:   
     - listen 80;
       server_name _;
       location / {
           proxy_pass http://backend;         
       }
   nginx_configs:
    upstream:
     - upstream backend { server 192.168.10.10; }

Config created after provisioning:

server {
   listen 80;
       server_name _;
       location / {
       proxy_pass http://backend;

   }
}

But there is no created upstream. Could you please advise how can I correctly configure it?
Ansible version: 1.9.4

With hash behavior = merge, default site is not removed

We use hash_behavior: merge and if I specify nginx_sites in my playbook the default site gets added back in sites-available and sites-enabled. I think this can be fixed by changing the order in main.yaml to

- include: configuration.yml
- include: remove-defaults.yml
  when: not keep_only_specified
- include: remove-extras.yml
  when: keep_only_specified
- include: remove-unwanted.yml

Default setup does not work on physical host

I have tested this role on a physical node and the generated configuration was invalid.
The nginx process was launching with 0 workers, and it hangs and cannot proceed any request.

Here is the truncated output of ansible -m setup for my host:

"ansible_processor_cores": 1,
"ansible_processor_count": 0,
"ansible_processor_threads_per_core": 1,
"ansible_processor_vcpus": 0,

The default configuration is using ansible_processor_vcpus but it looks like it is set to 0 on physical nodes. (

nginx_worker_processes: "{{ ansible_processor_vcpus }}"
)

I saw that we can enforce the number of worker in the configuration by setting the nginx_worker_processes.
You should consider using another property to ensure that it works out of the box for everyone.

Allow multiple dependencies

I would like to use ansible-role-nginx to add several nginx configurations from different roles to /etc/nginx/sites-{available,enabled}/. Unfortunately, the module doesn't support this yet. The Ansible docs say

By default, roles can also only be added as a dependency once - if another role also lists it as a dependency it will not be run again. This behavior can be overridden by adding allow_duplicates: yes to the meta/main.yml file.

Any thoughts on that?

default vhost configuration does not work

This is how my playbook looks like:

---
- hosts: vagrant 
  remote_user: vagrant 
  sudo: True
  roles:
  - role: jdauphant.nginx      
    nginx_sites: 
      default: 
        - listen *:80 
        - server_name localhost
        - root "/vagrant"
        - index index.html

When I run this playbook, under sites-enabled default as well as default.conf files are present due to which localhost requests do not work(default overrides default.conf's server section).

I did a bit of digging around and changed "Disable the default sites" task's when condition from

 when: >
    'default' not in nginx_sites.keys()

to

when: "'default' in nginx_sites.keys()"

After this change, I find only default.conf in sites-enabled and the configuration I provided for localhost kicks in.

Is this a bug or am I missing something?

Running this on vagrant with config.vm.box = "ubuntu/trusty64".

Can't start if daemon is on with systemd

Hi,

I'm trying to get it working with Debian Jessie. However, with systemd there's an issue when daemon is set to "on":

Feb 26 17:58:45 vm sudo[5522]: pam_unix(sudo:session): session closed for user root
Feb 26 17:58:45 vm sudo[5529]: vagrant : TTY=unknown ; PWD=/home/vagrant ; USER=root ; COMMAND=/bin/sh -c echo SUDO-SUCCESS-lkyorsvjl
Feb 26 17:58:45 vm sudo[5529]: pam_unix(sudo:session): session opened for user root by (uid=0)
Feb 26 17:58:45 vm ansible-<stdin>[5531]: Invoked with name=nginx pattern=None enabled=True state=started sleep=None arguments= runle
Feb 26 17:58:45 vm nginx[5563]: nginx: [emerg] "daemon" directive is duplicate in /etc/nginx/nginx.conf:51
Feb 26 17:58:45 vm nginx[5563]: nginx: configuration file /etc/nginx/nginx.conf test failed
Feb 26 17:58:45 vm systemd[1]: nginx.service: control process exited, code=exited status=1
Feb 26 17:58:45 vm systemd[1]: Failed to start A high performance web server and a reverse proxy server.
-- Subject: Unit nginx.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
-- 
-- Unit nginx.service has failed.
-- 
-- The result is failed.
Feb 26 17:58:45 vm systemd[1]: Unit nginx.service entered failed state.
Feb 26 17:58:45 vm sudo[5529]: pam_unix(sudo:session): session closed for user root

Trying to find the way to make it work

Unable to run the playbook (skipped tasks throw an error about `with_items`)

I just upgraded this role to the last version (1.11.4) and it does not run anymore. I am getting the following error:

TASK: [jdauphant.nginx | Find enabled sites] ********************************** 
skipping: [default]

TASK: [jdauphant.nginx | Disable unmanaged sites] ***************************** 
skipping: [default] => (item=enabled_sites.stdout_lines)

TASK: [jdauphant.nginx | Find config files] *********************************** 
skipping: [default]

TASK: [jdauphant.nginx | Remove unmanaged config files] *********************** 
fatal: [default] => with_items expects a list or a set

This seems to be an issue with Ansible itself (with_items + skipped tasks), but affects this role.
I am using Ansible 1.9.4 (latest release) with a standard nginx configuration dictionnary.

Downgrading to the version 1.11.1 of the role solved my issue.

Syntax check fail if SELinux is Enforcing

I have an error after that step when starting nginx, without this step nginx is starting ok

- name: Check nginx syntax of configuration files
  shell: nginx -t
  register: result
  changed_when: "result.rc != 0"
  always_run: yes
  when: nginx_installation_type in nginx_installation_types_using_service
  tags: [configuration,nginx]

With this i see

msg: Job for nginx.service failed. See 'systemctl status nginx.service' and 'journalctl -xn' for details.

and when I'm check failed status it is

nginx: [emerg] open() "/var/run/nginx.pid" failed (13: Permission denied)

I don't know why this happen, but anyway, without this step restart or reload will failed anyway, so why this step is needed?

map statements fail if in http configuration

I didn't test anywhere else yet,

but if you try to write something like:

  - map $scheme $hsts_header {
         https 'max-age=10886400; includeSubDomains;'
     }

then it adds a ; after the } which makes the the configuration testing fail.

formatting issues with embedded semi-colons

A site config that included this:

add_header X-Xss-Protection "1; mode=block" always

was making the formatting look odd because of the semi-colon in the middle of the statement. In the replace I tried adding a newline to match on the end of the line, e.g.

v.replace(";\n",";\n ")

which worked but its not a complete fix. Perhaps a regex match to end of line including any preceeding whitespace would work. Do you think this would be a useful fix?

add a way to include common configuration files.

when deploying SSL like shown in https://github.com/igrigorik/istlsfastyet.com/tree/master/nginx
you need to duplicate the ssl configuration twice between sites to make sure secure access to https://www.example.org and https://example.org are covered by the same configuration. i solved it with a quick hack like so: http://fpaste.org/163673/63848141/

and then put this in role configuration:

  • include /etc/nginx/ssl.conf

This is a pretty naive way of doing it, maybe you have a better idea.

It would be hard to automate properly as the loading order for the config files might matter, so simply processing them before or after the site inclusion might not work well for everyone.

Enabling gzip compression doesn't seem to work

First off, thanks for the nice role - it works a charm with very minimal configuration.

When I started looking more closely at my server responses in chrome's developer tools, I noticed that gzip compression was not enabled. I looked at the readme and it seemed basic enough, so I added the following to my playbook:

    - role: jdauphant.nginx
      nginx_configs:
        gzip:
          - gzip on
          - gzip_disable msie6

Which, sure enough, indeed added a file to /etc/nginx/conf.d/gzip.conf with the following contents:

$ cat /etc/nginx/conf.d/gzip.conf
#Ansible managed: /Users/chiel/dev/ansible/roles/jdauphant.nginx/templates/config.conf.j2 modified on 2016-06-18 11:57:02 by chiel on chiel-mbp.local

gzip on;
gzip_disable msie6;

However, when I inspect the network tab there is still no gzip header and the content is exactly the same size as before. Am I missing something?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.