DEV Community

Cover image for Configure a Web Server with Ansible Playbook
Tu Van Nguyen
Tu Van Nguyen

Posted on

Configure a Web Server with Ansible Playbook

If you ever need to configure an army of servers, then Ansible playbooks are your best friend. Playbooks are YAML files that contain desired state of the "hosts", the remote machines that Ansible controls. In this tutorial, we are going to create a playbook that sets up a web server on a virtual machine. This virtual machine is a managed node for Ansible, and you can see how to set it up in this other tutorial.

Write the webpage

This is just a very simple html page that we'll write on the local machine. Name it index.html. Later on, this file will be transferred to the managed node.

 <h1>Hello World. I am an nginx application. Thanks for visiting me!</h1>

Write the Playbook

The web server we'll be using is Nginx. We will write a simple playbook that tells Ansible that the managed host should have nginx installed and running. We communicate this by writing tasks, a task being the unit of action in Ansible. Tasks related to installation use the yum module for the package manager of CentOS on the virtual machine. The third task adds the index.html file from the local machine to the managed node. Then in the fifth task, we open tcp port 80 so that we can access the webpage from the local machine's browser. The final task starts the nginx service.

 - hosts:
   user: root
    - name: Add epel-repo
       name: epel-release
       state: present

    - name: Install Nginx
       name: nginx
       state: present

    - name: add index.html file
       src: ./index.html
       dest: /usr/share/nginx/html/index.html

    - name: allow all access to tcp port 80
       port: 80/tcp
       zone: public
       state: enabled

    - name: Start Nginx
       name: nginx
       state: started


Now we can run the playbook and test the web server from the local machine or control node.

ansible-playbook nginx.yml

You can also view the webpage by going to on your web browser.

And that's all you need to do to set up the web server. After using Ansible for a while, consider getting a That Was Easy button for every time you can sit back and let Ansible do all the work for you.

Top comments (0)