1.shell命令格式

kubectl create secret docker-registry regsecret --docker-server=xxx.com --docker-username=xxx --docker-password=xxxxxx --docker-email=xxx -n namespace

2.java代码格式

注意:CreateClientUtil是我项目这边根据创建ApiClient弄的工具类.主要是创建ApiClient。getCoreV1Api()方法是创建ApiClient时初始化提供的.具体的Api对象需要根据项目本身去调整.

创建/更新Docker-Secret代码

package com.badou.project.kubernetes.example.real.secret;

import com.alibaba.fastjson.JSONObject;
import com.badou.project.kubernetes.util.CreateClientUtil;
import com.google.gson.internal.LinkedTreeMap;
import io.kubernetes.client.openapi.*;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1Secret;
import io.kubernetes.client.openapi.models.V1SecretList;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @ClassName MySecret
 * @Description 检查和创建Docker镜像仓库密钥
 * @date 2023/1/9 10:06
 * @Version 1.0
 */

public class CheckAndCreateDockerSecret {

    public static void main(String[] args) throws ApiException, UnsupportedEncodingException {
        //密钥名字
        String secretName = "registrykey";
        //密钥类型 不变 固定写
        String type = "kubernetes.io/dockerconfigjson";
        //命名空间
        String nameSpace = "";
        //docker镜像仓库地址
        String registryServerAddress = "";
        //镜像仓库账号
        String username = "";
        //镜像仓库密码
        String password = "";
        CoreV1Api coreV1Api = CreateClientUtil.build239().getCoreV1Api();
        //1.检查是否存在
//        V1Secret oldSecret = KubernetesApiClientUtil.getApi().readNamespacedSecret(secretName, nameSpace, null, null, null);
        V1SecretList v1SecretList = coreV1Api.listNamespacedSecret(nameSpace, null, null, null,
                null, "app=" + secretName, null, null, null, null, null);
        if(v1SecretList.getItems()!=null && v1SecretList.getItems().size()>=1){
            V1Secret v1Secret = v1SecretList.getItems().get(0);
            //更新账号密码地址
            String dockerSecret = createDockerSecret(registryServerAddress, username, password);
            Map data = new LinkedTreeMap();
            data.put(".dockerconfigjson",dockerSecret.getBytes("UTF-8"));
            v1Secret.data(data);
            //存在则更新
            coreV1Api.replaceNamespacedSecret(v1Secret.getMetadata().getName(),nameSpace,v1Secret,null,null,null);
            return;
        }

        //2.创建密钥
        //等于命令 kubectl create secret docker-registry regsecret --docker-server=xxx.com --docker-username=xxx --docker-password=xxxxxx --docker-email=xxx -n namespace
        V1Secret v1Secret =
                new V1Secret();
        V1ObjectMeta meta = new V1ObjectMeta().name(secretName).namespace(nameSpace);
        String dockerSecret = createDockerSecret(registryServerAddress, username, password);

        v1Secret.setMetadata(meta);
        Map data = new LinkedTreeMap();

        data.put(".dockerconfigjson",dockerSecret.getBytes("UTF-8"));
        v1Secret.data(data);
        v1Secret.type(type);
        v1Secret.apiVersion("v1");
        v1Secret.setKind("Secret");
        //设置标签 方便查询
        Map labels = new LinkedHashMap();
        labels.put("app",secretName);
        meta.setLabels(labels);

        V1Secret namespacedSecret = coreV1Api.createNamespacedSecret(
                nameSpace,
                v1Secret, null,
                null, null
        );
    }

    /**
     * 创建Docker类型的密钥
     * @param registryServerAddress 镜像仓库地址
     * @param username 镜像仓库账号
     * @param password 镜像仓库密码
     * @return 生成的JSON字符串
     * @throws UnsupportedEncodingException
     */
    public static String createDockerSecret(String registryServerAddress,String username,String password) throws UnsupportedEncodingException {
        /**
         * 最终需要生成的secretyaml
         * apiVersion: v1
         * data:
         *   .dockerconfigjson: eyJhdXRocyI6eyJodHRwczovL3JlZ2lzdHJ5LmJhZG91Ijp7InVzZXJuYW1lIjoiemhhb2xpbnpoaUBiYWRvdXNvZnQuY29tIiwicGFzc3dvcmQiOiJGeG9lXjIxNjMkIiwiYXV0aCI6ImVtaGhiMnhwYm5wb2FVQmlZV1J2ZFhOdlpuUXVZMjl0T2taNGIyVmVNakUyTXlRPSJ9fX0=
         * kind: Secret
         * metadata:
         *   creationTimestamp: null
         *   name: dch-app-docker-secret
         *   namespace: bddevns
         *
         *   .dockerconfigjson由以下字符串使用base64加密做成
         *   {"auths":{"https://registry.badou":{"username":"xxxx","password":"xxxx","auth":"xxxx"}}}
         *   其中auth:xxxx 这里面的值由username:password加密而成,格式为:账号:密码
         */
        Map jsonObject = new LinkedHashMap();
        Map auths = new LinkedHashMap();
        Map content = new LinkedHashMap();
        content.put("username",username);
        content.put("password",password);
        content.put("auth", Base64.getEncoder().encodeToString((username+":"+password).getBytes("UTF-8")));
        auths.put(registryServerAddress,content);
        jsonObject.put("auths",auths);
        return JSONObject.toJSONString(jsonObject);
    }

}

3.更多资料说明

官网地址:
https://github.com/kubernetes-client/java
参考的示例工程:
https://github.com/kubernetes-client/java/tree/master/examples
不同的java-client版本对应不同的k8s版本:
https://github.com/kubernetes-client/java/wiki/2.-Versioning-and-Compatibility
我自己项目的k8s版本: 1.22
我自己项目的pom.xml依赖:
依赖仅供参考:建议以项目的实际情况和官方例子来配置依赖.
<okhttp3.version>4.9.1</okhttp3.version>

<kubernetes.api.version>13.0.0</kubernetes.api.version>

	<!-- kubernetes api start -->
	<dependency>
		<groupId>io.kubernetes</groupId>
		<artifactId>client-java</artifactId>
		<version>${kubernetes.api.version}</version>
		<exclusions>
			<exclusion>
				<groupId>org.slf4j</groupId>
				<artifactId>slf4j-api</artifactId>
			</exclusion>
			<exclusion>
				<groupId>ch.qos.logback</groupId>
				<artifactId>logback-classic</artifactId>
			</exclusion>
		</exclusions>
	</dependency>
	<dependency>
		<groupId>io.kubernetes</groupId>
		<artifactId>client-java-api</artifactId>
		<version>${kubernetes.api.version}</version>
		<exclusions>
			<exclusion>
				<groupId>ch.qos.logback</groupId>
				<artifactId>logback-classic</artifactId>
			</exclusion>
			<exclusion>
				<groupId>com.squareup.okhttp3</groupId>
				<artifactId>okhttp</artifactId>
			</exclusion>
			<exclusion>
				<groupId>com.squareup.okhttp3</groupId>
				<artifactId>logging-interceptor</artifactId>
			</exclusion>
		</exclusions>
	</dependency>
	<dependency>
		<groupId>io.kubernetes</groupId>
		<artifactId>client-java-extended</artifactId>
		<version>${kubernetes.api.version}</version>
	</dependency>
	<dependency>
		<groupId>commons-cli</groupId>
		<artifactId>commons-cli</artifactId>
		<version>1.5.0</version>
	</dependency>
	<dependency>
		<groupId>io.kubernetes</groupId>
		<artifactId>client-java-cert-manager-models</artifactId>
		<version>10.0.1</version>
	</dependency>
	<dependency>
		<groupId>io.kubernetes</groupId>
		<artifactId>client-java-prometheus-operator-models</artifactId>
		<version>10.0.1</version>
	</dependency>
	<dependency>
		<groupId>com.squareup.okhttp3</groupId>
		<artifactId>okhttp</artifactId>
		<exclusions>
			<exclusion>
				<groupId>org.jetbrains.kotlin</groupId>
				<artifactId>kotlin-stdlib</artifactId>
			</exclusion>
		</exclusions>
		<version>${okhttp3.version}</version>
	</dependency>
	<dependency>
		<groupId>com.squareup.okhttp3</groupId>
		<artifactId>logging-interceptor</artifactId>
		<exclusions>
			<exclusion>
				<groupId>org.jetbrains.kotlin</groupId>
				<artifactId>kotlin-stdlib-jdk8</artifactId>
			</exclusion>
		</exclusions>
		<version>${okhttp3.version}</version>
	</dependency>
	<dependency>
		<groupId>org.jetbrains.kotlin</groupId>
		<artifactId>kotlin-stdlib-jdk8</artifactId>
		<version>1.4.10</version>
	</dependency>
	<dependency>
		<groupId>org.jetbrains.kotlin</groupId>
		<artifactId>kotlin-stdlib</artifactId>
		<version>1.4.10</version>
	</dependency>
	<!-- kubenetes api end -->
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐