在 jenkins 属性中使用凭据

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

我正在尝试使用 jenkins 中特定 SVN 存储库中的每个分支/标签创建自定义列表。我正在使用 groovy 脚本来创建所需的列表,因为

List Subversion tags (and more)
插件无法返回所需的输出,例如[分支/myBranche1、分支/myBranche2、标签/myTag、主干]。

我目前的管道是:

pipeline {
    agent none
    stages {
        stage('Test') {
            agent any
            steps {
                echo "${params.SVN}"
            }
        }
    }
}
properties([
   parameters([
      [$class: 'ChoiceParameter',
        name: 'SVN',
        description: 'Select the SVN',
        choiceType: 'PT_SINGLE_SELECT',
        filterable: true,
        randomName: 'choice-parameter',
        script: [
            $class: 'GroovyScript',
            script: [
                script: '''
                    import jenkins.model.* 
                    import hudson.model.*
                    
                    def proc = "svn list --depth=immediates --username jenkins --password mypassword https://my.svn.com/svn/myTest/branches".execute()
                    def sout = new StringBuilder(), serr = new StringBuilder()
                    proc.waitForProcessOutput(sout, serr)
                    proc.waitForOrKill(10000) // Set timeout
                    def procT = "svn list --depth=immediates --username jenkins --password mypassword https://my.svn.com/svn/myTest/tags".execute()
                    def soutT = new StringBuilder(), serrT = new StringBuilder()
                    procT.waitForProcessOutput(soutT, serrT)
                    procT.waitForOrKill(10000) // Set timeout
                    
                    def resB = sout.toString().split('\\n').findAll { it.trim() }.collect { it.trim() }
                    def branches = resB.collect { "branches/${it}" }
                    
                    def resT = soutT.toString().split('\\n').findAll { it.trim() }.collect { it.trim() }
                    def tags = resT.collect { "tags/${it}" }
                    
                    def choices = ['trunk'] + branches + tags
                    return choices
                ''',
                sandbox: false
            ]
        ]
      ]
    ])
])

此管道返回预期值。虽然,我需要使用凭据而不是硬编码值。我尝试使用 withCredentials 和凭证功能,但它们都不起作用。我需要使用的 credentialId 是

jenkins-svn
。关于如何实现该逻辑有什么想法吗?请注意,我必须将参数保留在属性部分中。

jenkins groovy jenkins-pipeline jenkins-groovy credentials
1个回答
0
投票

我找到了我在帖子中提到的问题的解决方案。我还添加了一种使用环境变量为 choiceParameter 设置默认值的方法。答案可以在下面找到:

pipeline {
    agent none
    stages {
        stage('SVN Actions') {
            agent any
            steps {
                echo "${params.SVN}"
            }
        }
    }
}
properties([
    parameters([
        [$class: 'ChoiceParameter',
            name: 'SVN',
            description: 'Select the SVN',
            choiceType: 'PT_SINGLE_SELECT',
            filterable: true,
            randomName: 'choice-parameter',
            script: [
                $class: 'GroovyScript',
                script: [
                    script: '''
                        import jenkins.model.*
                        import hudson.model.*
                        import com.cloudbees.plugins.credentials.Credentials
                        import com.cloudbees.plugins.credentials.CredentialsProvider
                        import com.cloudbees.plugins.credentials.domains.DomainRequirement
                        import hudson.slaves.EnvironmentVariablesNodeProperty

                        def credentialId = 'jenkins-svn'
                        def svnUrl = 'https://my.svn.com/svn/myTest'

                        // Get the Jenkins instance
                        def jenkinsInstance = Jenkins.instance

                        // Retrieve DEFAULT_VALUE from global properties
                        def defaultValue = 'trunk'
                        jenkinsInstance.globalNodeProperties.getAll(EnvironmentVariablesNodeProperty).each { envNodeProperty ->
                            def value = envNodeProperty.envVars.get('DEFAULT_VALUE')
                            if (value != null) {
                                defaultValue = value
                            }
                        }

                        Credentials specificCredential = null
                        
                        // Search for the credential in Jenkins root
                        def creds = CredentialsProvider.lookupCredentials(
                            Credentials.class, jenkinsInstance, null, (List<DomainRequirement>) null
                        )
                        specificCredential = creds.find { it.id == credentialId }
                        
                        if (specificCredential != null) {
                            def branchesProc = ["svn", "list", "--depth=immediates", "--username", specificCredential.username, "--password", specificCredential.password, "${svnUrl}/branches"].execute()
                            def branchesOut = new StringBuilder(), branchesErr = new StringBuilder()
                            branchesProc.waitForProcessOutput(branchesOut, branchesErr)
                            branchesProc.waitForOrKill(10000) // Set timeout
                            
                            def tagsProc = ["svn", "list", "--depth=immediates", "--username", specificCredential.username, "--password", specificCredential.password, "${svnUrl}/tags"].execute()
                            def tagsOut = new StringBuilder(), tagsErr = new StringBuilder()
                            tagsProc.waitForProcessOutput(tagsOut, tagsErr)
                            tagsProc.waitForOrKill(10000) // Set timeout
                            
                            def branches = branchesOut.toString().split('\\n').findAll { it.trim() }.collect { "branches/${it.replaceAll('/$', '').trim()}" }
                            def tags = tagsOut.toString().split('\\n').findAll { it.trim() }.collect { "tags/${it.replaceAll('/$', '').trim()}" }
                            
                            def choices = [defaultValue] + branches + tags + ['trunk']
                            choices = choices.unique() // Remove any duplicates
                            return choices
                        } else {
                            throw new Exception("Credential with ID '${credentialId}' not found.")
                        }
                    ''',
                    sandbox: false
                ]
            ]
        ]
    ])
])
© www.soinside.com 2019 - 2024. All rights reserved.