A Short Golang AWS Example

in #cloudcomputing7 years ago (edited)

I must say I am falling in love with Golang this programming language allows me to easily write code or script that I can easily compile and run on any platform and yes I am mean any platform.

Here is a short example of a simple piece of code that allowed me to get my real internet IP address.


package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "runtime"
)

func main() {
    res, _ := http.Get("https://api.ipify.org")
    ip, _ := ioutil.ReadAll(res.Body)
    fmt.Println("My Internet IP:", string(ip))
}

Now that was not the real reason that you are reading this post you wanted to see a simple example of using AWS with Go.

The sample below is a simple CLI built that allows you to create a keypair for AWS.

I will not go into much detail in this post I will just show you the code ...


package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "os"

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

var (
    pairname string
    region   string
    svc      *ec2.EC2
)

func exitErrorf(msg string, args ...interface{}) {
    fmt.Fprintf(os.Stderr, msg+"\n", args...)
    os.Exit(1)
}

func savePem(f string, k string) error {

    return ioutil.WriteFile(f, []byte(k), 0666)

}

func main() {

    pairname := flag.String("k", "", "Keypair Name To Create (Required)")
    region := flag.String("r", "us-east-1", "Region name")
    flag.Parse()

    if *pairname == "" {
        flag.PrintDefaults()
        os.Exit(1)
    }

    svc = ec2.New(session.New(&aws.Config{Region: aws.String(*region)}))

    keyresult, err := svc.CreateKeyPair(&ec2.CreateKeyPairInput{
        KeyName: aws.String(*pairname),
    })

    if err != nil {
        if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "InvalidKeyPair.Duplicate" {
            exitErrorf("Keypair %q already exists.", *pairname)
        }
        exitErrorf("Unable to create key pair: %s, %v.", *pairname, err)
    }

    savePem(*pairname+".pem", *keyresult.KeyMaterial)

    fmt.Printf("Created key pair %q %s\n%s\n",
        *keyresult.KeyName, *keyresult.KeyFingerprint,
        *keyresult.KeyMaterial)
}