Activity:Create an EC2 instance & Install packages using Ansible


Install PIP and BOTO & then EC2
  • sudo apt-get install python-pip
  • pip install boto
































- name: Create a new Demo EC2 instance
  hosts: 127.0.0.1
  gather_facts: False

  vars:
      region: us-east-1
      instance_type: t2.micro
      ami: ami-07d0cf3af28718ef8  # Ubuntu
      keypair: n # pem file name

  tasks:

    - name: Create an ec2 instance
      ec2:
         key_name: "{{ keypair }}"
         aws_access_key: "AKIAJ33XMSCSCPBL7RB5ZA"
         aws_secret_key: "pIa38SDaJYSSDCSDc9DGORKyTS5sQSchJiqu/F"
         group: launch-wizard-1  # security group name
         instance_type: "{{ instance_type}}"
         image: "{{ ami }}"
         wait: true
         region: "{{ region }}"
         count: 1  # default
         count_tag:
            Name: "Demo"
         instance_tags:
            Name: "Demo"
         vpc_subnet_id: "subnet-afeab7f3"
         assign_public_ip: yes
      register: ec2





    - name: Add instance to host group
      add_host:
        hostname:  "{{ item.private_ip }}"
        groups:
        - launched
      with_items: "{{ ec2.instances }}"

    - debug:
        msg: Remote IP is "{{ item.public_ip }}"
      with_items: "{{ec2.instances }}"

    - name: Add in inventory file
      lineinfile:
        path: /home/ubuntu/dev
        insertafter: '^[web]'
        line: "{{ item.private_ip }}"
      with_items: "{{ec2.instances }}"

    - local_action: "wait_for host={{ item.public_ip }} port=22 state=started"
      name: "Wait for EC2 Instance to Spin-up and ready for SSH access"
      with_items: "{{ec2.instances }}"
   
    - name: SSH Key Export
      shell: cat ~/.ssh/id_rsa.pub | ssh -i key.pem ubuntu@{{ item.private_ip }} "cat >> ~/.ssh/authorized_keys"
      become_user: ubuntu
      delegate_to: localhost
      with_items: "{{ ec2.instances }}"

    - name: Install Python
      shell:
        ssh ubuntu@{{ item.private_ip }}
        sudo apt install python -y
      with_items: "{{ ec2.instances }}"

    - name: Refresh Inventory
      meta: refresh_inventory

- name: Configure Instance
  hosts: web
  become: true
  gather_facts: true
  tasks:
    - name: "Install Apache"
      apt: name=apache2 state=present update_cache=yes
 
    - name: "Install NTP"
      apt: name=ntp state=present update_cache=yes





In this article, will create AWS instances, SG and RDS database in Ansible. Ansible helps you automate your AWS infrastructure securely and reliably. Compared to cloud formation which majority of DevOps engineers use it to automate their AWS infrastructure Ansible provides an alternative. Unlike cloud formation which restricts you to only AWS services, Ansible provides more than 20 libraries which can do much than AWS resources.
For us to begin, we first need to create an IAM user. We would need the AWS Access Key ID and Secret Access Key. The IAM role needs to have access to the following policies:
  1. AmazonEC2FullAccess.
  2. AmazonVPCFullAccess.
  3. AmazonRDSFullAccess.
Note: You can restrict the policy based on your requirements.

How to create a Security Group in Ansible

The ec2_group module is responsible for managing security groups in AWS. To create a security group we first need to determine in which region are we going to host our services. The region code needs to be passed to the regionparameter. A list of region codes can be found on the region page.
In the below example we are creating a security group in “us-east-2” allowing the port  80 with cidr_ip 0.0.0.0/0.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- hosts: localhost
  connection: local
  gather_facts: false
  tasks:
      - name: create a security group in us-east-2
        ec2_group:
          name: dmz
          description: an example ec2 group
          region: us-east-2
          aws_access_key: "AKIAIWJUADQPQB16LCFI"
          aws_secret_key: "NCMx885+nNU51sKuprQeZeVsU9arRZc7hAX7Itez"
          rules:
            - proto: tcp
              from_port: 80
              to_port: 80
              cidr_ip: 0.0.0.0/0
        register: security_group
We store the output in the variable “security_group“.
We can access the following data using the output variable:
  • group_id: Security Group ID (Will use the group_id to assign the instance to it)
  • vpc_id: The unique ID of the VPC which the security group belongs to.
  • ip_permissions: the inbound rules assigned to this security group.
  • description: of the security group.
  • tags: associated tags.
  • group_name: name of the security group.
  • ip_permissions_egress: outbound rules.
  • owner_id: AWS account ID

How to create an AWS EC2 Instance using Ansible

To create EC2 instances, will use the ec2 module. The ec2 module allows us to perform the below operations on instances :
  • start
  • stop
  • terminate
  • stop
In the example below, will create a free tier Linux EC2 instance in the us-east-2 region and assign it to the security group created earlier.
1
2
3
4
5
6
7
8
9
10
11
12
13
- name: create ec2 instance
        ec2:
          aws_access_key: "AKIAIWJUADQPQB16LCFI"
          aws_secret_key: "NCMx885+nNU51sKuprQeZeVsU9arRZc7hAX7Itez"
          image: ami-caaf84af
          wait: yes
          instance_type: t2.micro
          group_id: security_group.group_id
          region: us-east-2
          count_tag:
            Name: apacheserver
          exact_count: 1
        register: ec2
Exact_Count determines the number of instances to launch
How to find an AMI Image ID?
The easiest way to find an AMI image ID is by trying to launch an instance. The image ID is displayed beside the image the name. (highlighted in yellow)

How to launch an EC2 Instance with SSD Volume

To select the volume type, you would need to use the “volume” option.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- name: create an EC2 instance with SSD volume type
  ec2:
    key_name: mykey
    group: webserver
    instance_type: c3.medium
    image: ami-123456
    wait: yes
    wait_timeout: 500
    volumes:
      - device_name: /dev/xvda
        volume_type: gp2  #insert the volume code here
        volume_size: 8  #size is in GB
    group_id: security_group.group_id
    count_tag:
      Name: apacheserver
    exact_count: 1
Different types of volume type codes
General Purpose SSDgp2
Provisioned IOPS SSDio1
Throughput Optimized HDDst1
Cold HDDsc1

How to create a Free tier RDS Database instance in Ansible

In this example, will launch an RDS instance in us-east-2 with a storage capacity of 20 GB.
1
2
3
4
5
6
7
8
9
10
11
12
13
- name: create RDS instance
        rds:
         command: create
         region: us-east-2
         instance_name: infinityppdatabase
         db_engine: MySQL
         size: 20 # determines the storage size in GB
         instance_type: db.t2.micro
         username: mysql_admin
         password: 1nsecure
         tags:
           Environment: testing
           Application: cms
size determines the storage capacity in GB

To download the code, please visit our Github page.

If the services are not being created, please ensure you have the right permission.

Conclusion:

Managing AWS resources using Ansible can be extremely efficient and easy. With Ansible you can use other resources such as Cloudflare or trigger NewRelic events in your continuous deployment or DevOps process.



Post a Comment

Previous Post Next Post