AWS SDK for Goをインストールしてみる

docs.aws.amazon.com

インストール

$ go get -u github.com/aws/aws-sdk-go/...

github.com

Configuring Credentials

$ echo export AWS_ACCESS_KEY_ID=XXXXXXXXXXX >> ~/.profile
$ echo export AWS_SECRET_ACCESS_KEY=XXXXXXX >> ~/.profile
$ source ~/.profile

EC2インスタンスのIDを表示してみる

  • vi ec2.go
package main

import (
    "fmt"

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

func main() {
    // Create an EC2 service object in the "us-west-2" region
    // Note that you can also configure your region globally by
    // exporting the AWS_REGION environment variable
    svc := ec2.New(session.New(), &aws.Config{Region: aws.String("ap-northeast-1")})

    // Call the DescribeInstances Operation
    resp, err := svc.DescribeInstances(nil)
    if err != nil {
        panic(err)
    }

    // resp has all of the response data, pull out instance IDs:
    fmt.Println("> Number of reservation sets: ", len(resp.Reservations))
    for idx, res := range resp.Reservations {
        fmt.Println("  > Number of instances: ", len(res.Instances))
        for _, inst := range resp.Reservations[idx].Instances {
            fmt.Println("    - Instance ID: ", *inst.InstanceId)
        }
    }
}
  • 実行してみる
$ go run ec2.go 
> Number of reservation sets:  XXX
  > Number of instances:  XXX
    - Instance ID:  i-XXXXXXXX
  > Number of instances:  XXX
    - Instance ID:  i-XXXXXXXX