First Ansible Playbook!
Setting Up a Web Server with Ansible
Ansible, the simple, yet powerful IT automation tool, allows users to set up and manage infrastructure seamlessly. In today's post, we will explore a simple Ansible playbook that sets up a web server on RedHat-based systems and presents the system's hostname on a web page.
The Playbook in Focus: run_httpd.yml
---
- name: Run a web server
hosts: redhat
become: yes
tasks:
- name: Check if apache is installed
yum:
name: httpd
state: present
- name: Start HTTPD and enable it
service:
name: httpd
state: started
enabled: yes
- name: Set content of index.html with hostname
copy:
content: |
<html>
<head><title>Welcome to {{ ansible_hostname }}</title></head>
<body>
<h1>This server's hostname is: {{ ansible_hostname }}, Using ANSIBLE PLAYBOOK!</h1>
</body>
</html>
dest: /var/www/html/index.html
notify: Restart HTTPD
handlers:
- name: Restart HTTPD
service:
name: httpd
state: restarted
Breaking Down the Playbook
1. Overview: The playbook is named "Run a web server". It targets hosts under the group redhat and escalates privileges using become: yes, ensuring that it has the necessary permissions for the operations.
2. Checking and Installing Apache: The first task uses the yum module to ensure the Apache HTTP Server (httpd) package is installed. If it's not, Ansible will install it.
3. Starting and Enabling HTTPD: Next, the playbook ensures that the httpd service is started and enabled to boot up at system startup.
4. Setting Up the Web Page: The playbook then creates an index.html file inside the /var/www/html directory, which is the default document root for Apache in RedHat-based systems. The web page will display the hostname of the server.
5. Handlers and Restarting HTTPD: Lastly, if the content of index.html changes, the playbook will restart the httpd service to reflect the changes. This is done using Ansible's handlers, which are tasks that only run when notified.
Conclusion
This Ansible playbook provides an illustrative example of how to set up a basic web server and display dynamic content. By leveraging Ansible's idempotent nature, this playbook ensures that your web server is consistently set up across multiple runs.
Whether you're new to Ansible or an experienced user, this playbook serves as a reminder of the simplicity and efficiency that Ansible brings to infrastructure management.
Last updated