Ansible playbooks are amazing, as you learned yesterday. What if you deploy a simple web app using ansible, sounds like a good project, right?
Task-01
- Create 3 EC2 instances . Make sure all three are created with same key pair
Launch 3 EC2 Instances with the same Private key pair, one will be the Ansible master and the remaining two will be nodes ( Ansible_Node1 and Ansible_Node2).
- Install Ansible in host server
Connect to Your EC2 Instance using SSH
Add the Ansible PPA (Personal Package Archive) to your instance
sudo apt-add-repository ppa:ansible/ansible
Update System Packages
Install Ansible
Verify Ansible Installation
- Copy the private key from local to Host server (Ansible_host) at (/home/ubuntu/.ssh)
Now, copy the private key pair from the local to the host server (Ansible master) at /home/ubuntu/.ssh
and paste the private key in the file
Copy the private key from your local.
Give permissions to the private key file using chmod command.
- Access the inventory file using sudo vim /etc/ansible/hosts
Create inventory file at location /etc/ansible/hosts which is by default location of the file. An Ansible hosts file is a configuration file that contains a list of hosts or servers. Add the IP addresses of the servers and also add private key file locations to use for authentication.
Use ansible-inventory --list -y
to check the list of hosts
- Create a playbook to install Nginx
Run the playbook using ansible-playbook command.
ansible-playbook file-name.yml
- Deploy a sample webpage using the ansible playbook
Create a new file index.html in the playbook directory, and add some content
Update the Ansible playbook file install_nginx.yml
in the playbook directory by providing the index.html file path, and the destination will be the default Nginx web server document root directory at /var/www/html/.
---
- name: playbook to install Nginx and deploy sample webpage
hosts: all
become: yes
tasks:
- name: Update apt package cache
apt:
update_cache: yes
- name: Install Nginx
apt:
name: nginx
state: latest
- name: Start Nginx
service:
name: nginx
state: started
- name: Deploy a sample webpage
copy:
src: /home/ubuntu/index.html
dest: /var/www/html/
become: true
become_user: root
become_method: sudo
This playbook will copy the index.html file to the default Nginx web server document root directory at /var/www/html/.
After successfully running the Ansible playbook, launch a web browser and navigate to the public IP address of any of the EC2 instances where Nginx is running.
Server1
Server2