输出到CloudFormation查询参数

问题描述

说我从CloudFormation堆栈查询中得到以下输出

$ aws cloudformation describe-stacks --stack-name my-stack --query "Stacks[0].Outputs[*]"
[
    {
        "OutputKey": "VPC","OutputValue": "vpc-123abcd"
    },{
        "OutputKey": "subnetAZ2","OutputValue": "subnet-456efgh"
    },{
        "OutputKey": "subnetAZ1","OutputValue": "subnet-789ijkl"
    },{
        "OutputKey": "PrivatesubnetAZ2","OutputValue": "subnet-012mnop"
    },{
        "OutputKey": "PrivatesubnetAZ1","OutputValue": "subnet-345qrst"
    }
]

我想将此输出格式化为可在aws cloudformation create-stack命令中使用的字符串,如下所示:

aws cloudformation create-stack \
  ...
  --parameters "ParameterKey=VPC,ParameterValue=vpc-123abcd ParameterKey=subnetAZ2,..."

问题:如何使用JMESPath将对象列表(如上面的对象)转换为格式化的字符串(如上面的对象)?

似乎可以通过使用map来实现这一点,

--query Stacks[0].Outputs[*].{ParameterKey: OutputKey,ParameterValue: OutputValue} | map([&ParameterKey,&ParameterValue],@)

解决方法

您可以尝试以下操作:

aws cloudformation describe-stacks --stack-name <stack-name> --query "Stacks[0].Outputs[*].[join(',',[join('=',['ParameterKey',OutputKey]),join('=',['ParameterValue',OutputValue])])] | join(' ',[])" --output text

它相当不可读,但是JMESPath语法远非如此。基本上,想法是使用join以所需的格式压缩整个字符串。

首先,您要构造内部部分(例如ParameterKey=VPCParameterValue=vpc-123abcd),然后将其合并到ParameterKey=VPC,ParameterValue=vpc-123abcd中。最终,您将所有这些都组合在一起以构造ParameterKey=VPC,ParameterValue=vpc-123abcd ParameterKey=SubnetAZ2,ParameterValue=subnet-456efgh