如何评估 CDK `CfnOutput`(CloudFormation 输出)值? [英] How to evaluate CDK `CfnOutput` (CloudFormation output) values?
问题描述
我正在编写一个工具,在 cdk deploy
之后利用 CloudFormation 输出,然后使用基于这些输出的配置文件设置开发环境.
I'm writing a tool that utilitizes CloudFormation outputs after a cdk deploy
and then sets up the development environment with config files based on those outputs.
在每个核心基础架构组件(auth、db、webapp、storage 等)的末尾,我有一个 CfnOutput
构造,如下所示:
At the end of each core infrastructure component (auth, db, webapp, storage, etc.), I have a CfnOutput
construct like the following:
cdk.CfnOutput(
self, 'UserPoolID',
value=self.user_pool.user_pool_id,
)
输出类似
Stack.AuthUserPoolIDABC1234 = s1lvgk44ul23ahfd91p4rdngnf
我的目标是将该值 (s1lvgk44ul23ahfd91p4rdngnf
) 连同来自其他 CloudFormation 输出的其他值一起放入配置文件 config.js
.
My goal is to get that value (s1lvgk44ul23ahfd91p4rdngnf
) into a configuration file config.js
, along with other values from other CloudFormation outputs.
所以我围绕 CfnOutput
编写了一个包装器,如下所示:
So I wrote a wrapper around CfnOutput
like the following:
import os
def cfn_output(scope, prefix, name, value):
cdk.CfnOutput(
scope, name,
value=value,
)
# Save name and value to flat files so that we can read them in other processes
os.makedirs('.tmp', exist_ok=True)
with open(os.path.join('.tmp', f'{prefix}{name}.txt'), 'w') as f:
f.write(value)
所以我用它代替了 CfnOutput
像这样:
And so I used it instead of CfnOutput
like so:
cfn_output(
scope=self,
prefix='Auth',
name='UserPoolID',
value=self.user_pool.user_pool_id
)
当我运行 cdk synth
时,生成的文件 (.tmp/AuthUserPoolID.txt
) 具有以下内容:
When I run cdk synth
, the file generated (.tmp/AuthUserPoolID.txt
) has this content:
${Token[TOKEN.249]}
这显然不是我预期的 s1lvgk44ul23ahfd91p4rdngnf
.
which is obviously not s1lvgk44ul23ahfd91p4rdngnf
as a I expected.
是否有任何解决方案或变通方法可以将该令牌解析为可用的东西,或者可能是完全不同的解决方案?
Any solutions or workarounds to getting that token resolved into something usable, or perhaps a different solution altogether?
推荐答案
相反,我决定使用 SDK 从 CloudFormation 堆栈中获取评估输出.
Instead I decided to use the SDK to get the evaluated outputs from the CloudFormation stack.
# Prepare
cloudformation = boto3.client('cloudformation')
stack_name = 'Stack'
# Get stack outputs
res = cloudformation.describe_stacks(StackName=stack_name)
outputs = res['Stacks'][0]['Outputs']
mp = {
'ApiURL': '',
'AuthUserPoolClientID': '',
'AuthUserPoolID': '',
'DatabaseName': '',
'StorageHostingBucketName': '',
'WebappURL': '',
}
# Parse stack output names
for output in outputs:
ok = output['OutputKey']
ov = output['OutputValue']
for k in mp:
if ok.startswith(k):
mp[k] = ov
# Generate config.js data
data = {
'endpoint': mp['ApiURL'],
'userPoolId': mp['AuthUserPoolID'],
'userPoolClientId': mp['AuthUserPoolClientID'],
}
json_data = json.dumps(data, separators=(',', ':'))
text = f'window.config={json_data}'
# Write ac.js
configjs = os.path.join(os.path.dirname(__file__), '../static/config.js')
with open(configjs, 'w') as f:
f.write(text)
这篇关于如何评估 CDK `CfnOutput`(CloudFormation 输出)值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!