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.
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.
<header> <h1>Hello World. I am an nginx application. Thanks for visiting me!</h1> </header>
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.
#nginx.yml --- - hosts: 192.168.56.3 user: root tasks: - name: Add epel-repo yum: name: epel-release state: present - name: Install Nginx yum: name: nginx state: present - name: add index.html file template: src: ./index.html dest: /usr/share/nginx/html/index.html - name: allow all access to tcp port 80 firewalld: port: 80/tcp zone: public state: enabled - name: Start Nginx service: 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 curl 192.168.56.3:80
You can also view the webpage by going to
192.168.56.3:80 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.