bitbrain
bitbrain

Reputation: 619

How to load AWS credentials in Jenkins job DSL?

I have the following DSL structure:

freeStyleJob {
  wrappers {
    credentialsBinding {
      [
         $class:"AmazonWebServicesCredentialsBinding",
         accessKeyVariable: "AWS_ACCESS_KEY_ID",
         credentialsId: "your-credential-id",
         secretKeyVariable: "AWS_SECRET_ACCESS_KEY"
      ]
     }
   }
   steps {
      // ACCESS AWS ENVIRONMENT VARIABLES HERE!
   }
}

However, this does not work. What is the correct syntax to do so? For Jenkins pipelines, you can do:

withCredentials([[
$class: "AmazonWebServicesCredentialsBinding",
accessKeyVariable: "AWS_ACCESS_KEY_ID",
credentialsId: "your-credential-id",
secretKeyVariable: "AWS_SECRET_ACCESS_KEY"]]) {
  // ACCESS AWS ENVIRONMENT VARIABLES HERE!
}

but this syntax does not work in normal DSL job groovy.

tl;dr how can I export AWS credentials defined by the AmazonWebServicesCredentialsBinding plugin into environment variables in Groovy job DSL? (NOT PIPELINE PLUGIN SYNTAX!)

Upvotes: 10

Views: 9400

Answers (3)

Logan Waggoner
Logan Waggoner

Reputation: 71

This is the full detailed answer that @bitbrain did with possible fix for issue reported by @Viacheslav

freeStyleJob {
    wrappers {
      credentialsBinding {
        amazonWebServicesCredentialsBinding {
          accessKeyVariable("AWS_ACCESS_KEY_ID")
          secretKeyVariable("AWS_SECRET_ACCESS_KEY")
          credentialsId("your-credentials-id")
        }
      }
    }
}

Ensure this is on the classpath for compilation: compile "org.jenkins-ci.plugins:aws-credentials:1.23"

If you have tests running you might also need to add the plugin to the classpath: testPlugins "org.jenkins-ci.plugins:aws-credentials:1.23"

I believe this is why there are reports of people needing to manually modify the XML to get this to work. Hint: if you can pass the compile stage (or compile in IDE) but not able to compile tests then this is the issue.

Upvotes: 0

Viacheslav
Viacheslav

Reputation: 1465

I'm not able to re-use Miguel's solution (even with installed aws-credentials plugin), so here is another approach with DSL configure block

    configure { project ->
        def bindings = project / 'buildWrappers' / 'org.jenkinsci.plugins.credentialsbinding.impl.SecretBuildWrapper' / 'bindings'
        bindings << 'com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentialsBinding' {
            accessKeyVariable("AWS_ACCESS_KEY_ID")
            secretKeyVariable("AWS_SECRET_ACCESS_KEY")
            credentialsId("credentials-id")
        }
    }

Upvotes: 1

bitbrain
bitbrain

Reputation: 619

I found a solution to solve this problem:

wrappers {
  credentialsBinding {
    amazonWebServicesCredentialsBinding {
      accessKeyVariable("AWS_ACCESS_KEY_ID")
      secretKeyVariable("AWS_SECRET_ACCESS_KEY")
      credentialsId("your-credentials-id")
    }
  }
}

This will lead to the desired outcome.

Upvotes: 12

Related Questions