How to pass AWS secret key and id in jenkins build pipeline script?

Viewed 8925

I am trying to pass the AWS secret key and password into jenkins script (which creates the env file)

My code:

node {

    writeFile file: 'temp_env.txt', text: """
    AWS_ACCESS_KEY= << Access Key >>
    AWS_SECRET_KEY= << password >>
  """
docker.withRegistry('https://quay.io', 'c5234316dc-dqwqwda1-415645452-b343-406bf8332edb') {

        sh 'docker pull quay.io/docker_image'
        docker.image ('quay.iodocker_image').run('-it --env-file temp_env.txt --name test quay.io/docker_image:develop ./code/test1.py test-service')
        sh 'rm temp_env.txt'
    }
}

I am using the actual secret key and id, i would rather have the credentials injected here. How can I achieve it? I read the entire instructions here but was not able to figure out.

I know how to use the credentials binding plug-in, but not sure how I can add the user_name and password credentials variables to my code.

2 Answers

Solution: The best practice for storing credentials, api tokens and secret keys is to store it on global credentials in jenkins ( this applies to all scope of credentials in the project/item/object) and get it pipeline code. This methodology prevents users storing sensitive data in plain-text insecurely on their code/project.

I'll demonstrate it with short example: On this example I'll store an api token of my app in Jenkins credentials ,get it in my pipeline step and curl it to perform some rest api HTTP operation on my server.

First Store it:

Jenkins -> Credentials -> Global -> Add Credentials -> Select your type and fill in the details

enter image description here In my example I create secret text with secret xxx, the ID would be MY_SECRET_TOKEN and the description would be my secret token for my api service. Than I'll save it and my pipeline would be like below...

script{
   withCredentials([
      string(
         credentialsId: 'MY_SECRET_TOKEN',
         variable: 'TOKEN_VARIABLE')
      ]) {
      sh """#!/bin/bash
         curl -k -L -H 'Authorization: Token ${TOKEN_VARIABLE}' 
         https://myservice/api/users/someaction/
      """
  }
}

For more information look on the documentation

Related