我有一个需求,我需要根据TargetHealth
状态为AWS目标组中的目标调用某些功能或说命令。我执行以下操作以获取目标组中的目标列表:-
aws elbv2 --region us-east-1 describe-target-health --target-group-arn=******
{
"TargetHealthDescriptions": [{
"Target": {
"Id": "***",
"Port": 80
},
"TargetHealth": {
"State": "initial",
"Reason": "Elb.RegistrationInProgress",
"Description": "Target registration is in progress"
}
},
{
"Target": {
"Id": "***",
"Port": 80
},
"TargetHealth": {
"State": "unhealthy",
"Reason": "Target.Timeout",
"Description": "Connection to target timed out"
}
},
{
"HealthCheckPort": "80",
"Target": {
"Id": "***",
"Port": 80
},
"TargetHealth": {
"State": "healthy"
}
},
{
"HealthCheckPort": "80",
"Target": {
"Id": "***",
"Port": 80
},
"TargetHealth": {
"State": "healthy"
}
},
{
"HealthCheckPort": "80",
"Target": {
"Id": "***",
"Port": 80
},
"TargetHealth": {
"State": "healthy"
}
},
{
"HealthCheckPort": "80",
"Target": {
"Id": "***",
"Port": 80
},
"TargetHealth": {
"State": "healthy"
}
},
{
"HealthCheckPort": "80",
"Target": {
"Id": "***",
"Port": 80
},
"TargetHealth": {
"State": "healthy"
}
}
]
}
一旦我要执行的所有目标都获得JSON响应,如果条件仅当目标数目> 4并且所有目标都健康时才确保,那么请执行xyz ...所以说类似
if ( countoftarget >4 && alltargethasstate == healthy) then
echo "*****"
else
sleep 2 minutes and keep checking the loop
是否有一种方法可以使用jq
解析所有目标的状态值,并实现一个Shell脚本来执行此循环条件。
答案 0 :(得分:0)
这里有个小片段,可以帮助您在没有jq
的情况下实现这一目标。
HEALTHY_COUNT=`aws elbv2 --region us-east-1 describe-target-health --target-group-arn=******* \
--query 'TargetHealthDescriptions[?TargetHealth.State==\`healthy\`].[Target.Id]' --output text | wc -l`
echo $HEALTHY_COUNT
if [ $HEALTHY_COUNT -eq 1 ]; then
echo "All izzz well!!!"
else
echo "Recheck how many healthy"
fi
这里有趣的部分是query
,用于控制was cli的输出。请参见aws cli documentation,尤其是本节
“如何使用--query选项过滤输出”。查询选项基于此处介绍的JMESPath,在使用AWS CLI时非常漂亮。
答案 1 :(得分:0)
在这里使用jq的潜在优势之一是,您可以轻松避免多次调用aws。
[.TargetHealthDescriptions[]
| select(.TargetHealth.State == "healthy")]
| . as $targets # in case you want to do something with them if the counting condition is satisfied
| length | if . > 4 then "found \(.) targets" else empty end