3

I am writing an ansible script to deploy django in centos 7. My problem is with nginx.

I have created /etc/nginx/sites-available and /etc/nginx/sites-enabled directories and have to include sites-available in /etc/nginx/nginx.conf file at the bottom if http { } block.

How do I insert the line include /etc/nginx/sites-available/*.conf inside the http {} block in my ansible script after creating the respective directories and copying the configuration files?

The output should be

http {
    .....
    .....

    server {
        .......
    }

    include /etc/nginx/sites-available/*.conf;
}
Eutychus
  • 442
  • 8
  • 12

2 Answers2

1

You can use the lineinfile module. Something like this should work:

- lineinfile: dest=/etc/nginx/nginx.conf regexp="^include /etc/nginx/sites-available/*.conf;" insertbefore="server {" line="include /etc/nginx/sites-available/*.conf;"

This will insert the line before the server block. You can play around with insertbefore and insert after and different regular expressions.

Károly Nagy
  • 1,734
  • 10
  • 13
  • I think the issue with this is this has the potential to insert more than one line if there's more than one `server {` phrase defined in the default config. – Arcsector Dec 08 '22 at 01:54
1

Don't use lineinfile you will regret it at some point. Everybody does.

You should create a template and then load that with ansible.

#file: templates/nginx.conf.j2
http {
    .....
    .....

    server {
        .......
    }

    include /etc/nginx/sites-available/*.conf;
}

#file: main.yml
- name: "Load nginx config"
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf

This will make the management of your config much easier if you need to change anything in the config file.

Docs: Template Module

shaps
  • 1,159
  • 6
  • 12
  • 1
    I did not want to copy the whole nginx.conf file to a template just to add the include line. Are you advising that its the better solution that lineinfile? – Eutychus May 09 '16 at 11:40
  • 1
    yes, believe me, you will regret using `lineinfile` at some point ;) Having nginx.conf as a template is good anyway, you might want to change something later and you will have to do it anyway :) – shaps May 09 '16 at 15:52