Skip to content

Instantly share code, notes, and snippets.

@simeji
Last active May 29, 2023 20:09
Show Gist options
  • Save simeji/945165da059d2f4ef4bf to your computer and use it in GitHub Desktop.
Save simeji/945165da059d2f4ef4bf to your computer and use it in GitHub Desktop.
Get EC2 instance list filtered by NameTag
package main
import (
"fmt"
"github.com/awslabs/aws-sdk-go/aws"
"github.com/awslabs/aws-sdk-go/aws/credentials"
"github.com/awslabs/aws-sdk-go/service/ec2"
)
func main() {
profile := "default" // your profile name
name := "*test*" // search string (NameTag)
svc := ec2.New(&aws.Config{
Credentials: credentials.NewSharedCredentials("", profile),
Region: "ap-northeast-1",
})
params := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
&ec2.Filter{
Name: aws.String("tag:Name"),
Values: []*string{
aws.String(name),
},
},
},
}
res, _ := svc.DescribeInstances(params)
for _, i := range res.Reservations[0].Instances {
var nt string
for _, t := range i.Tags {
if *t.Key == "Name" {
nt = *t.Value
break
}
}
fmt.Println(nt, *i.InstanceID, *i.State.Name)
}
}
@jecolasurdo
Copy link

Well, this just saved me a bunch of time. Thanks!

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