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.

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:

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

    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

  - name: configuring security group for the instance
        name: "{{ security_group }}"
        description: my-jenkins-security_group
        region: "{{ region }}"
            - proto: tcp
              from_port: 22
              to_port: 22
            - proto: tcp
              from_port: 80
              to_port: 80
            - proto: tcp
              from_port: 8080
              to_port: 8080
            - proto: all
  - name: creating 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

Top 10 DevOps Popular Tools | Popular DevOps Tools You Must Know In 2024 | Learn DevOps Tools in 2024

Here are the top 10 DevOps Tools to focus on to put your DevOps learning on a  faster track  and kick start your career quickly as a success...