密码凭证参数的用户名使用Groovy命令执行Groovy构建步骤

密码凭证参数的用户名使用Groovy命令执行Groovy构建步骤

本文介绍了从Jenkins访问带有密码凭证参数的用户名使用Groovy命令执行Groovy构建步骤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

软件级别:

  • Jenkins 2.121.2
  • 凭据插件2.1.18
  • 凭证绑定插件1.16
  • 普通证书插件1.4

我正在处理Freestyle项目(而不是管道),并且希望对工作的主要处理使用Groovy命令构建步骤.

I am working with a Freestyle project (not a pipeline) and want to use a Groovy command build step for the job's main processing.

我正在尝试从用户凭证中获取用户名和密码,以便常规脚本可以将其用于各种CLI操作.我花了很多时间来寻找答案,但是我发现没有一个起作用.大多数人不清楚,许多人是针对管道的.

I am trying to obtain the userid and password from a user credential so the groovy script can use them for various CLI manipulations. I spent a lot of time searching for answers, but none of the ones I've found worked. Most were not clear, many were geared toward pipelines.

在这一点上,我将不胜感激.

I would greatly appreciate a little guidance at this point.

以下是血腥细节.

我创建了一个新的参数化Freestyle项目,在其中为用户名和密码"凭据添加了凭据参数.它默认为我通过凭据插件定义给Jenkins的凭据之一.如果绑定选择要显式使用的凭据,我不确定是否有必要.

I created a new parameterized Freestyle project in which I added a Credentials Parameter for a "Username and password" credential. It defaults to one of the credentials that I defined to Jenkins via the Credentials Plugin. I'm not sure this is necessary if the binding selects the credential to use explicitly.

我不确定在构建环境"部分中是否使用了使用秘密文本或文件",尽管我不确定这对于用户名/密码样式绑定是必不可少的.

I checked "Use secret text(s) or file(s)" in the Build Environment section, although I'm not certain that is essential for a Username/password style binding.

我添加了用户名和密码(分隔)"绑定,并将USERID和PASSWORD设置为各自的变量.

I added a "Username and password (separated)" binding and set USERID and PASSWORD as the respective variables.

我的groovy命令窗口有以下一行:println("$ {USERID} $ {PASSWORD}")

My groovy command window has this sole line:println("${USERID} ${PASSWORD}")

建立工作时,出现此错误:

When I build the job, I get this error:

推荐答案

这两种方式都会将凭据注入环境变量,因此您可以从Groovy脚本的环境变量中访问它们,如下所示方式.

The both ways will inject the credential into Environment Variable, thus you can access them from Environment Variable in Groovy Script as following for both ways.

def env = System.getenv()
println env['auth']
println env['USERNAME']
println env['PASSSWORD']

但是两种方式的注入值都不同.

But the injected value of the both ways are different.

1)添加凭据作业参数供用户在运行作业时选择

通过这种方式,将插入credentialId,因此您将无法获得用户名和密码.

In this way, the credentialId is injected, so you not get the username and password.

credentialId example: 1dd4755a-9396-4819-9327-86f25650c7d7

2)使用凭据绑定

这样,用户名和密码就被注入了,我想这就是您想要的.

In this way, the username and password are injected, I think this is what you wanted.

def env = System.getenv()
def username = env['USERNAME']
def password = env['PASSSWORD']

def cmd = "curl -u $username:$password ...."

通过插件Execute Groovy script

这篇关于从Jenkins访问带有密码凭证参数的用户名使用Groovy命令执行Groovy构建步骤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 14:50