Menu Close

List all EC2 Instances in AWS using Go SDK

In this article, we will are going to learn how to List all EC2 Instances in AWS using Go SDK with example in details.

Retrieving / List all EC2 instances in AWS refers to the process of obtaining information about every Amazon Elastic Compute Cloud (EC2) instance within an AWS account.

Retrieving all EC2 instances can help you:

  1. Monitor the status of your instances to ensure they are running as expected.
  2. Keep track of resource usage and allocation to optimize costs and performance.
  3. Identify and troubleshoot issues with specific instances.
  4. Maintain an inventory of your cloud resources for better organization and management.

Prerequisites to List all EC2 Instances in AWS using Go SDK :

  1. You should have an AWS account
  2. Go installed on your local machine (v1.16 or later).
  3. A basic understanding of Go programming

To begin, you’ll need to install the AWS SDK for Go. Open your terminal and run:

go get -u github.com/aws/aws-sdk-go

This command downloads and installs the SDK for Go.

Example to List all EC2 Instances:

package main


import (

	"fmt"

	"github.com/aws/aws-sdk-go/aws"

	"github.com/aws/aws-sdk-go/aws/session"

	"github.com/aws/aws-sdk-go/service/ec2"

)


// To retrieve all EC2 instances
func listInstances(svc *ec2.EC2) ([]*ec2.Instance, error) {

	input := &ec2.DescribeInstancesInput{}

	result, err := svc.DescribeInstances(input)

	if err != nil {

		fmt.Println("Error describing instances:", err)

		return nil, err

	}


	instances := make([]*ec2.Instance, 0)

	for _, reservation := range result.Reservations {

		for _, instance := range reservation.Instances {

			instances = append(instances, instance)

		}

	}

	return instances, nil

}

func main() {

	sess, err := session.NewSession(&aws.Config{

		Region: aws.String("us-west-2")},

	)

	if err != nil {

		fmt.Println("Error creating session:", err)

		return

	}


	svc := ec2.New(sess)

	
	instances, err := listInstances(svc)

	if err != nil {

		fmt.Println("Error listing instances:", err)

		return

	}


	fmt.Println("Number of instances:", len(instances))

	for _, instance := range instances {

		fmt.Printf("Instance ID: %s, State: %s\n", *instance.InstanceId, *instance.State.Name)

	}

}

Save your Go file and run it using the go run command. You should see output similar to the following:

Output:

Number of instances: 3
Instance ID: i-xxxxxxxx1, State: running
Instance ID: i-xxxxxxxx2, State: stopped
Instance ID: i-xxxxxxxx3, State: running

This output indicates that the program successfully retrieved all EC2 instances within your AWS account and displayed their instance IDs and states.

To learn more about golang, Please refer given below link.

https://techieindoor.com/golang-tutorial/

References:

https://en.wikipedia.org/wiki/Go_(programming_language)

Posted in AWS, Cloud, golang

Leave a Reply

Your email address will not be published. Required fields are marked *