Install Apache Server on Amazon Linux Using Ansible
Introduction:
In this article, you will see how to create an Apache web server using Ansible. The Apache server is an open-source web server and it’s widely used in Linux servers. Ansible is an automation tool which can be used for configuration automation.
Prerequisites :
EC2 instance with amazon Linux
Ansible installed on the local machine
(Refer to the documentation for installation https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html#installing-and-upgrading-ansible)
How Ansible works?
Ansible is an agentless automation tool. That means unlike puppet or chef you don’t need to install any agent on remote machines. Ansible connects to the remote machines using ssh. Therefore it requires the IP addresses and private ssh key files to connect to the remote machines. This data can be provided to the ansible using an inventory file.
Ansible uses playbooks to perform actions on the remote machines. These playbooks are YAML files which contain plays (instructions).
Project directory:
Step 1:
Create an inventory file for Ansible like the following
File name: hosts
Recommended by LinkedIn
[ec2]
<Ip addresses of ec2 instances (use single line for each ip address)>
[ec2:vars]
ansible_user=ec2-user
ansible_ssh_private_key_file=<path to your private ssh key file>
Step 2:
Create an Ansible playbook file named apache.yaml
File name: apache.yaml
---
- name: Install apache server # name of the playbook
hosts: ec2 # target group defined in the inventory file
become: yes
tasks:
- name: install apache server # name of the play
yum:
name: httpd
state: latest
update_cache: yes
- name: start and enable autostart of apache server
systemd:
name: httpd
state: started
enabled: yes
The ‘become: yes’ attribute ensures to run the following plays as the root user. Here we are using the ‘yum’ module to install the latest httpd server. The ‘systemd’ module is used to start the httpd service and to make sure that httpd autostarts on every reboot. The ‘update_cache: yes’ is equivalent to ‘yum update’.
Documentation for the modules:
Step 3:
Run the Ansible playbook using the following command.
$ ansible-playbook Apache.yaml -i hosts
And you’ll see the following output.