I ran into this problem when trying to access the API from inside the module using Go code. The following is what I implemented to get this to work if someone comes across this issue, wanting to use Go too.
The example uses the pod resource, for which you must use the client-go library if you are working with native kubernetes objects. The code is more useful for those working with CustomResourceDefintions.
serviceHost := os.GetEnv("KUBERNETES_SERVICE_HOST") servicePort := os.GetEnv("KUBERNETES_SERVICE_PORT") apiVersion := "v1" // For example namespace := default // For example resource := "pod" // For example httpMethod := http.MethodGet // For Example url := fmt.Sprintf("https://%s:%s/apis/%s/namespaces/%s/%s", serviceHost, servicePort, apiVersion, namespace, resource) u, err := url.Parse(url) if err != nil { panic(err) } req, err := http.NewRequest(httpMethod, u.String(), bytes.NewBuffer(payload)) if err != nil { return err } caToken, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token") if err != nil { panic(err) // cannot find token file } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", string(caToken))) caCertPool := x509.NewCertPool() caCert, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") if err != nil { return panic(err) // Can't find cert file } caCertPool.AppendCertsFromPEM(caCert) client := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{ RootCAs: caCertPool, }, }, } resp, err := client.Do(req) if err != nil { log.Printf("sending helm deploy payload failed: %s", err.Error()) return err } defer resp.Body.Close() // Check resp.StatusCode // Check resp.Status
KyleHodgetts Apr 12 '18 at 16:28 2018-04-12 16:28
source share