Thursday, January 18, 2024

Ansible Playbook for provisioning a new EC2 in AWS | Create new EC2 instance in AWS cloud using Ansible Playbook

We will learn how to create a simple Ansible Playbook for provisioning a new EC2 instance in AWS cloud. Please follow the below steps in the machine where you have installed Ansible.

Pre-requisites:
Steps to create EC2 instance using Ansible:

Login to EC2 instance using Git bash or iTerm/putty where you installed Ansible. Execute the below command:

Create an Inventory file first

sudo mkdir /etc/ansible

Edit Ansible hosts or inventory file
sudo vi /etc/ansible/hosts

Add the below two lines in the end of the file:
[localhost]
local


cd ~
mkdir playbooks  
cd playbooks

Create Ansible playbook
sudo vi create-ec2.yml 
(copy the below content in green color)
edit the create-ec2.yml to make sure you update the key, AMI and region code which is red marked below:

- name: Ansible ec2 launch
  hosts: localhost
  connection: local
  gather_facts: False
  tags: provisioning

  vars:
    keypair: myNov2023Key
    instance_type: t2.small
    instance_name: test-ec2-instance
    image: ami-007855ac798b5175e
    wait: yes
    group: webserver
    region: us-east-1
    security_group: my-jenkins-security-grp1

  tasks:
  - name: configuring security group for the instance
    ec2_group:
        name: "{{ security_group }}"
        description: my-jenkins-security_group
        region: "{{ region }}"
        rules:
            - proto: tcp
              from_port: 22
              to_port: 22
              cidr_ip: 0.0.0.0/0
            - proto: tcp
              from_port: 80
              to_port: 80
              cidr_ip: 0.0.0.0/0
            - proto: tcp
              from_port: 8080
              to_port: 8080
              cidr_ip: 0.0.0.0/0
        rules_egress:
            - proto: all
              cidr_ip: 0.0.0.0/0
  - name: creating ec2 instance
    ec2_instance:
        security_group: "{{ security_group }}"
        name: "{{ instance_name }}"
        key_name: "{{ keypair }}"
        instance_type: "{{ instance_type}}"
        image_id: "{{ image }}"
        region: "{{ region }}"
        wait_timeout: 3

now execute the ansible playbook by
ansible-playbook create_ec2.yml




If everything is good, you should see the new instance created on AWS console. make sure you are able to connect to that instance.

That's it!! That is how you create a new EC2 instance using Ansible. 

Watch steps in YouTube channel:

No comments:

Post a Comment

How to configure Self-Hosted GitHub Actions Runner | How to install Self-Hosted GitHub Actions Runner | Configure EC2 instance as self-hosted runner in GitHub Actions

A self-hosted GitHub runner is a machine (physical or virtual) that you set up and manage to run GitHub Actions workflows.  A self-hosted ru...