Ansible for AWS – Create an EC2 Instance with Ansible

Ansible for AWS

Ansible for AWS is a set of modules and playbooks designed to manage and automate tasks on Amazon Web Services (AWS). It allows you to provision and configure AWS resources like EC2 instances, S3 buckets, VPCs, and more using code. By using Ansible with AWS, you can automate cloud infrastructure deployment, scaling, and management.

In this guide, we’ll explore using Ansible to create and manage AWS EC2 instances with necessary AWS resources like VPC, Subnet, Internet Gateway, and Security Groups. Additionally, we’ll cover how to create an S3 bucket using Ansible.

Prerequisites

Before we start, ensure you have the following:

  • An AWS account
  • AWS CLI installed and configured
  • Ansible installed on your local machine
  • IAM user with appropriate permissions to create EC2 instances and other AWS resources

Setting Up Ansible for AWS

First, you need to install Ansible on your local machine. You can do this using pip.

 # pip3 install ansible

Ansible requires AWS credentials to interact with AWS services. You can configure these using the AWS CLI.

 # aws configure

This command will prompt you to enter your AWS Access Key ID, Secret Access Key, default region, and output format. Make sure these credentials have sufficient permissions to create and manage EC2 instances.

Creating an EC2 Instance with Ansible

Create a playbook named create_ec2.yml to create an EC2 instance with the necessary AWS resources.

---
- name: Create EC2 and necessary AWS resources
  hosts: localhost
  gather_facts: no
  vars:
    region: us-east-1
    instance_type: t2.micro
    ami_id: ami-04e5276ebb8451442
    vpc_cidr_block: 10.0.0.0/16
    subnet_cidr_block: 10.0.1.0/24
    security_group_cidr_ingress: 0.0.0.0/0
    security_group_cidr_egress: 0.0.0.0/0
    security_group_ports:
        - 80
        - 443

  tasks:
    - name: Create VPC
      amazon.aws.ec2_vpc_net:
        name: MyVPC
        cidr_block: "{{ vpc_cidr_block }}"
        region: "{{ region }}"
        tags:
          Name: MyVPC
      register: my_vpc

    - name: Output VPC ID
      debug:
        msg: "VPC ID is {{ my_vpc.vpc.id }}"
    
    - name: Create subnet
      amazon.aws.ec2_vpc_subnet:
        state: present
        vpc_id: "{{ my_vpc.vpc.id }}"
        cidr: "{{ subnet_cidr_block }}"
        region: "{{ region }}"
        tags:
          Name: MySubnet
      register: my_subnet

    - name: Output Subnet ID
      debug:
        msg: "Subnet ID is {{ my_subnet.subnet.id }}"
    
    - name: Create internet gateway
      amazon.aws.ec2_vpc_igw:
        vpc_id: "{{ my_vpc.vpc.id }}"
        region: "{{ region }}"
        tags:
          Name: MyIGW
      register: igw

    - name: Output Internet Gateway ID
      debug:
        msg: "Internet Gateway ID is {{ igw.gateway_id }}"

    - name: Create security group
      amazon.aws.ec2_group:
        name: "MySecurityGroup"
        description: "My security group"
        vpc_id: "{{ my_vpc.vpc.id }}"
        region: "{{ region }}"
        rules:
          - proto: tcp
            ports: "{{ security_group_ports }}"
            cidr_ip: "{{ security_group_cidr_ingress }}"
        rules_egress:
          - proto: all
            cidr_ip: "{{ security_group_cidr_egress }}"
      register: security_group

    - name: Output Security Group ID
      debug:
        msg: "Security Group ID is {{ security_group.group_id }}"
    
    - name: Launch instance
      amazon.aws.ec2_instance:
        name: "MyInstance"
        instance_type: "{{ instance_type }}"
        region: "{{ region }}"
        image_id: "{{ ami_id }}"
        subnet_id: "{{ my_subnet.subnet.id }}"
        wait: yes
        security_group: "{{ security_group.group_id }}"
        network:
          assign_public_ip: true
        tags:
          Environment: Testing
      register: ec2

    - name: Output Instance Details
      debug:
        msg: "Instance ID is {{ ec2.instances[0].instance_id }}"

In this playbook:

  • amazon.aws.ec2_vpc_net module is used to create a VPC.
  • amazon.aws.ec2_vpc_subnet module is used to create a subnet.
  • amazon.aws.ec2_vpc_igw module is used to create an Internet Gateway.
  • amazon.aws.ec2_group module is used to create a security group.
  • amazon.aws.ec2_instance module is used to launch the EC2 instance.
  • debug module is used to output various IDs and details for verification.

Now, run the above playbook using the following command.

 # ansible-playbook create_ec2.yml

Ansible will execute the tasks defined in the playbook, creating an EC2 instance with the necessary AWS resources as specified. Below is an example of what the output might look like:

create an ec2 instance with ansible

Managing EC2 Instances

Once you have created your EC2 instance, you may need to manage its state. Ansible can also help with this.

Starting and Stopping Instances

To start or stop an EC2 instance, you can use the amazon.aws.ec2_instance module with the appropriate state:

Here is an example playbook to start an EC2 instance.

---
- name: Start EC2 instance
  hosts: localhost
  gather_facts: False
  tasks:
    - name: Start instance
      amazon.aws.ec2_instance:
        instance_id: i-1234567890abcdef0
        state: started
        region: us-east-1
      register: ec2_start

Here is an example playbook to stop an EC2 instance.

---
- name: Stop EC2 instance
  hosts: localhost
  gather_facts: False
  tasks:
    - name: Stop instance
      amazon.aws.ec2_instance:
        instance_id: i-1234567890abcdef0
        state: stopped
        region: us-east-1
      register: ec2_stop

Terminating Instances

To terminate an EC2 instance, you can use amazon.aws.ec2_instance module with the state set to terminated:

---
- name: Terminate EC2 instance
  hosts: localhost
  gather_facts: False
  tasks:
    - name: Terminate instance
      amazon.aws.ec2_instance:
        instance_id: i-1234567890abcdef0
        state: terminated
        region: us-east-1
      register: ec2_terminate

Create an S3 Bucket Using Ansible

Creating an S3 bucket is another common task you might want to automate using Ansible. Below is an example playbook to create an S3 bucket:

---
- name: Create S3 Bucket
  hosts: localhost
  gather_facts: no
  vars:
    bucket_name: my-unique-bucket-name
    region: us-east-1

  tasks:
    - name: Create S3 bucket
      amazon.aws.s3_bucket:
        name: "{{ bucket_name }}"
        region: "{{ region }}"
        state: present
      register: s3_bucket

    - name: Output S3 Bucket Details
      debug:
        msg: "S3 Bucket {{ s3_bucket.name }} created in {{ s3_bucket.region }}"

In this playbook:

  • amazon.aws.s3_bucket module is used to create an S3 bucket.
  • debug module is used to output the details of the created S3 bucket for verification.

To execute the playbook, save it to a file called create_s3_bucket.yml and run the following command:

 # ansible-playbook create_s3_bucket.yml

Ansible will execute the tasks defined in the playbook, creating the S3 bucket as specified. Below is an example of what the output might look like:

create an s3 bucket with ansible

Conclusion

Ansible provides a straightforward and powerful way to manage AWS EC2 instances and other resources. By automating the creation, management, and termination of EC2 instances and S3 buckets, you can ensure consistency and reduce manual intervention in your cloud infrastructure.

Feel free to explore more Ansible modules and features to enhance your cloud automation workflows further. Happy automating!

FAQs

1. What prerequisites do I need to create an EC2 instance with Ansible?

You need an AWS account, AWS CLI installed, and appropriate IAM permissions to create EC2 instances.

2. How do I specify the region for the EC2 instance in Ansible?

You can specify the region using the region parameter in the Ansible playbook or inventory.

3. What Ansible modules are used for managing EC2 instances?

The primary modules are ec2, ec2_instance, and ec2_vpc_net for instance creation and management.

4. Is it possible to create multiple EC2 instances at once?

Yes, you can create multiple instances by specifying the desired count in the count parameter of the EC2 module.

About Hitesh Jethva

Experienced Technical writer, DevOps professional with a demonstrated history of working in the information technology and services industry. Skilled in Game server hosting, AWS, Jenkins, Ansible, Docker, Kubernetes, Web server, Security, Proxy, Iptables, Linux System Administration, Domain Name System (DNS), and Technical Writing.

View all posts by Hitesh Jethva