Created
May 3, 2018 13:08
-
-
Save komeda-shinji/7526c1b4f591abee800a1c905e288901 to your computer and use it in GitHub Desktop.
goでのec2.DescribeInstancesテストコード
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" | |
"os" | |
"time" | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-sdk-go/aws/session" | |
"github.com/aws/aws-sdk-go/aws/ec2metadata" | |
"github.com/aws/aws-sdk-go/service/ec2" | |
) | |
const timezone = "Asia/Tokyo" | |
func main() { | |
location, err := time.LoadLocation(timezone) | |
if err != nil { | |
location = time.FixedZone(timezone, 9*60*60) | |
} | |
time.Local = location | |
fmt.Println(time.Now()) | |
sess := session.Must(session.NewSession()) | |
svc := ec2metadata.New(sess) | |
doc, _ := svc.GetInstanceIdentityDocument() | |
instanceId := doc.InstanceID | |
region := doc.Region | |
fmt.Println(region) | |
fmt.Println(instanceId) | |
ec2svc := ec2.New(sess, aws.NewConfig().WithRegion(region)) | |
start := time.Now() | |
for remain := 60*18; remain > 0; remain -= 1 { | |
now := time.Now() | |
fmt.Println(now) | |
fmt.Println(now.Sub(start)) | |
params := &ec2.DescribeInstancesInput{ | |
Filters: []*ec2.Filter{ | |
{ | |
Name: aws.String("instance-state-name"), | |
Values: []*string{aws.String("running"),}, | |
}, | |
}, | |
} | |
instances, err := ec2svc.DescribeInstances(params) | |
if err != nil { | |
fmt.Println("there was an error listing instances in", err.Error()) | |
os.Exit(1) | |
} | |
for idx, res := range instances.Reservations { | |
fmt.Println(" > Reservation Id", *res.ReservationId, " Num Instances: ", len(res.Instances)) | |
for _, inst := range instances.Reservations[idx].Instances { | |
fmt.Println(" - Instance ID: ", *inst.InstanceId) | |
} | |
} | |
time.Sleep(5*time.Minute) | |
} | |
end := time.Now() | |
fmt.Println(end.Sub(start)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment