如何在Groovy脚本中提取Jenkins FQDN并在Bash脚本中使用?
解决Groovy提取Jenkins URL主机名并传递给Bash脚本的问题
1. 正确提取主机名
不要用split('/')拆分URL,Groovy自带的URL类可以直接解析URL的各个组成部分,适配性更强(比如兼容带端口的URL):
def url = new URL(env.JENKINS_URL) def hostfqdn = url.host // 直接得到 dev.blsm.comp.com
如果坚持用拆分方式,需要取数组的第2个元素(拆分后数组为["https:", "", "dev.blsm.comp.com", ...]):
def hostfqdn = "${env.JENKINS_URL}".split('/')[2]
2. 将Groovy变量传递给Bash脚本
Groovy变量与Bash脚本变量相互隔离,以下两种方式可实现传递:
方式一:Groovy字符串插值(用双引号包裹Bash脚本)
用"""包裹Bash脚本,Groovy会自动将变量值插入脚本中,注意转义Bash里的$符号(避免Groovy误解析):
steps { container('main') { script { def url = new URL(env.JENKINS_URL) def hostfqdn = url.host withCredentials([[$class: 'VaultUsernamePasswordCredentialBinding', credentialsId: 'vaulted-jenkins-api-token' , passwordVariable: 'JENKINS_USER_TOKEN', usernameVariable: 'JENKINS_USERNAME']]) { sh """ echo ${hostfqdn} """ sh '''export JENKINS_CRUMB=$(curl -u "$JENKINS_USERNAME:$JENKINS_USER_TOKEN" -s --cookie-jar /tmp/cookies $JENKINS_URL'/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)')''' sh(script: """#!/bin/bash echo ${hostfqdn} curl -X POST https://${JENKINS_USERNAME}:${JENKINS_USER_TOKEN}@${hostfqdn}/credentials/store/system/domain/_/createCredentials \\ --data-urlencode 'json={ "credentials": { "scope": "GLOBAL", "id": "identification", "username": "manu", "password": "bar", "description": "linda1", "\$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl" } }' echo "Creds link is \${credsLink}" """) } } } }
方式二:将Groovy变量设为环境变量
把提取到的hostfqdn注入Jenkins Pipeline的环境变量,Bash脚本可直接通过$hostfqdn读取:
steps { container('main') { script { def url = new URL(env.JENKINS_URL) def hostfqdn = url.host env.hostfqdn = hostfqdn // 将变量转为环境变量 withCredentials([[$class: 'VaultUsernamePasswordCredentialBinding', credentialsId: 'vaulted-jenkins-api-token' , passwordVariable: 'JENKINS_USER_TOKEN', usernameVariable: 'JENKINS_USERNAME']]) { sh ''' echo $hostfqdn ''' // 可正确输出主机名 sh '''export JENKINS_CRUMB=$(curl -u "$JENKINS_USERNAME:$JENKINS_USER_TOKEN" -s --cookie-jar /tmp/cookies $JENKINS_URL'/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)')''' sh(script: '''#!/bin/bash echo ${hostfqdn} curl -X POST https://${JENKINS_USERNAME}:${JENKINS_USER_TOKEN}@${hostfqdn}/credentials/store/system/domain/_/createCredentials \\ --data-urlencode 'json={ "credentials": { "scope": "GLOBAL", "id": "identification", "username": "manu", "password": "bar", "description": "linda1", "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl" } }' echo "Creds link is ${credsLink}" ''') } } } }
3. 错误原因说明
你之前的代码存在两个核心问题:
split('/')返回的是数组而非单个字符串,导致hostfqdn无法直接在Bash中使用;- Bash脚本用
'''包裹时,Groovy不会插值变量,使得Bash里的$hostfqdn为空,最终引发curl的URL格式错误。
内容的提问来源于stack exchange,提问作者AhmFM
相关产品推荐
相关产品推荐

