DevOps, Day - 59

DevOps, Day - 59

Ansible Playbooks in actions for DevOps

1. Create 3 EC2 Instances with the Same Key Pair

You can use AWS CLI or AWS Management Console to create EC2 instances. Be sure to create them with the same key pair.

2. Install Ansible on the Host Server

SSH into the host server( select any 1 instance as your host server )

install Ansible in a host server

sudo apt update
sudo apt install ansible

3. Copy the Private Key from the Local to the Host Server

Assuming you have the private key on your local machine, you can use scp to copy it to the host server:

scp /path/to/your/key.pem ubuntu@your_host_server_ip:/home/ubuntu/.ssh/key.pem

Open your local machine or terminal --> navigate to your private key or .pem key and execute the command as shown below

we have successfully copied the private key to our remote server.

4. Access the Inventory File

in your local machine or terminal create a file for ansible_inventory as shown

vi ~/ansible_inventory

Add entries for your EC2 instances, for example:

[web]
ec2_instance_1 ansible_ssh_host=ec2_instance_1_ip ansible_ssh_private_key_file=/home/ubuntu/.ssh/key.pem
ec2_instance_2 ansible_ssh_host=ec2_instance_2_ip ansible_ssh_private_key_file=/home/ubuntu/.ssh/key.pem
ec2_instance_3 ansible_ssh_host=ec2_instance_3_ip ansible_ssh_private_key_file=/home/ubuntu/.ssh/key.pem

Create a folder in the host server as shown.

sudo mkdir -p /etc/ansible

Now copy the ansible_inventory file from the local to the host server as shown.

scp ~/ansible_inventory remote_user@remote_host:/path/to/ansible/inventory

5. Create a Playbook to Install Nginx

Create an Ansible playbook, e.g., install_nginx.yml, with the following content:

---
- name: Install Nginx
  hosts: web
  become: yes

  tasks:
    - name: Update package cache
      apt:
        update_cache: yes
      become: yes

    - name: Install Nginx
      apt:
        name: nginx
        state: present
      become: yes

    - name: Start Nginx service
      service:
        name: nginx
        state: started
      become: yes

This command will execute an Ansible playbook to install Nginx on remote servers specified in the inventory file using a provided SSH private key.

sudo ansible-playbook -i ~/ansible_inventory -e "ansible_ssh_private_key_file=/path/to/your/key.pem" install_nginx.yml

7. Execute the Ansible Playbook

Run the Ansible playbook to install Nginx and deploy the sample webpage on your EC2 instances:

ansible-playbook install_nginx.yml

This playbook will install Nginx and start the Nginx service on the specified instances. You should now be able to access your sample webpage using the public IP addresses of your EC2 instances in a web browser.


Thank you so much for reading

Follow me on LinkedIn to see interesting posts like this : )

Linkedin

Β