Ansible script to get state of EC2 instances

Share

Ansible is a configuration management tools that handles a wide range of Daily IT operational, automate configuration management, including cloud provisioning, package management, application deployment, and intra-service orchestration.

In this blog, we will create an ansible script to get the state of EC2 instances. First we will install awscli in our host machine so that we can create a profile to connect to AWS infrastructure.

Step1: Install awscli and configure a user profile

  • Use the following commands to install awscli.
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
  • Create a user profile with following command.
aws configure
  • You will need to provide access key id and secret access key of an IAM account to configure user profile.

Step2: Install boto and boto3

  • Use the following command to install boto, boto3, and botocore
pip3 install boto boto3

Step3: Run the ansible script

  • Create a file in your directory and paste the following script there.

---
- name: test aws ec2
  hosts: localhost
  connection: local
  gather_facts: False

  vars_prompt:
          name: region
          prompt: Enter the region
          private: no
  tasks:

    - name: Gathers facts (instance metadata) about remote hosts remote ec2 (all)
      ec2_instance_facts:
        region: "{{ region }}"
      register: ec2_metadata

    - debug:
        msg: "  Instance ID: {{ item.instance_id }}         State: {{ item.state.name }} "
      with_items: "{{ ec2_metadata.instances }}"
      loop_control:
        label: "{{ item.instance_id }}"

  • Run the script with the ansible playbook command.

Ansible

This blog is written by Amit Kumar, Director of engineering, at Checkmate Global Technologies. he has worked with worked with various other startups related to mobile app development, Web Development, and  Cloud DevOps production operation management. Please contact with him to discuss cloud infrastructure and SaaS based product engineering.

Leave a Reply

Your email address will not be published.

*