以编程方式颁发 Kubernetes 证书

Programmatically issuing a Kubernetes certificate

我能够手动创建证书:

  1. 我创建了一个 csr 文件
  2. 我创建并应用了 CertificateSigningRequest k8s 资源
  3. 我使用
  4. 批准了请求
kubectl certificate approve <name>
  1. 我从 CertificateSigningRequeststatus.certificate 字段中提取了证书。

现在我想以编程方式重复该过程。为此,我正在使用 @kubernetes/client-node npm 包。

我能够创建并应用 CertificateSigningRequest 资源:

const csrResource = await adminCertApi.createCertificateSigningRequest({
    metadata: {
        name: 'my.email@my.company.com',
    },
    spec: {
        request: csrBase64,
        signerName: 'kubernetes.io/kube-apiserver-client',
        usages: [
            'client auth'
        ],
    },
});

但后来我在尝试批准请求时遇到困难(尝试遵循 documentation)。我尝试了几种看起来像这样的变体:

csrResource.body.status.conditions = [
    {
        message: 'Approved by CWAdmin GraphQL Lambda function',
        reason: 'ApprovedByCWAdmin',
        type: 'Approved',
    }
];
const response = await adminCertApi.patchCertificateSigningRequest('my.email@my.company.com', csrResource.body, undefined, undefined, undefined, undefined, { headers: { 'Content-Type': 'application/strategic-merge-patch+json' } });

不幸的是,这不会更新 status.conditions 字段。即使是这样,是什么触发了证书的签署?文档指出 kube-controller-manager 从不自动批准类型为 kubernetes.io/kube-apiserver-client 的请求。

换句话说,kubectl certificate approve 的程序等效项是什么?

我发现 documentation 帮助我解决了问题:

  • status is required and must be True, False, or Unknown
  • Approved/Denied conditions can only be set via the /approval subresource

所以我将 status 字段添加到条件并将 API 调用更改为 patchCertificateSigningRequestApproval

工作代码现在看起来像这样:

const body = {
    status: {
        conditions: [
            {
                message: 'Approved by CWAdmin GraphQL Lambda function',
                reason: 'ApprovedByCWAdmin',
                type: 'Approved',
                status: 'True',
            }
        ]
    }
};

const response = await adminCertApi.patchCertificateSigningRequestApproval('my.email@my.company.com', body, undefined, undefined, undefined, undefined, { headers: { 'Content-Type': 'application/strategic-merge-patch+json' } });