0
votes

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.

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,
)

Which outputs something like

Stack.AuthUserPoolIDABC1234 = s1lvgk44ul23ahfd91p4rdngnf

My goal is to get that value (s1lvgk44ul23ahfd91p4rdngnf) into a configuration file config.js, along with other values from other CloudFormation outputs.

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)

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
)

When I run cdk synth, the file generated (.tmp/AuthUserPoolID.txt) has this content:

${Token[TOKEN.249]}

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?

1

1 Answers

0
votes

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)