How to make k8s Pod (generated by Jenkins) use Service account IAM role to access AWS resources How to make k8s Pod (generated by Jenkins) use Service account IAM role to access AWS resources jenkins jenkins

How to make k8s Pod (generated by Jenkins) use Service account IAM role to access AWS resources


Jenkins podTemplate has serviceAccount option:https://github.com/jenkinsci/kubernetes-plugin#pod-and-container-template-configuration

  • Create an IAM role mapped to an EKS cluster
  • Create a ServiceAccount mapped to an IAM role
  • Pass ServiceAccount name to a podTemplate

Further debugging:

  1. Ensure the pod has correct service account name.
  2. Check if pod got AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE env vars (they are added automatically).
  3. Check if AWS SDK you use is above the minimal version: https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts-minimum-sdk.html
  4. Run aws sts get-caller-identity to see the role, don't waste time on running an actual job.


In the case of working with Jenkins slaves, one needs to customize the container images to use AWS CLI V2 instead of AWS CLI V1. I was running into errors related to authorization like the question poses; my client was using the cluster node roles instead of using the assumed web identity role of my service account attached to my Jenkins-pods for the slave containers.

Apparently V2 of the AWS CLI includes the web identity token file as part of the default credentials chain whereas V1 does not.

Here's a sample Dockerfile that pulls the latest AWS CLI version so this pattern works.

FROM jenkins/inbound-agent# run updates as rootUSER root# Create docker groupRUN addgroup docker# Update & Upgrade OSRUN apt-get updateRUN apt-get -y upgrade#install python3RUN apt-get -y install python3# add AWS Cli version 2 for web_identity_token filesRUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"RUN unzip awscliv2.zipRUN ./aws/install# Add MavenRUN apt-get -y install maven --no-install-recommends# Add dockerRUN curl -sSL https://get.docker.com/ | shRUN usermod -aG docker jenkins# Add docker composeRUN curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-composeRUN chmod +x /usr/local/bin/docker-compose# Delete cached files we don't need anymore:RUN apt-get cleanRUN rm -rf /var/lib/apt/lists/*# close root accessUSER jenkins

Further, I had to make sure my serviceaccount was created and attached to both the Jenkins master image and the jenkins slaves. This can be accomplished via Manage Jenkins -> Manage Nodes and Clouds -> Configure Clouds -> Pod Template Details.

Be sure to edit Namespace and Serviceaccount fields with the appropriate values.