Deploying Multiple EC2 Instances with Ansible: A Hands-On Guide

Deploying Multiple EC2 Instances with Ansible: A Hands-On Guide

Creating multiple EC2 instances using Ansible can streamline your infrastructure management and make deployments consistent and repeatable. In this blog post, we'll walk through the steps to create three EC2 instances with different ami's using a provided Ansible YAML file.

Prerequisites

Before we begin, ensure you have the following:

  1. AWS Account: Access to create EC2 instances.

  2. AWS Access Key and Secret Key: To authenticate with the AWS API.

  3. Ansible Installed: Ansible must be installed on your local machine.

  4. Ansible Amazon AWS Collection: The Ansible collection for AWS should be installed. You can install it with:

     ansible-galaxy collection install amazon.aws
    

Ansible YAML File

Below is the Ansible YAML file that will create three EC2 instances:

---
- hosts: localhost
  connection: local

  tasks:
  - name: Create EC2 instances
    amazon.aws.ec2_instance:
      name: "{{ item.name }}"
      key_name: "Prod-01" #Give your key name
      instance_type: t2.micro
      security_group: default
      region: ap-south-1
      aws_access_key: "{{ lookup('env', 'AWS_ACCESS_KEY_ID') }}"  # From environment variable
      aws_secret_key: "{{ lookup('env', 'AWS_SECRET_ACCESS_KEY') }}"  # From environment variable
      network:
        assign_public_ip: true
      image_id: "{{ item.image }}"
      tags:
        environment: "{{ item.name }}"
    loop:
      - { image: "ami-0e1d06225679bc1c5", name: "manage-node-1" } # Update AMI ID according 
      - { image: "ami-0f58b397bc5c1f2e8", name: "manage-node-2" } # to your account
      - { image: "ami-0f58b397bc5c1f2e8", name: "manage-node-3" }

Prepare Your AWS Credentials

For security reasons, it's best to store your AWS credentials in an Ansible vault or as environment variables. For simplicity, we'll assume you have them stored as environment variables. You can export them as follows:

export AWS_ACCESS_KEY_ID='your_access_key'
export AWS_SECRET_ACCESS_KEY='your_secret_key'

Run the Ansible Playbook

Save the YAML content to a file, say ec2_create.yaml. Then run the playbook using the ansible-playbook command:

ansible-playbook ec2_create.yaml

Output:

Step 5: Verify the EC2 Instances

After running the playbook, go to the AWS Management Console and navigate to the EC2 dashboard. You should see three new EC2 instances named manage-node-1, manage-node-2, and manage-node-3

Did you find this article valuable?

Support Tarun Varma by becoming a sponsor. Any amount is appreciated!