Skip to content

Instantly share code, notes, and snippets.

@ffledgling
Created July 12, 2017 11:37
Show Gist options
  • Save ffledgling/62814ccbb12fd6b9ab6fd89da7e80cd2 to your computer and use it in GitHub Desktop.
Save ffledgling/62814ccbb12fd6b9ab6fd89da7e80cd2 to your computer and use it in GitHub Desktop.
kubernetes client-go example: Create a Deployment based on json
package main
import (
"encoding/json"
"log"
"os"
// We use pretty instead of the common go-spew or pretty-printing because,
// go-spew is vendored in client-go and causes problems
"github.com/kr/pretty"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
extensionsv1beta1 "k8s.io/client-go/pkg/apis/extensions/v1beta1"
)
var (
kubeconfig = "/home/ffledgling/.kube/config"
dbjson = "/tmp/deployment.json"
)
func ListDeployments() {
// Read the Deplolyment's json.
file, err := os.Open(dbjson)
if err != nil {
panic(err.Error())
}
dec := json.NewDecoder(file)
// Parse it into the internal k8s structs
var dep extensionsv1beta1.Deployment
dec.Decode(&dep)
// Dump the struct in case you want to see what it looks like
pretty.Println(dep)
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
deploymentsClient := clientset.ExtensionsV1beta1().Deployments("namespace-ffledgling")
// List existing deployments in namespace
deployments, err := deploymentsClient.List(metav1.ListOptions{})
if err != nil {
log.Println(err)
} else {
for i, e := range deployments.Items {
log.Printf("Deployment #%d\n", i)
log.Printf("%s", e.ObjectMeta.SelfLink)
}
}
// Create a new deployment based on our template.
if result, err := deploymentsClient.Create(&dep); err != nil {
log.Println("ERROR:", err.Error())
} else {
pretty.Println(result)
}
}
func main() {
ListDeployments()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment