从 ASG 名称前缀检索 Jenkins Groovy 脚本化管道中的 AWS EC2 Autoscaling 组名称

问题描述 投票:0回答:1

我正在尝试使用 Groovy 脚本化 Jenkins 管道中的 ASG 名称前缀检索 AWS EC2 Autoscaling Group (ASG) 名称查询。

到目前为止,我尝试在 Groovy 脚本中使用 AWS CLI,但没有成功。我认为我面临的主要挑战是在

sh
命令中处理 3 个不同级别的引号:1) Sh 命令必须用引号括起来 2) 在查询字符串内部必须用引号括起来,3)其中来自
asg_name_prefix
的值必须用引号引起来。

到目前为止我所做的就是这些。如果有其他解决方案,我可以接受,除非脚本太复杂太长。

当我在 bash 中运行以下行时,它会检索所需的 EC2 Autoscaling 组名称并存储在

asg_name
:

asg_name=$(aws autoscaling describe-auto-scaling-groups --query "AutoScalingGroups[?starts_with(AutoScalingGroupName, '${asg_name_prefix}')].AutoScalingGroupName" --output text | head -n 1)
echo "asg_name: $asg_name"

输出:

asg_name: my-app-asg-01

当我尝试按照以下方式在 Groovy for Jenkins 管道中使用它时,它不会检索 Aautoscaling 组名称:

def asg_name = sh(script: """ aws autoscaling describe-auto-scaling-groups --query "AutoScalingGroups[?starts_with(AutoScalingGroupName, '${asg_name_prefix}')].AutoScalingGroupName" --output text | head -n 1""", returnStdout: true).trim()
echo "asg_name: ${asg_name}"

它没有给出任何错误,但该行的控制台输出如下所示:

21:34:43  [Pipeline] sh
21:34:43  + aws autoscaling describe-auto-scaling-groups --query AutoScalingGroups[?starts_with(AutoScalingGroupName, 'my-app-asg-')].AutoScalingGroupName --output text
21:34:43  + head -n 1
21:34:43  [Pipeline] echo
21:34:43  asg_name:

我的理解是该命令的

query
字符串部分必须用引号引起来。因此,我尝试通过以下方式转义双引号,但行为仍然相似 - 不起作用:

def asg_name = sh(script: """ aws autoscaling describe-auto-scaling-groups --query \"AutoScalingGroups[?starts_with(AutoScalingGroupName, '${asg_name_prefix}')].AutoScalingGroupName\" --output text | head -n 1""", returnStdout: true).trim()
echo "asg_name: ${asg_name}"

这次上述命令的控制台输出显示双引号未保留,并且管道化的

head -n 1
显示在实际命令之前:

21:59:29  [Pipeline] sh
21:59:29  + head -n 1
21:59:29  + aws autoscaling describe-auto-scaling-groups --query AutoScalingGroups[?starts_with(AutoScalingGroupName, 'my-app-asg-')].AutoScalingGroupName --output text
21:59:29  [Pipeline] echo
21:59:29  asg_name: 

我怎样才能做到这一点,以便将自动缩放组名称存储在 Groovy 变量中

asg_name

注:

  1. 更新添加额外的行以显示准确的控制台输出。
  2. 更改了标题并添加了更多信息来澄清我的问题,因为我需要一个解决方案来从前缀检索 EC2 ASG 名称。主要问题是无法在 Jenkins 中处理引号。
bash groovy escaping jenkins-groovy
1个回答
0
投票

您可以使用groovy来解析来自aws的jsnon响应。

我们假设

aws autoscaling describe-auto-scaling-groups --output json

结果类似于:

{
    "AutoScalingGroups": [
        {
            "AutoScalingGroupName": "other-app-asg-01",
            "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:..."
        },
        {
            "AutoScalingGroupName": "my-app-asg-01",
            "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:..."
        }
    ]
}

然后在詹金斯常规中以下应该可以工作:

def asg_json = sh("aws autoscaling describe-auto-scaling-groups --output json", returnStdout: true)
asg_json = readJSON(text: asg_json)
def asg_name = asg_json.AutoScalingGroups.find{it.AutoScalingGroupName =~ /^my-app-asg-/}.AutoScalingGroupName

作为您原始问题的故障排除模型:

而不是

sh("""...""")
使用
echo("""...""")
并确保在日志输出中具有所需的 shell 语法

© www.soinside.com 2019 - 2024. All rights reserved.