-
-
Save subfission/2f7fb6a8dad8dcf2b57bc1dfdc2d6dd9 to your computer and use it in GitHub Desktop.
List running EC2 instances with golang and aws-sdk-go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
List all of your running (or pending) EC2 instances with Amazon golang sdk. | |
For a list of filters or instance attributes consult the [official documentation](http://godoc.org/github.com/awslabs/aws-sdk-go/gen/ec2#Instance). | |
*/ | |
package main | |
import ( | |
"fmt" | |
"github.com/awslabs/aws-sdk-go/aws" | |
"github.com/awslabs/aws-sdk-go/gen/ec2" | |
"os" | |
) | |
func check(e error) { | |
if e != nil { | |
panic(e) | |
} | |
} | |
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{ | |
ec2.Filter{ | |
aws.String("instance-state-name"), | |
[]string{"running", "pending"}, | |
}, | |
} | |
request := ec2.DescribeInstancesRequest{Filters: filters} | |
result, err := client.DescribeInstances(&request) | |
check(err) | |
for _, reservation := range result.Reservations { | |
for _, instance := range reservation.Instances { | |
fmt.Println(*instance.InstanceId) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment