Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
List running EC2 instances with golang and aws-sdk-go

This is the beginning of hopefully many new posts with golang snippets from my blog. List all of your running (or pending) EC2 instances with Amazon's golang sdk.

For a list of filters or instance attributes consult the official documentation.

package main

import (

func check(e error) {

	if e != nil {

func main() {

	aws_user := os.Getenv("AWS_ACCESS_KEY_ID")
	aws_pass := os.Getenv("AWS_SECRET_ACCESS_KEY")

	creds := aws.Creds(aws_user, aws_pass, "")
	client := ec2.New(creds, "us-west-1", nil)

	// Only grab instances that are running or just started
	filters := []ec2.Filter{
			[]string{"running", "pending"},
	request := ec2.DescribeInstancesRequest{Filters: filters}
	result, err := client.DescribeInstances(&request)

	for _, reservation := range result.Reservations {
		for _, instance := range reservation.Instances {
Copy link

farrellit commented Aug 18, 2017

AWS API applications should not handle credentials like this. the standard session credentials chain will automatically check those environment variables, as well as other options like config files and the metadata service. If you're programming against the aws sdk, and you're not delegating to AWS for all credentials resolution, you're probably doing it wrong.

Thanks for the code example!

Copy link

DanielRis commented Sep 7, 2017

fmt.Println(*instance.InstanceID) should be fmt.Println(*instance.InstanceId)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment