タイトルの通りのことをやりたい機会があったのですが
情報を探してまとめるのに手間取ったのでメモしておきます。
やり方
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
}