[英]Run AWS CLI KMS encrypt commands from Cloudformation
我有 2 個 cloudformation 模板 - 一個創建 kms 密鑰,另一個模板使用 kms 密鑰加密 lambda 函數中使用的 env 變量。
我想知道是否有辦法從 cloudformation 中運行 kms encrypt 命令作為先前的步驟,然后在創建 lambda 函數時使用環境變量的加密文本。
aws kms encrypt --key-id <key-id-output-from-stack1> --plaintext fileb://file.txt --query CiphertextBlob --output text > fileoutput.txt
此命令輸出加密文本,我需要在 lambda 函數中使用此文本作為環境變量之一,如下所示。
GTMLambdaFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: s3://test.google.com/lambdas/09yu567943879
Handler: src/lambda.handler
FunctionName: !Ref GTMLambdaFunctionName
Runtime: nodejs10.x
MemorySize: !Ref GTMLambdaMemorySize
Timeout: !Ref GTMLambdaTimeout
AutoPublishAlias: prod
Role: !GetAtt GTMLambdaRole.Arn
KmsKeyArn: !ImportValue GTMKMSKeyArn
Environment:
Variables:
url: >-
**{insert encrypted text}**
tbl_prefix: gtm-
如果這是不可能的,是否有任何關於如何實現這一目標的建議? 提前致謝。
您可以為此使用自定義資源。 它將執行一個 Lambda 函數,該函數將加密並返回值。 然后可以在環境變量中使用該值。
類似於以下內容。 確保有一個名為KeyId
的資源/參數/輸出和 KMS 密鑰 ID。
Resources:
EncryptEnvRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action: sts:AssumeRole
Effect: Allow
Principal:
Service: lambda.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: DescribeImages
PolicyDocument:
Version: '2012-10-17'
Statement:
- Action: kms:Encrypt
Effect: Allow
Resource: "*"
EncryptEnvFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.6
Handler: index.handler
Role: !Sub ${EncryptEnvRole.Arn}
Timeout: 60
Code:
ZipFile:
Fn::Sub: |
import base64
import boto3
import cfnresponse
import traceback
def handler(event, context):
try:
t = event['ResourceProperties']['Value']
k = event['ResourceProperties']['KeyId']
v = base64.b64encode(boto3.client('kms').encrypt(KeyId=k, Plaintext=t.encode('utf-8'))['CiphertextBlob']).decode('utf-8')
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, v)
except:
traceback.print_last()
cfnresponse.send(event, context, cfnresponse.FAIL, {}, 'ok')
EncryptedEnv:
Type: Custom::EncryptEnv
Properties:
ServiceToken: !Sub ${EncryptEnvFunction.Arn}
Value: "hello world"
KeyId: !ImportValue KeyId
GTMLambdaFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: s3://test.google.com/lambdas/09yu567943879
Handler: src/lambda.handler
FunctionName: !Ref GTMLambdaFunctionName
Runtime: nodejs10.x
MemorySize: !Ref GTMLambdaMemorySize
Timeout: !Ref GTMLambdaTimeout
AutoPublishAlias: prod
Role: !GetAtt GTMLambdaRole.Arn
KmsKeyArn: !ImportValue GTMKMSKeyArn
Environment:
Variables:
url: !Ref EncryptedEnv
tbl_prefix: gtm-
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.