Last active
May 29, 2023 20:09
-
-
Save simeji/945165da059d2f4ef4bf to your computer and use it in GitHub Desktop.
Get EC2 instance list filtered by NameTag
This file contains 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
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well, this just saved me a bunch of time. Thanks!