Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Go开发k8s ConfigMap操作

Go语言开发k8s之ConfigMap操作解析

作者:开发运维玄德公

这篇文章主要为大家介绍了Go语言开发k8s之ConfigMap操作示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

1. 结构体

1.1 ConfigMapList

所在包:"k8s.io/api/core/v1"

type ConfigMapList struct {
    v1.TypeMeta `json:",inline"`
    v1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
    Items           []ConfigMap `json:"items" protobuf:"bytes,2,rep,name=items"`
}

Items中每个ConfigMap结构体如下:

1.2 ConfigMap

所在包:"k8s.io/api/core/v1"

type ConfigMap struct {
    v1.TypeMeta   `json:",inline"`
    v1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
    Immutable         *bool             `json:"immutable,omitempty" protobuf:"varint,4,opt,name=immutable"`
    Data              map[string]string `json:"data,omitempty" protobuf:"bytes,2,rep,name=data"`
    BinaryData        map[string][]byte `json:"binaryData,omitempty" protobuf:"bytes,3,rep,name=binaryData"`
}

其成员说明如下:

1.3 TypeMeta

所在包:"k8s.io/apimachinery/pkg/apis/meta/v1"

type TypeMeta struct {
    Kind       string `json:"kind,omitempty" protobuf:"bytes,1,opt,name=kind"`
    APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,2,opt,name=apiVersion"`
}

对应在k8s上创建service的yml文件的如下部分:

apiVersion: v1
kind: ConfigMap

1.4 ObjectMeta

所在包:"k8s.io/apimachinery/pkg/apis/meta/v1"

type ObjectMeta struct {
    Name                       string               `json:"name,omitempty" protobuf:"bytes,1,opt,name=name"`
    GenerateName               string               `json:"generateName,omitempty" protobuf:"bytes,2,opt,name=generateName"`
    Namespace                  string               `json:"namespace,omitempty" protobuf:"bytes,3,opt,name=namespace"`
    SelfLink                   string               `json:"selfLink,omitempty" protobuf:"bytes,4,opt,name=selfLink"`
    UID                        types.UID            `json:"uid,omitempty" protobuf:"bytes,5,opt,name=uid,casttype=k8s.io/kubernetes/pkg/types.UID"`
    ResourceVersion            string               `json:"resourceVersion,omitempty" protobuf:"bytes,6,opt,name=resourceVersion"`
    Generation                 int64                `json:"generation,omitempty" protobuf:"varint,7,opt,name=generation"`
    CreationTimestamp          Time                 `json:"creationTimestamp,omitempty" protobuf:"bytes,8,opt,name=creationTimestamp"`
    DeletionTimestamp          *Time                `json:"deletionTimestamp,omitempty" protobuf:"bytes,9,opt,name=deletionTimestamp"`
    DeletionGracePeriodSeconds *int64               `json:"deletionGracePeriodSeconds,omitempty" protobuf:"varint,10,opt,name=deletionGracePeriodSeconds"`
    Labels                     map[string]string    `json:"labels,omitempty" protobuf:"bytes,11,rep,name=labels"`
    Annotations                map[string]string    `json:"annotations,omitempty" protobuf:"bytes,12,rep,name=annotations"`
    OwnerReferences            []OwnerReference     `json:"ownerReferences,omitempty" patchStrategy:"merge" patchMergeKey:"uid" protobuf:"bytes,13,rep,name=ownerReferences"`
    Finalizers                 []string             `json:"finalizers,omitempty" patchStrategy:"merge" protobuf:"bytes,14,rep,name=finalizers"`
    ManagedFields              []ManagedFieldsEntry `json:"managedFields,omitempty" protobuf:"bytes,17,rep,name=managedFields"`
}

对应在k8s上创建service的yml文件的如下部分:

metadata:
  name: nginxconf
  namespace: test

1.7 对照yml文件示例

附原生k8s集群上一个configMap信息,大家可以对照理解一下以上结构体

apiVersion: v1
data:
  nginx.conf: |2-
        worker_processes  1;
        events {
            worker_connections  1024;
        }
        http {
            include       mime.types;
            default_type  application/octet-stream;
            client_max_body_size 50m;
            sendfile        on;
            keepalive_timeout  65;
            server {
                listen       80;
                server_name  localhost;
                root   /usr/share/nginx/html;
                location / {
                   index  index.html index.htm;
                }
            }
        }
kind: ConfigMap
metadata:
  creationTimestamp: "2022-10-14T06:53:14Z"
  name: nginxconf
  namespace: liubei
  resourceVersion: "23364643"
  selfLink: /api/v1/namespaces/liubei/configmaps/nginxconf
  uid: cbe236fb-b86b-47f5-bf13-696fada4e400

1.5 Immutable

bool值的指针

1.6 Data

map[string]string类型,对应yaml文件中的data字段,每一个成员对应一个键值对,即一个要挂载的配置文件

1.7 BinaryData

map[string][]byte类型,和Data类似,只不过传入的字串变成了[]byte

2. Create configMap

语法

func (ConfigMapInterface) Create(ctx context.Context, configMap *v1.ConfigMap, opts v1.CreateOptions) (*v1.ConfigMap, error)
configMapInfo,err = clientSet.CoreV1().ConfigMaps(namespaceName).Create(context.TODO(),configMap,metaV1.CreateOptions{})

完整示例

apiVersion: v1
kind: ConfigMap
metadata:
  name: nginxconf
  namespace: test
data:
  nginx.conf: |
    worker_processes  1;
    events {
        worker_connections  1024;
    }
    http {
        include       mime.types;
        default_type  application/octet-stream;
        client_max_body_size 50m;
        sendfile        on;
        keepalive_timeout  65;
        server {
            listen       80;
            server_name  localhost;
            root   /usr/share/nginx/html;
            location / {
               index  index.html index.htm;
            }
        }
    }
package crowK8S
import (
    "context"
    coreV1 "k8s.io/api/core/v1"
    metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)
func CreateConfigMap(clientSet *kubernetes.Clientset,namespaceName string,configMapName string,dataInfo string)(configMapInfo *coreV1.ConfigMap,err  error)  {
    configMap := &coreV1.ConfigMap{
        ObjectMeta: metaV1.ObjectMeta{
            Name: configMapName,
        },
        Data: map[string]string{
            "nginx.conf" : dataInfo,
        },
    }
    configMapInfo,err = clientSet.CoreV1().ConfigMaps(namespaceName).Create(context.TODO(),configMap,metaV1.CreateOptions{})
    if err != nil {
        return configMapInfo,err
    }
    return configMapInfo,nil
}
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    var dataInfo string
    dataInfo = "    worker_processes  1;\n    events {\n        worker_connections  1024;\n    }\n    http {\n        include       mime.types;\n        default_type  application/octet-stream;\n        client_max_body_size 50m;\n        sendfile        on;\n        keepalive_timeout  65;\n        server {\n            listen       80;\n            server_name  localhost;\n            root   /usr/share/nginx/html;\n            location / {\n               index  index.html index.htm;\n            }\n        }\n    }"
    configMapInfo,err := crowK8S.CreateConfigMap(clientSet ,"liubei","nginxconf",dataInfo)
    fmt.Println(configMapInfo)
}
[root@crust-m01 ~]# kubectl describe -n liubei configmaps nginxconf
Name:         nginxconf
Namespace:    liubei
Labels:       <none>
Annotations:  <none>
Data
====
nginx.conf:
----
    worker_processes  1;
    events {
        worker_connections  1024;
    }
    http {
        include       mime.types;
        default_type  application/octet-stream;
        client_max_body_size 50m;
        sendfile        on;
        keepalive_timeout  65;
        server {
            listen       80;
            server_name  localhost;
            root   /usr/share/nginx/html;
            location / {
               index  index.html index.htm;
            }
        }
    }
Events:  <none>

3. Get ConfigMapList

完整示例

package crowK8S
import (
    "context"
    coreV1 "k8s.io/api/core/v1"
    metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)
func GetConfigMapList(clientSet *kubernetes.Clientset,namespaceName string)(configMapList *coreV1.ConfigMapList,err error)  {
    configMapList,err = clientSet.CoreV1().ConfigMaps(namespaceName).List(context.TODO(), metaV1.ListOptions{})
    if err != nil{
        return nil, err
    }
    return configMapList, err
}
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    configMapList,err := crowK8S.GetConfigMapList(clientSet ,"liubei")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(configMapList)
}

结果打印

&ConfigMapList{ListMeta:{/api/v1/namespaces/liubei/configmaps 22893420  <nil>},Items:[]ConfigMap{ConfigMap{ObjectMeta:{kube-root-ca.crt  liubei /api/v1/namespaces/liubei/configmaps/kube-root-ca.crt ecb54dbb-3082-4caa-9055-8061e5d9d7b6 19106476 0 2022-09-28 13:23:29 +0800 CST <nil> <nil> map[] map[] [] [] [{kube-controller-manager Update v1 2022-09-28 13:23:29 +0800 CST F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ruEH5wKxjxBg8=
-----END CERTIFICATE-----
,},BinaryData:map[string][]byte{},Immutable:nil,},ConfigMap{ObjectMeta:{nginxconf  liubei /api/v1/namespaces/liubei/configmaps/nginxconf 395535db-1df7-408a-9976-18e6ded1207e 22854355 0 2022-10-12 17:21:03 +0800 CST <nil> <nil> map[] map[] [] [] [{___go_build_main_go.exe Update v1 2022-10-12 17:21:03 +0800 CST FieldsV1 {"f:data":{".":{},"f:nginx.conf":{}}} }]},Data:map[string]string{nginx.conf:     worker_processes  1;
    events {
        worker_connections  1024;
    }
    http {
        include       mime.types;
        default_type  application/octet-stream;
        client_max_body_size 50m;
        sendfile        on;
        keepalive_timeout  65;
        server {
            listen       80;
            server_name  localhost;
            root   /usr/share/nginx/html;
            location / {
               index  index.html index.htm;
            }
        }
    },},BinaryData:map[string][]byte{},Immutable:nil,},},}

4. Get ConfigMap

func (ConfigMapInterface) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1.ConfigMap, error)
configmapInfo,err = clientSet.CoreV1().ConfigMaps(namespaceName).Get(context.TODO(),configMapName,metaV1.GetOptions{})

完整示例

package crowK8S
import (
    "context"
    coreV1 "k8s.io/api/core/v1"
    metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)
func GetConfigMap(clientSet *kubernetes.Clientset,namespaceName string,configMapName string)(configmapInfo *coreV1.ConfigMap,err error)  {
    configmapInfo,err = clientSet.CoreV1().ConfigMaps(namespaceName).Get(context.TODO(), configMapName,metaV1.GetOptions{})
    if err != nil{
        return nil, err
    }
    return configmapInfo, err
}
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    configmapInfo,err := crowK8S.GetConfigMap(clientSet ,"liubei","nginxconf")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(configmapInfo)
}

结果

&ConfigMap{ObjectMeta:{nginxconf  liubei /api/v1/namespaces/liubei/configmaps/nginxconf 395535db-1df7-408a-9976-18e6ded1207e 22854355 0 2022-10-12 17:21:03 +0800 CST <nil> <nil> map[] map[] [] [] [{___go_build_main_go.exe Update v1 2022-10-12 17:21:03 +0800 CST FieldsV1 {"f:data":{".":{},"f:nginx.conf":{}}} }]},Data:map[string]string{nginx.conf:     worker_processes  1;
    events {
        worker_connections  1024;
    }
    http {
        include       mime.types;
        default_type  application/octet-stream;
        client_max_body_size 50m;
        sendfile        on;
        keepalive_timeout  65;
        server {
            listen       80;
            server_name  localhost;
            root   /usr/share/nginx/html;
            location / {
               index  index.html index.htm;
            }
        }
    },},BinaryData:map[string][]byte{},Immutable:nil,}

5. Update ConfigMap

func (ConfigMapInterface) Update(ctx context.Context, configMap *v1.ConfigMap, opts v1.UpdateOptions) (*v1.ConfigMap, error)
configmapInfo,err = clientSet.CoreV1().ConfigMaps(namespaceName).Update(context.TODO(),configmapInfo,metaV1.UpdateOptions{})

完整示例

package crowK8S
import (
    "context"
    coreV1 "k8s.io/api/core/v1"
    metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)
func ApplyConfigMap(clientSet *kubernetes.Clientset,namespaceName string,configMapName string,fileName string,configMapData string)(configmapInfo *coreV1.ConfigMap,err error)  {
    configmapInfo,err = clientSet.CoreV1().ConfigMaps(namespaceName).Get(context.TODO(), configMapName,metaV1.GetOptions{})
    if err != nil{
        return nil, err
    }
    configmapInfo.Data[fileName] = configMapData
    configmapInfo,err = clientSet.CoreV1().ConfigMaps(namespaceName).Update(context.TODO(),configmapInfo,metaV1.UpdateOptions{})
    if err !=nil {
        return configmapInfo,err
    }
    return configmapInfo,nil
}
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    configMapInfo,err := crowK8S.ApplyConfigMap(clientSet ,"liubei","nginxconf","nginx.conf","hello world")
    fmt.Println(configMapInfo)
}

&ConfigMap{ObjectMeta:{nginxconf  liubei /api/v1/namespaces/liubei/configmaps/nginxconf 395535db-1df7-408a-9976-18e6ded1207e 22901163 0 2022-10-12 17:21:03 +0800 CST <nil> <nil> map[] map[] [] [] [{___go_build_main_go.exe Update v1 2022-10-12 17:21:03 +0800 CST FieldsV1 {"f:data":{".":{},"f:nginx.conf":{}}} }]},Data:map[string]string{nginx.conf: hello world,},BinaryData:map[string][]byte{},Immutable:nil,}

[root@crust-m01 ~]# kubectl describe -n liubei configmaps nginxconf
Name:         nginxconf
Namespace:    liubei
Labels:       <none>
Annotations:  <none>
Data
====
nginx.conf:
----
hello world
Events:  <none>

6. Delete ConfigMap

func (ConfigMapInterface) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error
err = clientSet.CoreV1().ConfigMaps(namespaceName).Delete(context.TODO(),configMapName,metaV1.DeleteOptions{})

完整示例

package crowK8S
import (
    "context"
    coreV1 "k8s.io/api/core/v1"
    metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
)
func DeleteConfigMap(clientSet *kubernetes.Clientset,namespaceName string,configMapName string)(err error)  {
    err = clientSet.CoreV1().ConfigMaps(namespaceName).Delete(context.TODO(),configMapName,metaV1.DeleteOptions{})
    if err != nil {
        return err
    }
    return nil
}
package main
import (
    "fmt"
    "go-k8s/crowK8S"
)
func main()  {
    clientSet,err := crowK8S.ConnectK8s()
    if err !=nil {
        fmt.Println(err)
    }
    err = crowK8S.DeleteConfigMap(clientSet,"liubei","nginxconf")
    if err != nil {
        fmt.Println(err)
    }else {
        fmt.Println("删除成功")
    }
}

结果打印

删除成功

以上就是Go语言开发k8s之ConfigMap操作解析的详细内容,更多关于Go开发k8s ConfigMap操作的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文