0
0

More than 3 years have passed since last update.

golangでk8sクラスタのDeployment一覧を取得

Last updated at Posted at 2019-12-06

golangでk8sクラスタのDeployment一覧APiを叩いて取得したjsonのレスポンスを標準出力に表示します。(SAのトークンを利用します)

依存関係です。

package main
import (
        "fmt"
        "net/http"
        "io/ioutil"
        "log"
        "crypto/x509"
        "crypto/tls"
        "encoding/json"
)

リクエスト送付とレスポンス受領するrequest関数です。

func request (endpoint,method,crtpath,token string) int {

        //証明書の設定
        caCert, _ := ioutil.ReadFile(crtpath)
        caCertPool := x509.NewCertPool()
        caCertPool.AppendCertsFromPEM(caCert)

        //リクエストの構成
        req, _ := http.NewRequest(method, endpoint, nil)

        req.Header.Set("Accept","application/json")
        req.Header.Set("Content-Type","application/json")
        req.Header.Set("Authorization","Bearer "+token)

        tr := &http.Transport{
                TLSClientConfig: &tls.Config{RootCAs: caCertPool,},
        }

        client := &http.Client{
                Transport: tr,
        }

        //レスポンスの処理
        resp, err := client.Do(req)
        defer resp.Body.Close()

        body, _ := ioutil.ReadAll(resp.Body)
        json.Unmarshal([]byte(body),&val)
        r,_ := json.MarshalIndent(val,"","  ")
        //fmt.Println(resp.StatusCode) <-ステータスコード
        return string(r)

最後にrequest関数を呼び出すメイン関数です。
(以下コード中のAPIサーバーのエンドポイントの変数apiserver、証明書パスの変数crtpath、トークンの変数tokenについてはこちらを参照してください。リンク先で、それぞれAPISERVERCRTFILETOKEN変数で格納しています)

func main () {
        apiserver := "https://192.168.99.100:8443" //k8sエンドポイント
        path := "/apis/apps/v1/namespaces/default/deployments"
        endpoint := apiserver+path
        method := "GET"
        crtpath := "/Users/sota-n/.minikube/ca.crt" //<-証明書
        token := xxx...  //SAトークンの値
        result := request(endpoint,method,crtpath,token)
        fmt.Println(result)

あとはビルドしてバイナリを実行するかgo run <以上のコード>.goを実行します。

0
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
0
0