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-rolewith 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
shblock. - The base principal needs
sts:AssumeRolepermission on the target role and a matching trust policy.
Related guides
How to Deploy a Static Site to S3 With JenkinsDeploy a built static site to an S3 bucket from a Jenkins Declarative Pipeline using aws s3 sync, then invali…
How to Deploy to Amazon ECS With JenkinsDeploy a new container image to an Amazon ECS service from a Jenkins Declarative Pipeline by registering a ta…