如何解密Terraform数据资源返回的ssm参数安全字符串值

如何解密Terraform数据资源返回的ssm参数安全字符串值

本文介绍了如何解密Terraform数据资源返回的ssm参数安全字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下面的terraofrm代码,可以从商店中获取参数

I have a below terraofrm code to fetch parameter from store

data "aws_ssm_parameter" "foo" {
 name = "password"
with_decryption = false
}

module "lambda_env_vars" {
New_password = data.aws_ssm_parameter.foo.value
}

plan output:-
New_password = Q#iuws##)9ssdhs(some encryptrd value)

如何在lambda函数中将其解密为纯文本?

How can I decrypt this to plain text in the lambda function?

我一直在尝试的示例代码.

sample code I have been trying.

import boto3
import os

from base64 import b64decode

def lambda_handler(event, context):
    encrypted = os.environ['New_password']
    decrypted = boto3.client('kms').decrypt(CiphertextBlob=b64decode(encrypted))['Plaintext']

    print("Decrypted value:", decrypted)

推荐答案

经过研究,我发现AWS Encryption SDK以加密方式将加密上下文绑定到加密数据参考,因此我们必须使用相同的参数进行解密. EncryptionContext 为我解决了这个问题.

After some research, I found that The AWS Encryption SDK cryptographically binds the encryption context to the encrypted data reference so we have to use the same to decrypt. EncryptionContext solved the issue for me.

注意:这是Node js代码

const aws = require('aws-sdk')
const kms = new aws.KMS()
exports.handler = async (event, context, callback) => {
  var password_json = JSON.parse(process.env.New_password)
  let params = {
    CiphertextBlob: Buffer.from(password_json['value'], 'base64'),
     EncryptionContext: {
        'PARAMETER_ARN': password_json['arn']
    }
  }

  let secret = null
    const decrypted = await kms.decrypt(params).promise()

          secret = decrypted.Plaintext.toString('utf-8')

  return secret;
}

属性更改

module "lambda_env_vars" {
New_password = jsonencode(data.aws_ssm_parameter.foo)
}

lambda控制台上的ENV变量看起来像

New_password {"arn":"arn:aws:ssm:xxxxx:41xxxxx:parameter/password","id":"password","name":"password","type":"SecureString","value":"xxxxxxxx","version":2,"with_decryption":false}

通过这种方式(jsonencode),我们还可以避免在代码内部对参数ARN进行硬编码.

This way(jsonencode) we can also avoid hardcoding parameter ARN inside code.

这篇关于如何解密Terraform数据资源返回的ssm参数安全字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 14:54