Jenkins – 在Scripted Pipeline中获取用户输入的字符串

74次阅读
没有评论

问题描述

在设置一个scripted Jenkins流水线时,遇到了在流水线中设置一个输入步骤的问题,该步骤允许用户输入一个字符串。
具体场景是这样的:用户正在构建一个Docker镜像,他想要询问用户在构建完成后如何为镜像打标签。用户希望用户能够提供一个逗号分隔的标签列表,类似于:latest,0.0.4,some-tag-name。
目前,他只有一个输入步骤,询问用户是否应该构建核心镜像:

def buildCoreImage = input(
  message: 'Build Core Image?',
  ok: 'Yes',
  parameters: [
    booleanParam(
      defaultValue: true,
      description: 'Push the button to build core image.',
      name: 'Yes?'
    )
  ]
)
echo "Build core?:" + buildCoreImage

理论上来说,只需要将booleanParam更改为stringParam就可以了,但是文档中并没有相关内容:Jenkins – Pipeline: Input Step
感谢您的时间!

解决方案

请注意以下操作可能会涉及版本差异及备份操作。
为了在Jenkins的Scripted Pipeline中获取用户输入的字符串,您可以使用input步骤,并且指定一个字符串参数来实现。以下是您可以使用的解决方案之一:

def coreImageTags = input(
  id: 'coreImageTags',
  message: 'Enter a comma separated list of additional tags for the image (0.0.1,some-tagname,etc):?',
  parameters: [
    [$class: 'StringParameterDefinition', defaultValue: 'None', description: 'List of tags', name: 'coreImageTagsList']
  ]
)
echo ("Image tags: " + coreImageTags)

重要提示:根据文档的说明,如果您复制/粘贴上述解决方案,coreImageTags将直接包含一个字符串。如果您需要多个参数,您可以像下面这样定义:

parameters: [
  [$class: 'StringParameterDefinition', defaultValue: 'None', description: 'List of tags', name: 'coreImageTagsList'],
  [$class: 'StringParameterDefinition', defaultValue: 'None', description: 'Something else', name: 'somethingElse']
]

这将导致coreImageTags变为一个值的数组,您可以通过指定参数名来访问不同的值,例如:coreImageTags['coreImageTagsList']
以下资源可能对您有所帮助:
stackoverflow.com read-interactive-input-in-jenkins-pipeline-to-a-variable
CloudBees – Pipeline-How-to-manage-user-inputs
– Jenkins Input-Step文档中列出了可以在此方式中使用的类以及它们的功能:Pipeline – Input Step
请注意,确保您的Jenkins版本与上述解决方案中的代码和说明相匹配,以确保操作顺利进行。

正文完