LoginSignup
1
0

More than 5 years have passed since last update.

GoでGoogleComputeEngineインスタンスの外部IPを取得

Posted at

タイトルの通りのことをやりたい機会があったのですが
情報を探してまとめるのに手間取ったのでメモしておきます。

やり方

ComputeEngineの外部IP取得

import (
    "context"
    "fmt"

    // この2つの外部パッケージが必要
    "golang.org/x/oauth2/google"
    "google.golang.org/api/compute/v1"
)

func getExternalIP() (externalIP string, err error) {
    ctx := context.Background()
    // デフォルトの認証情報(gcloud auth aplication-default loginとか、GAEとかの認証)でClient生成
    client, err := google.DefaultClient(ctx, compute.ComputeScope)
    if err != nil {
        return "", err
    }
    computeService, err := compute.New(client)
    if err != nil {
        return "", fmt.Errorf("error opening connection, err: %s", err)
    }
    service := compute.NewInstancesService(computeService)

    // instanceを取得。projectIDとinstanceのzoneとinstance名が必要。
    ins, err := service.Get(ProjectID, Zone, InstanceName).Do()
    if err != nil {
        return "", fmt.Errorf("error getting instance, err: %s", err)
    }

    if len(ins.NetworkInterfaces) == 0 {
        return "", fmt.Errorf("error, network interface is not attached :%s", ins.Name)
    }

    nwIf := ins.NetworkInterfaces[0]
    if len(nwIf.AccessConfigs) == 0 {
        return "", fmt.Errorf("error, nothing access configs on network interface, instance:%s, nwif: %s", ins.Name, nwIf.Name)
    }

    exIP := nwIf.AccessConfigs[0].NatIP
    return exIP, nil
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0