Last active
September 30, 2015 11:19
-
-
Save ksss/600789c8ac12064cc420 to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"flag" | |
"fmt" | |
"log" | |
"net/url" | |
"strings" | |
"github.com/aws/aws-sdk-go/aws" | |
"github.com/aws/aws-sdk-go/aws/credentials" | |
"github.com/aws/aws-sdk-go/service/ec2" | |
) | |
var profile = flag.String("profile", "default", "profile name in aws shared credentials file") | |
var instanceType = flag.Bool("instance-type", false, "show instance type(e.g. 'c4.large')") | |
func main() { | |
flag.Parse() | |
svc := ec2.New(&aws.Config{ | |
Credentials: credentials.NewSharedCredentials("", *profile), | |
Region: aws.String("ap-northeast-1"), | |
}) | |
filters := []*ec2.Filter{&ec2.Filter{ | |
Name: aws.String("instance-state-name"), | |
Values: []*string{ | |
aws.String("running"), | |
}, | |
}} | |
resp, err := svc.DescribeInstances(&ec2.DescribeInstancesInput{ | |
Filters: filters, | |
}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
var lines [][]string | |
for _, res := range resp.Reservations { | |
for _, inst := range res.Instances { | |
if inst.PublicIpAddress == nil { | |
continue | |
} | |
name := "None" | |
for _, keys := range inst.Tags { | |
if *keys.Key == "Name" { | |
name = url.QueryEscape(*keys.Value) | |
break | |
} | |
} | |
values := []string{ | |
*inst.PublicIpAddress, | |
*inst.PrivateIpAddress, | |
name, | |
*inst.KeyName, | |
} | |
if *instanceType { | |
values = append(values, *inst.InstanceType) | |
} | |
lines = append(lines, values) | |
} | |
} | |
for _, line := range lines { | |
fmt.Println(strings.Join(line, "\t")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment