How can I use the “AWS EC2 describe Instances” for retrieving the details?
I am currently engaged in a particular task that is related to managing large-scale applications hosted on AWS EC2 instances. My team needs to collect specific information about the running instance by using the AWS CLI. How can I use the “AWS EC2 describe Instances” command for retrieving the details such as Instance IDs, Instance types, public IP addresses, and availability zones in a single command output?
In the context of AWS, you can easily use the “aws EC2 describe Instances” command with the specific parameters to retrieve the required information. Here is how you can do so:-
#!/bin/bash
# Function to check if the AWS CLI is installed
Check_aws_cli() {
If ! command -v aws &>/dev/null; then
Echo “AWS CLI is not installed. Please install it before running this script.”
Exit 1
Fi
}
# Function to describe EC2 instances and output information
Describe_ec2_instances() {
Aws ec2 describe-instances
--query ‘Reservations[*].Instances[*].[InstanceId, InstanceType, PublicIpAddress, Placement.AvailabilityZone]’
--output table
}
# Check if AWS CLI is installed
Check_aws_cli
# Describe EC2 instances and output information
Echo “Retrieving information about EC2 instances…”
Describe_ec2_instances
Here is the example given in java programming language:-
Import com.amazonaws.auth.AWSStaticCredentialsProvider;
Import com.amazonaws.auth.BasicAWSCredentials;
Import com.amazonaws.client.builder.AwsClientBuilder;
Import com.amazonaws.services.ec2.AmazonEC2;
Import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
Import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
Import com.amazonaws.services.ec2.model.DescribeInstancesResult;
Import com.amazonaws.services.ec2.model.Instance;
Import com.amazonaws.services.ec2.model.Reservation;
Public class DescribeEC2Instances {
Public static void main(String[] args) {
// Replace these with your AWS access key ID and secret access key
String accessKey = “YOUR_ACCESS_KEY”;
String secretKey = “YOUR_SECRET_KEY”;
// Set up credentials
BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
// Set up AWS EC2 client
AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(“YOUR_AWS_REGION”)
.build();
// Describe EC2 instances
DescribeInstancesRequest request = new DescribeInstancesRequest();
DescribeInstancesResult result = ec2Client.describeInstances(request);
// Print instance information
For (Reservation reservation : result.getReservations()) {
For (Instance instance : reservation.getInstances()) {
System.out.println(“Instance ID: “ + instance.getInstanceId());
System.out.println(“Instance Type: “ + instance.getInstanceType());
System.out.println(“Public IP Address: “ + instance.getPublicIpAddress());
System.out.println(“Availability Zone: “ + instance.getPlacement().getAvailabilityZone());
System.out.println(“----------------------------------------“);
}
}
}
}
Here is the example given in python programming language:-
From flask import Flask, render_template, request
Import boto3
App = Flask(__name__)
@app.route(‘/’)
Def index():
Return render_template(‘index.html’)
@app.route(‘/describe’, methods=[‘POST’])
Def describe_instances():
Access_key = request.form[‘accessKey’]
Secret_key = request.form[‘secretKey’]
Region = request.form[‘region’]
# Set up AWS session
Session = boto3.Session(
Aws_access_key_id=access_key,
Aws_secret_access_key=secret_key,
Region_name=region
)
# Create EC2 client
Ec2_client = session.client(‘ec2’)
# Describe EC2 instances
Response = ec2_client.describe_instances()
# Extract instance information
Instance_info = []
For reservation in response[‘Reservations’]:
For instance in reservation[‘Instances’]:
Instance_id = instance[‘InstanceId’]
Instance_type = instance[‘InstanceType’]
Public_ip = instance.get(‘PublicIpAddress’, ‘N/A’)
Availability_zone = instance[‘Placement’][‘AvailabilityZone’]
Instance_info.append({
‘Instance ID’: instance_id,
‘Instance Type’: instance_type,
‘Public IP Address’: public_ip,
‘Availability Zone’: availability_zone
})
Return render_template(‘result.html’, instance_info=instance_info)
If __name__ == ‘__main__’:
App.run(debug=True)
Here is the method coding given in HTML:-
<meta</span> charset=”UTF-8”>
<meta</span> name=”viewport” content=”width=device-width, initial-scale=1.0”>
EC2 Instance Information
Instance ID | Instance Type | Public IP Address | Availability Zone |
---|---|---|---|
{{ instance[‘Instance ID’] }} | {{ instance[‘Instance Type’] }} | {{ instance[‘Public IP Address’] }} | {{ instance[‘Availability Zone’] }} |