Skip to content

Commit

Permalink
Add EC2 list instances example (#1492)
Browse files Browse the repository at this point in the history
Adds an example using the AWS SDK for Go to list EC2 instances instance state by different region.

Minor tweak of #1481 for style and example consistence.
  • Loading branch information
jasdel authored Aug 25, 2017
1 parent f437614 commit 45cac07
Show file tree
Hide file tree
Showing 2 changed files with 169 additions and 0 deletions.
32 changes: 32 additions & 0 deletions example/service/ec2/instancesbyRegion/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

# Example Fetch By region

This is an example using the AWS SDK for Go to list ec2 instances instance state By different region . By default it fetch all running and stopped instance


# Usage


```sh
# To fetch the stopped instance of all region use below:
./filter_ec2_by_region --state running --state stopped

# To fetch the stopped and running instance for region us-west-1 and eu-west-1 use below:
./filter_ec2_by_region --state running --state stopped --region us-west-1 --region=eu-west-1
```

## Sample Output

```
Fetching instace details for region: ap-south-1 with criteria: [running][stopped]**
printing instance details.....
instance id i-************
current State stopped
done for region ap-south-1 ****
Fetching instace details for region: eu-west-2 with criteria: [running][stopped]**
There is no instance for the for region eu-west-2 with the matching Criteria: [running][stopped]
done for region eu-west-2 ****
```
137 changes: 137 additions & 0 deletions example/service/ec2/instancesbyRegion/instancesByRegion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// +build example

package main

import (
"flag"
"fmt"
"os"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)

// Prints a list of instances for each region. If no regions are provided
// all regions will be searched. The state is required.
//
// Will use the AWS SDK for Go's default credential chain and region. You can
// specify the region with the AWS_REGION environment variable.
//
// Usage: instancesByRegion -state <value> [-state val...] [-region region...]
func main() {
states, regions := parseArguments()

if len(states) == 0 {
fmt.Fprintf(os.Stderr, "error: %v\n", usage())
os.Exit(1)
}
instanceCriteria := " "
for _, state := range states {
instanceCriteria += "[" + state + "]"
}

if len(regions) == 0 {
var err error
regions, err = fetchRegion()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}

for _, region := range regions {
sess := session.Must(session.NewSession(&aws.Config{
Region: aws.String(region),
}))

ec2Svc := ec2.New(sess)
params := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
&ec2.Filter{
Name: aws.String("instance-state-name"),
Values: aws.StringSlice(states),
},
},
}

result, err := ec2Svc.DescribeInstances(params)
if err != nil {
fmt.Println("Error", err)
} else {
fmt.Printf("\n\n\nFetching instace details for region: %s with criteria: %s**\n ", region, instanceCriteria)
if len(result.Reservations) == 0 {
fmt.Printf("There is no instance for the for region %s with the matching Criteria:%s \n", region, instanceCriteria)
}
for _, reservation := range result.Reservations {

fmt.Println("printing instance details.....")
for _, instance := range reservation.Instances {
fmt.Println("instance id " + *instance.InstanceId)
fmt.Println("current State " + *instance.State.Name)
}
}
fmt.Printf("done for region %s **** \n", region)
}
}
}

func fetchRegion() ([]string, error) {
awsSession := session.Must(session.NewSession(&aws.Config{}))

svc := ec2.New(awsSession)
awsRegions, err := svc.DescribeRegions(&ec2.DescribeRegionsInput{})
if err != nil {
return nil, err
}

regions := make([]string, 0, len(awsRegions.Regions))
for _, region := range awsRegions.Regions {
regions = append(regions, *region.RegionName)
}

return regions, nil
}

type flagArgs []string

func (a flagArgs) String() string {
return strings.Join(a.Args(), ",")
}

func (a *flagArgs) Set(value string) error {
*a = append(*a, value)
return nil
}
func (a flagArgs) Args() []string {
return []string(a)
}

func parseArguments() (states []string, regions []string) {
var stateArgs, regionArgs flagArgs

flag.Var(&stateArgs, "state", "state list")
flag.Var(&regionArgs, "region", "region list")
flag.Parse()

if flag.NFlag() != 0 {
states = append([]string{}, stateArgs.Args()...)
regions = append([]string{}, regionArgs.Args()...)
}

return states, regions
}

func usage() string {
return `
Missing mandatory flag 'state'. Please use like below Example:
To fetch the stopped instance of all region use below:
./filter_ec2_by_region -state running -state stopped
To fetch the stopped and running instance for region us-west-1 and eu-west-1 use below:
./filter_ec2_by_region -state running -state stopped -region us-west-1 -region=eu-west-1
`
}

0 comments on commit 45cac07

Please sign in to comment.