Setup Webserver with Ansible

Configuration management tools come in handy when configuring multiple servers. Not only for speed but also reliability.


Let us list down the steps we would take to configure it manually.

I - Install apache httpd (Check if installed)

II - Create the document root directory incase you wish to override the original configuration

III - Copy your webpages to that folder

IV - Create configuration in /etc/httpd/conf.d/

V - Start / Check if httpd service running

VI - Allow specified port in firewall

VII - Incase config file is modified, we would need to restart httpd service. We'll use handlers for that purpose


This is my config file: httpd.j2

I've decided to change DocumentRoot and Port number

Listen {{ portnum }}


<VirtualHost {{ ansible_facts["default_ipv4"]["address"]}}:{{ portnum }}>
DocumentRoot {{ docroot }}
</VirtualHost>

Note the use of facts to configure the file dynamically.


Playbook: websetup.yml

You can see I've used variables for DocumentRoot and Port Number so that script can run dynamically.

---
- hosts: webservers
  vars:
    - docroot: "/var/www/ishan"
    - portnum: 81
  tasks:
    - name: httpd install(ed)
      package:
        name: "httpd"
        state: present
    - name: create document root directory
      file:
        path: "{{ docroot }}"
        state: directory
        owner: "apache"
    - name: copy webpages
      copy:
        src: "webpages/"
        dest:  "{{ docroot }}"
    - name: httpd configuration
      template:
        src: "httpd.j2"
        dest: "/etc/httpd/conf.d/ishan.conf"
      notify:
        - Restart Httpd
    - name: start or check running httpd
      service:
        name: httpd
        state: started
        enabled: yes
    - name: firewall allow
      firewalld:
        port: "{{ portnum }}/tcp"
        state: enabled
        permanent: yes
  handlers:
    - name: Restart Httpd
      service:
        name: httpd
        state: restarted

You can see that handler is triggered to restart the httpd service only when the config file is changed. Hence no need to keep restarting it every run and waste resources.


Run the playbook:

#ansible-playbook websetup.yml

Do not forget to configure your inventory and create a webpages folder.

No alt text provided for this image
No alt text provided for this image

There you go !

To view or add a comment, sign in

More articles by Ishan Singhal

Others also viewed

Explore content categories