Go语言开发k8s-05-ConfigMap操作

2024-03-12 03:20

本文主要是介绍Go语言开发k8s-05-ConfigMap操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 1. 结构体
    • 1.1 ConfigMapList
    • 1.2 ConfigMap
    • 1.3 TypeMeta
    • 1.4 ObjectMeta
    • 1.7 对照yml文件示例
    • 1.5 Immutable
    • 1.6 Data
    • 1.7 BinaryData
  • 2. Create configMap
    • 语法
    • 完整示例
  • 3. Get ConfigMapList
    • 语法
    • 完整示例
  • 4. Get ConfigMap
    • 语法
    • 完整示例
  • 5. Update ConfigMap
    • 语法
    • 完整示例
  • 6. Delete 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: nginxconfnamespace: 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: nginxconfnamespace: liubeiresourceVersion: "23364643"selfLink: /api/v1/namespaces/liubei/configmaps/nginxconfuid: cbe236fb-b86b-47f5-bf13-696fada4e400

1.5 Immutable

bool值的指针

  • true,不可更改
  • 否则可以随时更改

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{})

完整示例

  • 之前一个k8s上nginx服务的configmap如下
apiVersion: v1
kind: ConfigMap
metadata:name: nginxconfnamespace: 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 crowK8Simport ("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 mainimport ("fmt""go-k8s/crowK8S"
)func main()  {clientSet,err := crowK8S.ConnectK8s()if err !=nil {fmt.Println(err)}var dataInfo stringdataInfo = "    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)
}
  • k8s上查看结果如下
[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 crowK8Simport ("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 mainimport ("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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f8L2WtTFdrXgbbHCbOaIj9rruEH5wKxjxBg8=
-----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 crowK8Simport ("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 mainimport ("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 crowK8Simport ("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] = configMapDataconfigmapInfo,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,}
  • k8s上查看结果
[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 crowK8Simport ("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 mainimport ("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-05-ConfigMap操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/799985

相关文章

Linux使用fdisk进行磁盘的相关操作

《Linux使用fdisk进行磁盘的相关操作》fdisk命令是Linux中用于管理磁盘分区的强大文本实用程序,这篇文章主要为大家详细介绍了如何使用fdisk进行磁盘的相关操作,需要的可以了解下... 目录简介基本语法示例用法列出所有分区查看指定磁盘的区分管理指定的磁盘进入交互式模式创建一个新的分区删除一个存

Golang操作DuckDB实战案例分享

《Golang操作DuckDB实战案例分享》DuckDB是一个嵌入式SQL数据库引擎,它与众所周知的SQLite非常相似,但它是为olap风格的工作负载设计的,DuckDB支持各种数据类型和SQL特性... 目录DuckDB的主要优点环境准备初始化表和数据查询单行或多行错误处理和事务完整代码最后总结Duck

基于Python开发电脑定时关机工具

《基于Python开发电脑定时关机工具》这篇文章主要为大家详细介绍了如何基于Python开发一个电脑定时关机工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 简介2. 运行效果3. 相关源码1. 简介这个程序就像一个“忠实的管家”,帮你按时关掉电脑,而且全程不需要你多做

使用SQL语言查询多个Excel表格的操作方法

《使用SQL语言查询多个Excel表格的操作方法》本文介绍了如何使用SQL语言查询多个Excel表格,通过将所有Excel表格放入一个.xlsx文件中,并使用pandas和pandasql库进行读取和... 目录如何用SQL语言查询多个Excel表格如何使用sql查询excel内容1. 简介2. 实现思路3

Go语言实现将中文转化为拼音功能

《Go语言实现将中文转化为拼音功能》这篇文章主要为大家详细介绍了Go语言中如何实现将中文转化为拼音功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 有这么一个需求:新用户入职 创建一系列账号比较麻烦,打算通过接口传入姓名进行初始化。想把姓名转化成拼音。因为有些账号即需要中文也需要英

C# 读写ini文件操作实现

《C#读写ini文件操作实现》本文主要介绍了C#读写ini文件操作实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录一、INI文件结构二、读取INI文件中的数据在C#应用程序中,常将INI文件作为配置文件,用于存储应用程序的

Python使用qrcode库实现生成二维码的操作指南

《Python使用qrcode库实现生成二维码的操作指南》二维码是一种广泛使用的二维条码,因其高效的数据存储能力和易于扫描的特点,广泛应用于支付、身份验证、营销推广等领域,Pythonqrcode库是... 目录一、安装 python qrcode 库二、基本使用方法1. 生成简单二维码2. 生成带 Log

Java操作ElasticSearch的实例详解

《Java操作ElasticSearch的实例详解》Elasticsearch是一个分布式的搜索和分析引擎,广泛用于全文搜索、日志分析等场景,本文将介绍如何在Java应用中使用Elastics... 目录简介环境准备1. 安装 Elasticsearch2. 添加依赖连接 Elasticsearch1. 创

Go语言使用Buffer实现高性能处理字节和字符

《Go语言使用Buffer实现高性能处理字节和字符》在Go中,bytes.Buffer是一个非常高效的类型,用于处理字节数据的读写操作,本文将详细介绍一下如何使用Buffer实现高性能处理字节和... 目录1. bytes.Buffer 的基本用法1.1. 创建和初始化 Buffer1.2. 使用 Writ

k8s部署MongDB全过程

《k8s部署MongDB全过程》文章介绍了如何在Kubernetes集群中部署MongoDB,包括环境准备、创建Secret、创建服务和Deployment,并通过Robo3T工具测试连接... 目录一、环境准备1.1 环境说明1.2 创建 namespace1.3 创建mongdb账号/密码二、创建Sec