Search code examples
jenkinsjenkins-pipelinejenkins-groovy

how to add a secret file credential to a jenkins pipeline stage using withCredentials syntax


My jenkins pipeline stage works find when I just use aws credentials alone. However I am trying to add in a second withCredentials in the same pipeline stage to point to a secret file called kubeconfig (this holds my kubeconfig file and is stored in the jenkins credentials) But I cannot get this to work. Would anyone mind taking a second look to review my syntax here please and if I'm missing some configuration. Thanks Brian

           steps {
               
        withCredentials([[
                      $class: 'AmazonWebServicesCredentialsBinding',
                      accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                      credentialsId: 'awstoEKS',  // ID of credentials in Jenkins
                      secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
                  ],
                  [
                      credentialsId: 'kubeconfig',
                      Variable: 'kubeconfig'
                      ])
                      
                   {

               script{ 

Solution

  • With your example, you have specified correctly for AmazonWebServicesCredentialsBinding and missed the secret file details. It will be like the below example:

    pipeline {
        agent any;
        stages {
            stage('debug') {
                steps {
                    withCredentials([
                        file(credentialsId: 'secret-file', variable: 'FILE'),
                        [
                            $class: 'AmazonWebServicesCredentialsBinding',
                            accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                            credentialsId: 'awstoEKS',
                            secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
                        ]
                        
                    ]) {
                        
                      
                      sh """
                        cat $FILE
                        curl -u $AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY https:/do.something.aws.com > output
                      """
                    }
                }
            }
        }
    }
    

    If I correct your example it will be:

    ....
    steps {
       withCredentials([
           file(credentialsId: 'kubeconfig', variable: 'kubeconfig'),
           [
               $class: 'AmazonWebServicesCredentialsBinding',
               accessKeyVariable: 'AWS_ACCESS_KEY_ID',
               credentialsId: 'awstoEKS',  // ID of credentials in Jenkins
               secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
           ]
       ]) {
          sh """
             echo 'do something with' $kubeconfig $AWS_ACCESS_KEY_ID $AWS_SECRET_ACCESS_KEY
          """
    
       }
    }
    
    

    you can find more example from jenkins documentation