如何使用aws-cdk从AWS Secrets Manager导入EKS机密?

时间:2020-04-11 05:44:46

标签: aws-cdk aws-eks aws-secrets-manager kubernetes-secrets

我有:

  • 由aws-cdk脚本部署的EKS(已启用kubectl),由psql: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. 部署的应用
  • AWS Secrets Manager,其中包含我希望可用于EKS应用程序的一组秘密

我尝试通过以下方式部署Secret:

eks.Cluster.addResource()

我从CloudFormation遇到错误:

版本“ v1”中的秘密不能作为秘密处理:v1.Secret.ObjectMeta:v1.ObjectMeta.TypeMeta:类型:数据:解码base64:输入字节0处的非法base64数据

之所以会发生这种情况,是因为秘密令牌未展开,并且“ .dockerconfigjson”字段值在这种情况下看起来像 import * as sm from "@aws-cdk/aws-secretsmanager"; getSecret(secretKey: string): string { let secretTokens = sm.Secret.fromSecretArn(scope, "ImportedSecrets", awsSecretStorageArn); return secretTokens.secretValueFromJson(secretKey).toString(); } createKubernetesImagePullSecrets(k8s: eks.Cluster): void { let eksSecretStorageName = this.env.awsResourcesConfig.k8sImagePullSecretStorageName; k8s.addResource(eksSecretStorageName, { apiVersion: "v1", kind: "Secret", metadata: { name: eksSecretStorageName, }, data: { ".dockerconfigjson": this.getSecret('hub-secret'), }, type: "kubernetes.io/dockerconfigjson", }); }

是否可以在部署过程中正确部署EKS Secret资源并正确扩展秘密令牌?

1 个答案:

答案 0 :(得分:0)

我为此创建了一个临时的解决方法,方法是使用aws-cli下载秘密的纯文本版本。不是安全的方法,但是可以。 如果您有更安全的解决方案,请不要使用它。

import { execSync } from "child_process";

  extractSecretValues(awsSecretStorageArn: string) : Map<string, string> {
    let map = new Map<string, string>();
    let secretsContent = execSync(`aws secretsmanager get-secret-value --secret-id ${awsSecretStorageArn}`).toString();
    let secrets = JSON.parse(secretsContent);
    if (!secrets)
      throw new Error(`Secret values could not be extracted from ${awsSecretStorageArn}`);
    if (secrets.SecretString) {
      let secretValuesObj = JSON.parse(secrets.SecretString);
      for (let [secretKey, secretValue] of Object.entries<string>(secretValuesObj)) {
        map.set(secretKey, secretValue);
      }
    }
    return map;
  }

  let secretValueMap = extractSecretValues();

  createKubernetesImagePullSecrets(k8s: eks.Cluster): void {
    let eksSecretStorageName = this.env.awsResourcesConfig.k8sImagePullSecretStorageName;
    k8s.addResource(eksSecretStorageName, {
      apiVersion: "v1",
      kind: "Secret",
      metadata: {
        name: eksSecretStorageName,
      },
      data: {
        ".dockerconfigjson": secretValueMap.get('hub-secret'),
      },
      type: "kubernetes.io/dockerconfigjson",
    });
  }