Coder Social home page Coder Social logo

geerlingguy / ansible-role-nginx Goto Github PK

View Code? Open in Web Editor NEW
803.0 39.0 492.0 172 KB

Ansible Role - Nginx

Home Page: https://galaxy.ansible.com/geerlingguy/nginx/

License: MIT License

Jinja 100.00%
ansible role nginx webserver http https balancer

ansible-role-nginx's Introduction

Ansible Role: Nginx

CI

Note: Please consider using the official NGINX Ansible role from NGINX, Inc.

Installs Nginx on RedHat/CentOS, Debian/Ubuntu, Archlinux, FreeBSD or OpenBSD servers.

This role installs and configures the latest version of Nginx from the Nginx yum repository (on RedHat-based systems), apt (on Debian-based systems), pacman (Archlinux), pkgng (on FreeBSD systems) or pkg_add (on OpenBSD systems). You will likely need to do extra setup work after this role has installed Nginx, like adding your own [virtualhost].conf file inside /etc/nginx/conf.d/, describing the location and options to use for your particular website.

Requirements

None.

Role Variables

Available variables are listed below, along with default values (see defaults/main.yml):

nginx_listen_ipv6: true

Whether or not to listen on IPv6 (applied to all vhosts managed by this role).

nginx_vhosts: []

A list of vhost definitions (server blocks) for Nginx virtual hosts. Each entry will create a separate config file named by server_name. If left empty, you will need to supply your own virtual host configuration. See the commented example in defaults/main.yml for available server options. If you have a large number of customizations required for your server definition(s), you're likely better off managing the vhost configuration file yourself, leaving this variable set to [].

nginx_vhosts:
  - listen: "443 ssl http2"
    server_name: "example.com"
    server_name_redirect: "www.example.com"
    root: "/var/www/example.com"
    index: "index.php index.html index.htm"
    error_page: ""
    access_log: ""
    error_log: ""
    state: "present"
    template: "{{ nginx_vhost_template }}"
    filename: "example.com.conf"
    extra_parameters: |
      location ~ \.php$ {
          fastcgi_split_path_info ^(.+\.php)(/.+)$;
          fastcgi_pass unix:/var/run/php5-fpm.sock;
          fastcgi_index index.php;
          fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
          include fastcgi_params;
      }
      ssl_certificate     /etc/ssl/certs/ssl-cert-snakeoil.pem;
      ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
      ssl_protocols       TLSv1.1 TLSv1.2;
      ssl_ciphers         HIGH:!aNULL:!MD5;

An example of a fully-populated nginx_vhosts entry, using a | to declare a block of syntax for the extra_parameters.

Please take note of the indentation in the above block. The first line should be a normal 2-space indent. All other lines should be indented normally relative to that line. In the generated file, the entire block will be 4-space indented. This style will ensure the config file is indented correctly.

  - listen: "80"
    server_name: "example.com www.example.com"
    return: "301 https://example.com$request_uri"
    filename: "example.com.80.conf"

An example of a secondary vhost which will redirect to the one shown above.

Note: The filename defaults to the first domain in server_name, if you have two vhosts with the same domain, eg. a redirect, you need to manually set the filename so the second one doesn't override the first one

nginx_remove_default_vhost: false

Whether to remove the 'default' virtualhost configuration supplied by Nginx. Useful if you want the base / URL to be directed at one of your own virtual hosts configured in a separate .conf file.

nginx_upstreams: []

If you are configuring Nginx as a load balancer, you can define one or more upstream sets using this variable. In addition to defining at least one upstream, you would need to configure one of your server blocks to proxy requests through the defined upstream (e.g. proxy_pass http://myapp1;). See the commented example in defaults/main.yml for more information.

nginx_user: "nginx"

The user under which Nginx will run. Defaults to nginx for RedHat, www-data for Debian and www on FreeBSD and OpenBSD.

nginx_worker_processes: "{{ ansible_processor_vcpus|default(ansible_processor_count) }}"
nginx_worker_connections: "1024"
nginx_multi_accept: "off"

nginx_worker_processes should be set to the number of cores present on your machine (if the default is incorrect, find this number with grep processor /proc/cpuinfo | wc -l). nginx_worker_connections is the number of connections per process. Set this higher to handle more simultaneous connections (and remember that a connection will be used for as long as the keepalive timeout duration for every client!). You can set nginx_multi_accept to on if you want Nginx to accept all connections immediately.

nginx_error_log: "/var/log/nginx/error.log warn"
nginx_access_log: "/var/log/nginx/access.log main buffer=16k flush=2m"

Configuration of the default error and access logs. Set to off to disable a log entirely.

nginx_sendfile: "on"
nginx_tcp_nopush: "on"
nginx_tcp_nodelay: "on"

TCP connection options. See this blog post for more information on these directives.

nginx_keepalive_timeout: "65"
nginx_keepalive_requests: "100"

Nginx keepalive settings. Timeout should be set higher (10s+) if you have more polling-style traffic (AJAX-powered sites especially), or lower (<10s) if you have a site where most users visit a few pages and don't send any further requests.

nginx_server_tokens: "on"

Nginx server_tokens settings. Controls whether nginx responds with it's version in HTTP headers. Set to "off" to disable.

nginx_client_max_body_size: "64m"

This value determines the largest file upload possible, as uploads are passed through Nginx before hitting a backend like php-fpm. If you get an error like client intended to send too large body, it means this value is set too low.

nginx_server_names_hash_bucket_size: "64"

If you have many server names, or have very long server names, you might get an Nginx error on startup requiring this value to be increased.

nginx_proxy_cache_path: ""

Set as the proxy_cache_path directive in the nginx.conf file. By default, this will not be configured (if left as an empty string), but if you wish to use Nginx as a reverse proxy, you can set this to a valid value (e.g. "/var/cache/nginx keys_zone=cache:32m") to use Nginx's cache (further proxy configuration can be done in individual server configurations).

nginx_extra_http_options: ""

Extra lines to be inserted in the top-level http block in nginx.conf. The value should be defined literally (as you would insert it directly in the nginx.conf, adhering to the Nginx configuration syntax - such as ; for line termination, etc.), for example:

nginx_extra_http_options: |
  proxy_buffering    off;
  proxy_set_header   X-Real-IP $remote_addr;
  proxy_set_header   X-Scheme $scheme;
  proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header   Host $http_host;

See the template in templates/nginx.conf.j2 for more details on the placement.

nginx_extra_conf_options: ""

Extra lines to be inserted in the top of nginx.conf. The value should be defined literally (as you would insert it directly in the nginx.conf, adhering to the Nginx configuration syntax - such as ; for line termination, etc.), for example:

nginx_extra_conf_options: |
  worker_rlimit_nofile 8192;

See the template in templates/nginx.conf.j2 for more details on the placement.

nginx_log_format: |-
  '$remote_addr - $remote_user [$time_local] "$request" '
  '$status $body_bytes_sent "$http_referer" '
  '"$http_user_agent" "$http_x_forwarded_for"'

Configures Nginx's log_format. options.

nginx_default_release: ""

(For Debian/Ubuntu only) Allows you to set a different repository for the installation of Nginx. As an example, if you are running Debian's wheezy release, and want to get a newer version of Nginx, you can install the wheezy-backports repository and set that value here, and Ansible will use that as the -t option while installing Nginx.

nginx_ppa_use: false
nginx_ppa_version: stable

(For Ubuntu only) Allows you to use the official Nginx PPA instead of the system's package. You can set the version to stable or development.

nginx_yum_repo_enabled: true

(For RedHat/CentOS only) Set this to false to disable the installation of the nginx yum repository. This could be necessary if you want the default OS stable packages, or if you use Satellite.

nginx_zypper_repo_enabled: true

(For Suse only) Set this to false to disable the installation of the nginx zypper repository. This could be necessary if you want the default OS stable packages, or if you use Suse Manager.

nginx_service_state: started
nginx_service_enabled: yes

By default, this role will ensure Nginx is running and enabled at boot after Nginx is configured. You can use these variables to override this behavior if installing in a container or further control over the service state is required.

Overriding configuration templates

If you can't customize via variables because an option isn't exposed, you can override the template used to generate the virtualhost configuration files or the nginx.conf file.

nginx_conf_template: "nginx.conf.j2"
nginx_vhost_template: "vhost.j2"

If necessary you can also set the template on a per vhost basis.

nginx_vhosts:
  - listen: "80 default_server"
    server_name: "site1.example.com"
    root: "/var/www/site1.example.com"
    index: "index.php index.html index.htm"
    template: "{{ playbook_dir }}/templates/site1.example.com.vhost.j2"
  - server_name: "site2.example.com"
    root: "/var/www/site2.example.com"
    index: "index.php index.html index.htm"
    template: "{{ playbook_dir }}/templates/site2.example.com.vhost.j2"

You can either copy and modify the provided template, or extend it with Jinja2 template inheritance and override the specific template block you need to change.

Example: Configure gzip in nginx configuration

Set the nginx_conf_template to point to a template file in your playbook directory.

nginx_conf_template: "{{ playbook_dir }}/templates/nginx.conf.j2"

Create the child template in the path you configured above and extend geerlingguy.nginx template file relative to your playbook.yml.

{% extends 'roles/geerlingguy.nginx/templates/nginx.conf.j2' %}

{% block http_gzip %}
    gzip on;
    gzip_proxied any;
    gzip_static on;
    gzip_http_version 1.0;
    gzip_disable "MSIE [1-6]\.";
    gzip_vary on;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/xml+rss
        application/xhtml+xml
        application/x-font-ttf
        application/x-font-opentype
        image/svg+xml
        image/x-icon;
    gzip_buffers 16 8k;
    gzip_min_length 512;
{% endblock %}

Dependencies

None.

Example Playbook

- hosts: server
  roles:
    - { role: geerlingguy.nginx }

License

MIT / BSD

Author Information

This role was created in 2014 by Jeff Geerling, author of Ansible for DevOps.

ansible-role-nginx's People

Contributors

3wille avatar benjamin-smith avatar bersace avatar bmcclure avatar danlamanna avatar dbaio avatar dearlordylord avatar edwinsteele avatar eriksencosta avatar geerlingguy avatar glaszig avatar icamys avatar jamieburchell avatar jon4hz avatar leventyalcin avatar lioman avatar mfriedenhagen avatar minitux avatar mtlynch avatar opdavies avatar oxyc avatar pedronofuentes avatar podarok avatar racke avatar robbyoconnor avatar russell-io avatar seeafish avatar shieldwed avatar techraf avatar thiagocaiubi 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ansible-role-nginx's Issues

Support for HTTP Auth

It would be a great feature, if you could control HTTP Authentication with this role, without writing an extension role for doing this. For example, if you could state a user : password variable and the role would automatically create the .htpasswd file and include it in the vhost on "location /".

server_name_redirect results in invalid vhost configuration

Setting server_name_redirect results in the following invalid vhost configuration file for me:

$ cat /etc/nginx/sites-enabled/foobar.com.conf
    listen       80;
    server_name  www.foobar.com;
    return       301 $scheme://foobar.com$request_uri;
}

server {

    listen 80;

    server_name foobar.com;

    root /home/wordpress/web;

    index index.php index.html index.htm;




}

This is quite an obvious effect from the vhost.j2 template, but maybe I'm missing something?

nginx_user should verify user exists?

Brand new to ansible, so maybe this is my ignorance.

That said, I ran this and expected it to check that if there was no user nginx (by default) that it would create one (or at least tell me).

After rebooting my VM, nginx didn't start because there wasn't a valid user account.

If this isn't The Ansible Way, that's fine (and there's a story for your book!)

error in vhosts.conf requires manual removal

If an error is accidentally injected into the vhosts.conf file, fixing it in the playbook won't take effect until the vhosts file is explicitly removed from the target host. I think this occurs because the nginx restart is attempted before the include of vhosts.yml. When there's an error in the vhosts file on the target host, the startup fails and the playbook halts before the new vhost.conf can be generated with the fix.

  • name: Ensure nginx is started and enabled to start at boot.
    service: name=nginx state=started enabled=yes
  • include: vhosts.yml

Can't set some http properties like gzip

I would be great to provide a hash to set generic values instead of specific variables like nginx_client_max_body_size...

-or-

Provide a dictionary of files to put in conf.d/

I need to configure compression :(

vhosts should be symlinked to sites-available

This is just a minor thing, but to follow convention with debian (or at least ubuntu, I think), the vhost configs usually go in /etc/nginx/sites-available/, and then get symlinked from in /etc/nginx/sites-enabled/

"Job for nginx.service failed..." while installing on RHEL7

[17:59:28][Step 5/7] 
[17:59:28][Step 5/7] TASK: [ansible-role-nginx | Include OS-specific variables.] ******************* 
[17:59:28][Step 5/7] ok: [SRV2-ELOG-VM52] => {"ansible_facts": {"__nginx_user": "nginx", "nginx_conf_path": "/etc/nginx/conf.d", "nginx_default_vhost_path": "/etc/nginx/conf.d/default.conf", "nginx_vhost_path": "/etc/nginx/conf.d"}}
[17:59:28][Step 5/7] 
[17:59:28][Step 5/7] TASK: [ansible-role-nginx | Define nginx_user.] ******************************* 
[17:59:28][Step 5/7] ok: [SRV2-ELOG-VM52] => {"ansible_facts": {"nginx_user": "nginx"}}
[17:59:28][Step 5/7] 
[17:59:28][Step 5/7] TASK: [ansible-role-nginx | Enable nginx repo.] ******************************* 
[17:59:28][Step 5/7] changed: [SRV2-ELOG-VM52] => {"changed": true, "checksum": "bff0bd4df6b8bccfb86c1b03fc1f1bc93fb7a0f2", "dest": "/etc/yum.repos.d/nginx.repo", "gid": 0, "group": "root", "md5sum": "c8473d7b3b6920ac8d59ac3ae6e843e0", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:system_conf_t:s0", "size": 99, "src": "/root/.ansible/tmp/ansible-tmp-1453301957.63-203060419101425/source", "state": "file", "uid": 0}
[17:59:28][Step 5/7] 
[17:59:28][Step 5/7] TASK: [ansible-role-nginx | Ensure nginx is installed.] *********************** 
[17:59:33][Step 5/7] changed: [SRV2-ELOG-VM52] => {"changed": true, "msg": "", "rc": 0, "results": ["Resolving Dependencies\n--> Running transaction check\n---> Package nginx.x86_64 1:1.8.0-1.el7.ngx will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package        Arch            Version                    Repository      Size\n================================================================================\nInstalling:\n nginx          x86_64          1:1.8.0-1.el7.ngx          nginx          369 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 369 k\nInstalled size: 889 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : 1:nginx-1.8.0-1.el7.ngx.x86_64                               1/1 \n----------------------------------------------------------------------\n\nThanks for using nginx!\n\nPlease find the official documentation for nginx here:\n* http://nginx.org/en/docs/\n\nCommercial subscriptions for nginx are available on:\n* http://nginx.com/products/\n\n----------------------------------------------------------------------\n  Verifying  : 1:nginx-1.8.0-1.el7.ngx.x86_64                               1/1 \n\nInstalled:\n  nginx.x86_64 1:1.8.0-1.el7.ngx                                                \n\nComplete!\n"]}
[17:59:33][Step 5/7] 
[17:59:33][Step 5/7] TASK: [ansible-role-nginx | Update apt cache.] ******************************** 
[17:59:33][Step 5/7] skipping: [SRV2-ELOG-VM52]
[17:59:33][Step 5/7] 
[17:59:33][Step 5/7] TASK: [ansible-role-nginx | Ensure nginx is installed.] *********************** 
[17:59:33][Step 5/7] skipping: [SRV2-ELOG-VM52]
[17:59:33][Step 5/7] 
[17:59:33][Step 5/7] TASK: [ansible-role-nginx | Remove default nginx vhost config file (if configured).] *** 
[17:59:33][Step 5/7] changed: [SRV2-ELOG-VM52] => {"changed": true, "path": "/etc/nginx/conf.d/default.conf", "state": "absent"}
[17:59:33][Step 5/7] 
[17:59:33][Step 5/7] TASK: [ansible-role-nginx | Add managed vhost config file (if any vhosts are configured).] *** 
[17:59:33][Step 5/7] changed: [SRV2-ELOG-VM52] => {"changed": true, "checksum": "0516a135a2151f0437ee4ebc160fc849600e8f2b", "dest": "/etc/nginx/conf.d/vhosts.conf", "gid": 0, "group": "root", "md5sum": "f9c8987ed3878b97a2a047122f64323f", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:httpd_config_t:s0", "size": 407, "src": "/root/.ansible/tmp/ansible-tmp-1453301968.32-140063811035792/source", "state": "file", "uid": 0}
[17:59:33][Step 5/7] 
[17:59:33][Step 5/7] TASK: [ansible-role-nginx | Remove managed vhost config file (if no vhosts are configured).] *** 
[17:59:33][Step 5/7] skipping: [SRV2-ELOG-VM52]
[17:59:33][Step 5/7] 
[17:59:33][Step 5/7] TASK: [ansible-role-nginx | Copy nginx configuration in place.] *************** 
[17:59:33][Step 5/7] changed: [SRV2-ELOG-VM52] => {"changed": true, "checksum": "a4ed36ad2818c5ed8dce3e445ea1eb28239d15ad", "dest": "/etc/nginx/nginx.conf", "gid": 0, "group": "root", "md5sum": "af905d0576cc9ac8844823806b19b2bc", "mode": "0644", "owner": "root", "secontext": "system_u:object_r:httpd_config_t:s0", "size": 776, "src": "/root/.ansible/tmp/ansible-tmp-1453301969.84-29133007962817/source", "state": "file", "uid": 0}
[17:59:33][Step 5/7] 
[17:59:33][Step 5/7] TASK: [ansible-role-nginx | Ensure nginx is started and enabled to start at boot.] *** 
[17:59:33][Step 5/7] failed: [SRV2-ELOG-VM52] => {"failed": true}
[17:59:33][Step 5/7] msg: Job for nginx.service failed. See 'systemctl status nginx.service' and 'journalctl -xn' for details.

Tried ansible 1.9.1 and 19.4.

add nginx_server_names_hash_bucket_size param

My server name is ec2-52-10-27-203.us-west-2.compute.amazonaws.com and I'm getting this error:

nginx: [emerg] could not build the server_names_hash, you should increase server_names_hash_bucket_size: 64

unfortunately the role doesn't give a possibility to override this setting now.

Thanks

vhost evaluation fails when role is wrapped and nested variables are used

I was trying to create an application role that uses this role as a dependency. In my application role, I pass in certain variables to your role including a vhost with a variable.

Example:

  - role: geerlingguy.nginx
    nginx_remove_default_vhost: true
    nginx_vhosts:
      - listen: "80 default_server"
        server_name: "_"
        root: "{{ PROJECT_APP_PATH }}/dist"

This causes the following error...

TASK: [geerlingguy.nginx | Add managed vhost config file (if any vhosts are configured).] *** 
fatal: [127.0.0.1] => Failed to template {% if [{'root': u'$/vagrant/dist', 'server_name': '_', 'listen': '80 default_server'}] %} True {% else %} False {% endif %}: template error while templating string: expected token ',', got 'string'

FATAL: all hosts have already failed -- aborting

I made a fix for this and will PR. Although I am not 100% sure why this behavior occurs when using the role as a dependency and not when using it directly. The issue seems to be related to the Jinja2 variable expansion as when I remove the variable, it works fine.

Fail to install newer Nginx on Debian 7

I'm running Debian 7 and setting nginx_default_release: "wheezy-backports" per instruction in the README to install a newer version of Nginx, but received this error

SystemError: E:The value 'wheezy-backports' is invalid for APT::Default-Release as such a release is not available in the sources

Any idea?

Add SELinux Rules On Red Hat Systems?

Just wondering if it seems appropriate to add the SELinux rules to permit nginx to be used without modification / post-task with Red Hat systems that have SELinux enabled?

Or does it seem more appropriate to let people manage that outside of the role itself? I could add a PR if it seems appropriate. I'd just add it to the setup-RedHat.yml probably, and then make it optional via a flag (default: false to match current resulting deploy).

Debian nginx_default_vhost_path is included in nginx.conf

nginx.conf includes two globs:

  • include /etc/nginx/conf.d/*.conf;
  • include /etc/nginx/sites-enabled/*.conf;

nginx_default_vhost_path is .../default on Debian thus it is not included by either of the includes. There should probably be a line including nginx_default_vhost_path if it is not scheduled for removal.

Configure the target server ip or hostname in nginx_upstreams varaible.

Hi,

I define these in the group_vars/nginx/nginx.yml, but it seems the target server IP is not intercepted.

How could I write the target server IP or hostname with the port in the nginx_upstreams varaibles?

nginx_upstreams:
  - name: backend_front
    servers: {
      "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}:8088"
    }
  
  - name: backend_manager
    servers: {
      "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}:8284"
    }
  
  - name: backend_tenant_manager
    servers: {
      "hostvars[inventory_hostname]['ansible_default_ipv4']['address']"
    }

/etc/nginx/nginx.conf


    upstream backend_front {
        server {{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}:8088;
    }
    upstream backend_manager {
        server {{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}:8284;
    }
    upstream backend_tenant_manager {
        server hostvars[inventory_hostname]['ansible_default_ipv4']['address'];
    }

Thanks,
James.

restarting nginx fails but it not noticed by ansible

NOTIFIED: [geerlingguy.nginx | restart nginx] *********************************
changed: [webs]

But in fact it fails:

root@webs:~# service nginx restart
 * Restarting nginx nginx                                               [fail] 
root@webs:~# echo $?
0
root@webs:~# service nginx restart | grep fail
   ...fail!
root@webs:~# 

I guess scraping the output is necessary in order to detect whether restarting succeeded. Or check afterwards whether the service is indeed running.

Add tags ?

Why not add some tags to improve the time to launch a playbook ?

Like :

  • nginx
  • nginx setup
  • nginx conf
    ...

Adding Location Block For PHPFPM

No matter what I try the extra_parameters variable in the vhosts will not accept a block for phpfpm configuration. What is the best way to do this? Multiline doesn't work inside of a dictionary it seems like.

        extra_parameters: >
            "location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
            }"

The above does not work as well as a number of other things I have tried. Any suggestions?

How to run this role via loop @ Ansible 2.x

Im newbie in ansivle configurations, but in readme.md file in secion about nginx_vhosts_filename setting i found this heplfull words If you run the role multiple times (e.g. include the role with with_items),.

So i tried to separate my vhosts into different files and could not find how to do this. Any ideas?

nginx restart causes task failure with multiple sources of nginx config

I overrode nginx.conf in my own role, dependent on this one, in order to add a new logging format. This starts to run into problems on later runs once I have vhosts deployed using my new logging format. The vhost files already exist, your role overwrites nginx.conf, and then before I can overwrite it again this line triggers a service restart that fails due to the vhosts depending on a missing logging format entry: https://github.com/geerlingguy/ansible-role-nginx/blob/master/tasks/main.yml#L28

IMO that task should just check that service=enabled, with a notify nginx restart to actually ensure it's running. That way all of the nginx configuration, including config from later-executing roles, will have been applied by the time nginx attempts a reload.

Create Diffie-Hellman parameter

Would be great if this role would allow the option to get the dhparam generated and set up.

https://raymii.org/s/tutorials/Strong_SSL_Security_On_nginx.html#Forward_Secrecy_&_Diffie_Hellman_Ephemeral_Parameters

What I used in my role:

- name: Generate strong DHE parameter
  command: openssl dhparam -out {{ nginx_dhparam_path }} {{ nginx_dhparam_size }}
  args:
    creates: "{{ nginx_dhparam_path }}"

And in the nginx.conf template I then simply add this to the http section:

ssl_dhparam {{ nginx_dhparam_path }};

so how does nginx gets installed on ubuntu?

---
- name: Add PPA for Nginx.
  apt_repository:
    repo: 'ppa:nginx/{{ nginx_ppa_version }}'
    state: present
    update_cache: yes
  register: nginx_ppa_added
  when: nginx_ppa_use

- name: Ensure nginx will reinstall if the PPA was just added.
  apt:
    name: nginx
    state: absent
  when: nginx_ppa_added.changed

so where does nginx gets installed???

Use official Nginx PPA for Debian/Ubuntu

It should be relatively simple to do this, and would allow people to use the stable or development releases of Nginx more easily (without having to configure the PPA themselves, as I suggested in #17 ).

It seems it may be as simple as adding a task like:

- name: Add repository for Nginx.
  apt_repository: repo='ppa:nginx/{{ nginx_ppa_version }}'

And nginx_ppa_version would be either stable or development.

More docs in the Nginx install page: http://wiki.nginx.org/Install

Add support for Drupal private files

At the moment DrupalVM is unable to serve private files in Drupal 8 due to a missing rule in nginx:

location ~ ^(/[a-z\-]+)?/system/files/ {
    try_files $uri /index.php?$query_string;
}

Perhaps this could be added.

Validation of nginx.conf fails if it have includes of pre-defined files (like fastcgi_params)

If nginx.conf or vhosts.conf have include fastcgi_params;, ansible fails on line 29 in tasks/main.yml (validate: 'nginx -t -c %s')

TASK: [geerlingguy.nginx | Copy nginx configuration in place.] **************** failed: [flugertest] => {"failed": true} msg: failed to validate: rc:1 error:nginx: [emerg] open() "/root/.ansible/tmp/ansible-tmp-1452489701.48-215325050721011/fastcgi_params" failed (2: No such file or directory) in /etc/nginx/sites-enabled/vhosts.conf:29 nginx: configuration file /root/.ansible/tmp/ansible-tmp-1452489701.48-215325050721011/source test failed

I suggest to remove this validation, because we already validate nginx configuration via handler.

Task 'Define nginx_user.' skipped

Defining the nxing_user is skipped even though the variable is defined in both defaults/main.yml and the playbook.yml

TASK [geerlingguy.nginx : Define nginx_user.] **********************************
skipping: [010php.vm]

This occurs on a debian based system. I may be able to provide a PR if I got the time.

Add default / simple virtualhost configuration

One thing that this role doesn't yet have, but is present in the geerlingguy.apache role and is extremely convenient for quick one-off servers or testing, is a simple mechanism for defining virtual hosts via role vars.

Nginx package not available from scratch

The playbook does not run the equivalent to apt-get update which means a fresh install of Debian 8.1 will fail to locate nginx (tested for Linode's Debian 8.1 standard image).

The role should require an apt update before it is run.

Best way to add extra parameters

I am trying to add the following to the extra parameters config:

error_log /var/log/nginx/symfony2.error.log;
access_log /var/log/nginx/symfony2.access.log;

# strip app.php/ prefix if it is present
rewrite ^/app\.php/?(.*)$ /$1 permanent;
rewrite ^/app_dev\.php/?(.*)$ /$1 permanent;

location / {
    index app_dev.php;
    try_files $uri @rewriteapp;
}

location @rewriteapp {
    rewrite ^(.*)$ /app_dev.php/$1 last;
}

# pass the PHP scripts to FastCGI server from upstream phpfcgi
location ~ ^/(app|app_dev|config)\.php(/|$) {
    fastcgi_pass phpfcgi;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param  HTTPS off;
}

But I get an error:

Failed to template {% if [{'extra_parameters': PARAMETER_STRING_HERE, ...my other parameters...] %} True {% else %} False {% endif %}: template error while templating string: expected token ',', got 'string'

Is there a better way of doing this? Ultimately, I think there is room for improvement here, at least location configs should be able to configured here.

Is it possible to use latest version of NGINX for Ubuntu?

What I need to specify in nginx_default_release variable to install the latest version of NGINX for this OS? I've tried "1.8.0" and "trusty". First variant was terminated with an error and second is installed the default stable version - "1.4.6".

Add `nginx_proxy_cache_path` configuration option

To configure Nginx as a reverse proxy, the nginx_proxy_cache_path option needs to be configurable. Leave it blank by default, but allow a user to set a value so server definitions can include proxy caching configuration.

"filename" configuration seems to be ignored

Even when I set "filename: foo" in the vars file, it gets ignored. A "grep" through source-code for "filename" has no hit, so I wonder if it is used at all.
Specifying a filename would be quite handy, as "server_name" can also include a RegEx-match string, which can result in filenames like "~^foo.blahr[0-9]" or similar unreadable filenames.

TIA

Better support for multiple vhost files

Per ansible/ansible#12623, with_items is not supported with roles in Ansible2. However, the current setup of the code is strongly geared toward a single nginx_vhosts_filename, and indeed the readme says

If you run the role multiple times (e.g. include the role with with_items), you can change the name for each run, effectively creating a separate vhosts file per vhost configuration.

The current recommendation seems to be to move the with_items into the role.

vhosts.j2 indentation

When creating vhosts, due to the way the jinja2 lines are placed, the indentation in the target file is all over the place. For example:

server {
    listen 80 default_server;

        server_name _;

        root /usr/share/nginx/html;

    index index.html index.htm;

            access_log /var/log/nginx/jenkins_access.log;
            error_log /var/log/nginx/jenkins_error.log error;


        location / {
    proxy_set_header        Host $host:$server_port;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto $scheme;
    proxy_pass              http://jenkins;
    proxy_read_timeout      90;
}

    }

By changing the vhosts.j2 file to this (which is identical functionally, but with the filters moved to position 0 on each line):

{% for vhost in nginx_vhosts %}
server {
    listen {{ vhost.listen | default('80 default_server') }};

{% if vhost.server_name is defined %}
    server_name {{ vhost.server_name }};
{% endif %}

{% if vhost.root is defined %}
    root {{ vhost.root }};
{% endif %}

    index {{ vhost.index | default('index.html index.htm') }};

{% if vhost.error_page is defined %}
    error_page {{ vhost.error_page }};
{% endif %}
{% if vhost.access_log is defined %}
    access_log {{ vhost.access_log }};
{% endif %}
{% if vhost.error_log is defined %}
    error_log {{ vhost.error_log }} error;
{% endif %}

{% if vhost.return is defined %}
    return {{ vhost.return }};
{% endif %}

{% if vhost.extra_parameters is defined %}
    {{ vhost.extra_parameters }}
{% endif %}
}
{% endfor %}

it outputs the file properly:

server {
    listen 80 default_server;

    server_name _;

    root /usr/share/nginx/html;

    index index.html index.htm;

    access_log /var/log/nginx/jenkins_access.log;
    error_log /var/log/nginx/jenkins_error.log error;


    location / {
        proxy_set_header        Host $host:$server_port;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;
        proxy_pass              http://jenkins;
        proxy_read_timeout      90;
    }

}

Disclaimer:
The vhost.extra_parameters will be incorrectly indented unless the actual block in the vars file is indented in a particular way. This is just how those YAML blocks work unfortunately. To get the neat indentation in the corrected example above, I did:

    extra_parameters: |
      location / {
              proxy_set_header        Host $host:$server_port;
              proxy_set_header        X-Real-IP $remote_addr;
              proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header        X-Forwarded-Proto $scheme;
              proxy_pass              http://jenkins;
              proxy_read_timeout      90;
          }

As you can see the first line is a normal 2 space YAML indent, but everything else is 4 space indented (the closing } with the proxy parameters 4 spaces in from that). This could be reflected in the README as well as in commented out examples in defaults.

Repo url needs updating for CentOS / EL 7

In files/nginx.repo, currently we have

baseurl=http://nginx.org/packages/centos/6/$basearch/

Changing 6 to 7 works for me, otherwise I get

msg: Error: Package: nginx-1.6.2-1.el6.ngx.x86_64 (nginx)
           Requires: libpcre.so.0()(64bit)

Looks like the version # in the url needs to be dynamic?

Exclude specific user agents

Hi,

I would like to exclude some specific user agents from my logs.
I need to add a map directive outside the server scope.
How can I add specific configurations in /etc/nginx/conf.d ?

How to geerling.nginx + geerling.php

Hi Jeff,

Sorry to bother you, but I've put a fair amount of time into trying to get the two roles working together and I've been unsuccessful. Do you have an example configuration that will get the two roles working together?

I've come close a couple of times, but the best I was able to do was to get nginx to execute index.php and then fail to load /test.php

Allow for extra 'listen' directives to enable ipv4/ipv6 simultaneously

My default http and https nginx configs contain:

  listen 80;
  listen [::]:80;

and

  listen 443 ssl http2;
  listen [::]:443 ssl http2;

But the role template currently only allows a single listen directive. You can of course sneak a 2nd one in with the extra_parameters option, but I assume we're going to be supporting ipv4/ipv6 simultaneously for many years to come

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.