从KMS获取GCP部署的秘密

时间:2018-01-30 15:33:44

标签: google-cloud-platform google-deployment-manager google-cloud-kms

我想使用Deployment Manager在GCP中部署Cloud VPN隧道

我为此设置了使用Python的部署脚本,并且我不希望在我的配置中以纯文本形式显示VPN隧道的共享密钥。

所以我尝试包含通过KMS加密的秘密,然后在python脚本中执行对KMS的调用以获取纯文本秘密。

解密秘密的python代码如下所示:

import base64
import googleapiclient.discovery 

def decryptSecret(enc_secret,context):
    """ decrypts the given Secret via KMS"""

    # KMS Configuration
    KEY_RING     = <Key Ring>
    KEY_ID       = <Key>
    KEY_LOCATION = REGION
    KEY_PROJECT  = context.env['project'],

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    key_name = 'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}'.format(
       KEY_PROJECT, KEY_LOCATION, KEY_RING, KEY_ID)

    crypto_keys =  kms_client.projects().locations().keyRings().cryptoKeys()

    request = crypto_keys.decrypt(
            name=key_name,
            body={'ciphertext': enc_secret})
    response = request.execute()
    plaintext = base64.b64decode(response['plaintext'].encode('ascii'))

    return plaintext

但是,如果我部署此代码,我只是从部署管理器收到以下错误消息:

Waiting for update [operation-<...>]...failed.
ERROR: (gcloud.deployment-manager.deployments.update) Error in Operation [operation-1517326129267-5640004f18139-450d8883-8d57c3ff]: errors:
- code: MANIFEST_EXPANSION_USER_ERROR
  message: |
    Manifest expansion encountered the following errors: Error compiling Python code: No module named googleapiclient.discovery Resource: cloudvpn-testenv.py Resource: config

我还尝试在我的配置yaml中包含完整的google-api-python-client库,但我仍然遇到此错误。

有人在想吗?

1 个答案:

答案 0 :(得分:0)

直接回答您的问题:

# requirements.txt

google-api-python-client
# main.py

import base64
import os
import googleapiclient.discovery

crypto_key_id = os.environ['KMS_CRYPTO_KEY_ID']

def decrypt(client, s):
    response = client \
        .projects() \
        .locations() \
        .keyRings() \
        .cryptoKeys() \
        .decrypt(name=crypto_key_id, body={"ciphertext":s}) \
        .execute()

    return base64.b64decode(response['plaintext']).decode('utf-8').strip()


kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

auth = decrypt(kms_client, '...ciphertext...'])

您可以找到更多示例和示例on GitHub

要间接回答您的问题,您可能对Secret Manager感兴趣。