Skip to content
Latchkey

How to Deploy to AWS With an Assumed Role in Jenkins

Call sts assume-role inside the deploy stage and export the temporary keys so the AWS CLI runs with that role.

Bind a base AWS credential, run aws sts assume-role to get short-lived keys, then export AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN for the deploy commands.

Steps

  • Store a base AWS access key/secret as Jenkins credentials.
  • Run aws sts assume-role with the target role ARN and a session name.
  • Export the returned temporary keys and session token, then run your deploy command.

Pipeline

Jenkinsfile
pipeline {
  agent any
  stages {
    stage('Deploy') {
      steps {
        withCredentials([usernamePassword(credentialsId: 'aws-base',
            usernameVariable: 'AWS_ACCESS_KEY_ID',
            passwordVariable: 'AWS_SECRET_ACCESS_KEY')]) {
          sh '''
            CREDS=$(aws sts assume-role \
              --role-arn arn:aws:iam::123456789012:role/deployer \
              --role-session-name jenkins-$BUILD_NUMBER \
              --query 'Credentials' --output json)
            export AWS_ACCESS_KEY_ID=$(echo "$CREDS" | jq -r .AccessKeyId)
            export AWS_SECRET_ACCESS_KEY=$(echo "$CREDS" | jq -r .SecretAccessKey)
            export AWS_SESSION_TOKEN=$(echo "$CREDS" | jq -r .SessionToken)
            aws lambda update-function-code --function-name api --zip-file fileb://build.zip
          '''
        }
      }
    }
  }
}

Gotchas

  • Assumed-role credentials are temporary; keep all AWS commands inside the same sh block.
  • The base principal needs sts:AssumeRole permission on the target role and a matching trust policy.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →