Search code examples
amazon-web-servicesjenkinsjenkins-pipelinejenkins-groovycredentials

How can I use AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to perform actions in AWS through a Jenkins pipeline?


I'm trying to create a Jenkins pipeline (.jenkinsfile) to perform some actions in AWS, but cannot give everyone in my company access to the pipeline. My thought was to have the user paste in their AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY values (these values are refreshed every 24 hours) into Jenkins pipeline parameters and then use them as some type of credentials in the .jenkinsfile. If the user pastes in wrong values/does not have the correct permissions to run the code, the job will fail. So far I have been unable to find a way to do this as all the examples I've seen have been using existing credentials stored on the Jenkins server, and not generating them for each run.

I've tried the following bits of code with no luck:

environment {
   TMP_AWS_CREDS =
     credentialsBinding {
       amazonWebServicesCredentialsBinding {
         accessKeyVariable(${AWS_ACCESS_KEY_ID})
         secretKeyVariable(${AWS_SECRET_ACCESS_KEY})
         credentialsId('temp-aws-creds')
       }
     }
}

steps {
  withAWS(credentials: "${TMP_AWS_CREDS}, region: 'ap-southeast-4') {
    // some block
  }
}

and

steps {
  withAWS(credentials: wrappers {
    credentialsBinding {
      amazonWebServicesCredentialsBinding {
        accessKeyVariable(${AWS_ACCESS_KEY_ID})
        secretKeyVariable(${AWS_SECRET_ACCESS_KEY})
        credentialsId('temp-aws-creds')
      }
    }
  }, region: 'ap-southeast-4') {
     // some block
  }
}

and

steps {
  withAWS(credentials: '[certificate(credentialsId: 'temp-aws-creds', \
    keystoreVariable: AWS_ACCESS_KEY_ID, \
    passwordVariable: AWS_SECRET_ACCESS_KEY)]', region: 'ap-southeast-4') {
                            // some block
  }
}

Solution

  • Use this pipeline pipeline { agent any

        parameters {
            string(name: 'AWS_ACCESS_KEY_ID', defaultValue: '', description: 'AWS Access Key ID')
            string(name: 'AWS_SECRET_ACCESS_KEY', defaultValue: '', description: 'AWS Secret Access Key')
        }
    
        environment {
            AWS_ACCESS_KEY_ID = "${params.AWS_ACCESS_KEY_ID}"
            AWS_SECRET_ACCESS_KEY = "${params.AWS_SECRET_ACCESS_KEY}"
            AWS_REGION = 'ap-southeast-4' // Set your desired region
        }
    
        stages {
            stage('Run AWS Commands') {
                steps {
                    script {
                        // Use AWS CLI or SDK commands here
                        sh '''
                        aws sts get-caller-identity --region ${AWS_REGION}
                        '''
                    }
                }
            }
        }
    }