使用client-go實現k8s操作

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。package main


import (
"flag"
"fmt"
"k8s.io/client-go/1.4/kubernetes"
"k8s.io/client-go/1.4/pkg/api"
"k8s.io/client-go/1.4/pkg/api/unversioned"
"k8s.io/client-go/1.4/pkg/api/v1"
"k8s.io/client-go/1.4/tools/clientcmd"
"log"
)


var (
kubeconfig = flag.String("kubeconfig", "./config", "absolute path to the kubeconfig file")
)


func main() {
flag.Parse()
// uses the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("116.213.205.180:8080", *kubeconfig)
if err != nil {
panic(err.Error())
}
// creates the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
// 建立pod
pod := new(v1.Pod)
pod.TypeMeta = unversioned.TypeMeta{Kind: "Pod", APIVersion: "v1"}
pod.ObjectMeta = v1.ObjectMeta{Name: "testapi", Namespace: "default", Labels: map[string]string{"name": "testapi"}}
pod.Spec = v1.PodSpec{
RestartPolicy: v1.RestartPolicyAlways,
Containers: []v1.Container{
v1.Container{
Name:  "testapi",
Image: "nginx",
Ports: []v1.ContainerPort{
v1.ContainerPort{
ContainerPort: 80,
Protocol:      v1.ProtocolTCP,
},
},
},
},
}
_, err = clientset.Core().Pods("default").Create(pod)
if err != nil {
panic(err.Error())
}
// 擷取現有的pod數量
pods, err := clientset.Core().Pods("").List(api.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))


// 建立namespace
nc := new(v1.Namespace)
nc.TypeMeta = unversioned.TypeMeta{Kind: "NameSpace", APIVersion: "v1"}
nc.ObjectMeta = v1.ObjectMeta{
Name: "k8s-test",
}
nc.Spec = v1.NamespaceSpec{}
_, err = clientset.Core().Namespaces().Create(nc)
if err != nil {
log.Println(err)
}


// 擷取namespace
namespaces, err := clientset.Core().Namespaces().List(api.ListOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("There are %d namespaces in the cluster\n", len(namespaces.Items))
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.