Today we study an example of using Ansible to configure nginx.
We create an Ansible playbook named web-notls.yml.
Type the following commands:
- name: Configure webserver with nginx hosts: host1 become: yes become_user: root become_method: su tasks: - name: install nginx yum: name=nginx - name: create sites-available directory file: path=/etc/nginx/sites-available state=directory mode=0755 - name: copy nginx config file copy: src=files/nginx.conf dest=/etc/nginx/sites-available/default - name: create sites-enabled directory file: path=/etc/nginx/sites-enabled state=directory mode=0755 - name: enable configuration file: > dest=/etc/nginx/sites-enabled/default src=/etc/nginx/sites-available/default state=link - name: copy index.html template: src=templates/index.html.j2 dest=/usr/share/nginx/html/index.html mode=0644 - name: restart nginx service: name=nginx state=restarted
We need to extra files.
1) files/nginx.conf
server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; server_name localhost; location / { try_files $uri $uri/ =404; }}
2) templates/index.html.j2
Welcome to ansible nginx, configured by Ansible
If you can see this, Ansible successfully installed nginx.
{
{ ansible_managed }}
Then, we run ansible-playbook and got an error:
TASK [restart nginx] *****************************************************************************************************************************fatal: [host1]: FAILED! => {"changed": false, "failed": true, "msg": "Unable to start service nginx: Job for nginx.service failed because the control process exited with error code. See \"systemctl status nginx.service\" and \"journalctl -xe\" for details.\n"}
Why is that?
After running
systemctl status nginx.service
The output is
nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)
If we run
lsof-i -P -n
It is found that
httpd ....................TCP *:80 (LISTEN)
Port 80 was used by httpd.
After we stopped httpd, the error disappeared.
Then we type "localhost" in a web browser, we got the following words printed:
nginx, configured by Ansible
If you can see this, Ansible successfully installed nginx.
Ansible managed