我需要在CodeBuild期间生成CloudFormation参数列表(config.json)。我的仓库中有一个bash脚本,它将包含几个参数。这将是生产,暂存或开发。
这是generator.json。此处的值将用于生成config.json。
{
"Parameters" : {
"FargateStackSuffix" : "environment-fargate",
"VPCStackSuffix": "environment-base-vpc",
"ContainerPort" : "80",
"ContainerCpu" : "256",
"ContainerMemory" : "512",
"Path" : "*",
"productionDesiredCount" : "3",
"stagingDesiredCount" : "2",
"developmentDesiredCount" : "1",
"ELBType" : "application",
"ELBIpAddressType": "ipv4",
"productionZone": "service.example.com",
"stagingZone": "service-staging.example.com",
"devZone": "service-dev.example.com"
}
}
例如:
./generate.sh my-service production
会产生这个:
{
"Parameters" : {
"FargateStackSuffix" : "production-fargate",
"VPCStackSuffix": "production-base-vpc",
"ServiceName" : "myservice",
"EnvironmentName" : "production",
"ContainerPort" : "80",
"ContainerCpu" : "256",
"ContainerMemory" : "512",
"Path" : "*",
"DesiredCount" : "3",
"ELBType" : "application",
"ELBIpAddressType": "ipv4",
"Zone": "myservice.example.com"
}
}
如您所见,基于添加项,有一些替代项。只是遍历键不会这样做。有没有办法只用jq就能完成我需要的所有eh转换?
编辑:我最终使用了一些sed过滤器替换了一些值。现在,我需要替换适当的DesiredCount:
cat .codedeploy/generator.json | jq '[paths(type == "string" and contains("DesiredCount"))]'
[]
我的问题是它返回一个空数组。
答案 0 :(得分:0)
您可以使用对象构造来执行此操作。
cat generator.json | jq --arg variable $variable '{Parameters: {DesiredCount: .Parameters.developmentDesiredCount, Zone: .Parameters.devZone, environmentName: "Production", var: $variable}}'
在这里,我显示了一些可以帮助您的解决方案。
generator.json
中的参数。 输出(不完整,但显示了解决方案)
{
"Parameters": {
"DesiredCount": "1",
"Zone": "service-dev.example.com",
"environmentName": "Production",
"var": "VariableString"
}
}
答案 1 :(得分:0)
这是一种可以生成json的方式。也许这里最棘手的部分是为环境DesiredCount
和Zone
生成动态名称。但是jq相当容易处理。
$ jq --arg ServiceName "myservice" --arg EnvironmentName "production" '.Parameters |=
{
FargateStackSuffix,
VPCStackSuffix,
$ServiceName,
$EnvironmentName,
ContainerPort,
ContainerCpu,
ContainerMemory,
Path,
DesiredCount: ."\($EnvironmentName)DesiredCount",
ELBType,
ELBIpAddressType,
Zone: ."\($EnvironmentName)Zone"
}
' generator.json > config.json
$ cat config.json
{
"Parameters": {
"FargateStackSuffix": "environment-fargate",
"VPCStackSuffix": "environment-base-vpc",
"ServiceName": "myservice",
"EnvironmentName": "production",
"ContainerPort": "80",
"ContainerCpu": "256",
"ContainerMemory": "512",
"Path": "*",
"DesiredCount": "3",
"ELBType": "application",
"ELBIpAddressType": "ipv4",
"Zone": "service.example.com"
}
}