DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Production-Ready Kubernetes Service Checklist
  • KIAM vs AWS IAM Roles for Service Accounts (IRSA)
  • Streamline Microservices Development With Dapr and Amazon EKS
  • Container Checkpointing in Kubernetes With a Custom API

Trending

  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  • Start Coding With Google Cloud Workstations
  • Segmentation Violation and How Rust Helps Overcome It
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. How to Use AWS IAM Role on AWS EKS PODs

How to Use AWS IAM Role on AWS EKS PODs

A native-AWS way to attach an IAM role into the Kubernetes POD, without third-party software, reducing latency and improving your EKS security.

By 
Matheus Lozano user avatar
Matheus Lozano
·
Apr. 05, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
27.8K Views

Join the DZone community and get the full member experience.

Join For Free

How It Works

It’s possible to attach an IAM role in a Kubernetes POD without using third-party software, such as kube2iam and kiam. This is thanks to the integration between AWS IAM and Kubernetes ServiceAccount, following the approach of IAM Roles for Service Accounts (IRSA).

Attach IAM Role to the Kubernetes POD
Using an IAM Role in a Kubernetes POD

Benefits

There are quite a few benefits of using IRSA with Kubernetes PODs.

  • Granular restriction (per cluster, per namespace, etc.).
    It’s also possible to not use it.
  • More flexible than the other tools.
  • One less point of failure (maybe a few less).
  • Lesser resource consumption.
  • More pods per node.
  • Latency may reduce by ~50ms.
    Especially for the first request.
  • Prevent issues with caching the credentials.
    This software takes a few minutes to update its cache.
  • Better auditing.
    Instead of checking the logs of kube2iam/kiam pods, you can check AWS CloudTrails.
  • Easier to set up.
  • AWS provides full support.

Pre-requirements

There are a few pre-requirements that you’ll need to attempt in order to use the IAM role in a POD.

  • An IAM OpenID Connect provider pointing to the AWS EKS OpenID Connect provider URL.
  • AWS EKS cluster 1.13 or above.
  • A trust relationship between your IAM Role and the OpenID Provider.

Costs

There is no extra cost.


How to Setup

There a few ways to set up, I’ll share how to do it via eksctl and terraform.

I didn’t add eksctl and terraform as pre-requirements, since you can do it via AWS Console too.

Both tools eksctl or terraform, will set up the exact same thing (except for the IAM Policy that isn't created via eksctl). These tools will do:

  • Create an AWS OpenID Connect provider.
  • Link the OIDC provider to the EKS OIDC URL.
  • Create an IAM Role.
  • Create an IAM Policy (only via terraform).
  • Attach the IAM Policy to the IAM Role.
  • Set up the Trust Relationship between the IAM Role and the OpenID Connect provider.
  • Create a Kubernetes ServiceAccount.


Setting up With eksctl

Using eksctl may be easy for the first time, but it can be trick/hard to automate.

You can follow these scripts/steps:

01-verify_oidc.sh - here we'll just get the EKS OIDC endpoint and check if there is an OpenID Providers created. There is no change in this step.

Shell
 




xxxxxxxxxx
1
23


 
1
## First of all, check if you already have an OpenID Connect
2
### List your EKS cluster OIDC URL
3
aws eks describe-cluster --name <CLUSTER_NAME> --query "cluster.identity.oidc.issuer"
4

          
5
#### Output
6
https://oidc.eks.<REGION>.amazonaws.com/id/<OIDC_ID>
7

          
8
### List your 
9
aws iam list-open-id-connect-providers
10

          
11
#### The output shouldn't contain any provider with the same <OIDC_ID> listed in the previous command
12
{
13
    "OpenIDConnectProviderList": []
14
}
15
#### OR
16
{
17
    "OpenIDConnectProviderList": [
18
        {
19
            "Arn": "arn:aws:iam::<ACCOUNT_ID>:oidc-provider/oidc.eks.<REGION>.amazonaws.com/id/<ANOTHER_OIDC_ID>"
20
        }
21
    ]
22
}



02-setting_up.sh - On this step, we'll create an OpenID provider (in case you need it) and then create a Kubernetes Service Account in your EKS Cluster.

Shell
 




xxxxxxxxxx
1
17


 
1
## Create this only if you don't have an OpenID Connect provider for the cluster
2
eksctl utils associate-iam-oidc-provider --cluster <CLUSTER_NAME> --approve
3

          
4

          
5
## Now it's time to create the AWS IAM Role (<ROLE_NAME>), a Kubernetes ServiceAccount
6
##   and attach an pre-existing IAM Policy (<POLICY_NAME>) into the new role (<ROLE_NAME>)
7

          
8
## The IAM role will be created by the eksctl and attach the pre-existing policy (<POLICY_NAME>) into it.
9

          
10
eksctl create iamserviceaccount \
11
  --cluster=<CLUSTER_NAME> \
12
  --role-name=<ROLE_NAME> \
13
  --namespace=<NAMESPACE> \
14
  --name=<SERVICE_ACCOUNT_NAME> \
15
  --attach-policy-arn=<POLICY_NAME> \
16
  --approve



03-deploy_pod.sh - Last but not least, here is an example of using the IAM Role in a POD by attaching a Service Account.

Shell
 




xxxxxxxxxx
1
16


 
1
## In the spec, we'll provide the <SERVICE_ACCOUNT_NAME> created previously.
2

          
3
kubectl apply -f- <<EOF
4
apiVersion: v1
5
kind: Pod
6
metadata:
7
  name: amazonlinux
8
  namespace: <NAMESPACE>
9
spec:
10
  serviceAccountName: <SERVICE_ACCOUNT_NAME>
11
  containers:
12
    - name: amazonlinux
13
      image: amazonlinux
14
      command: [ "sh", "-c", "sleep 8h" ]
15
EOF



You can check the 04-cleaning.sh in case you want to clean up; just be careful with it.

Setting With Terraform

I created a GitHub repository: LozanoMatheus/eks-oidc. It’s straightforward to adapt to the real scenario.

The main.tf: Here we'll define the TF code to create an OpenID Connect, an IAM Policy, an IAM Role, and a Kubernetes Service Account (plus attach the IAM role to the K8s Service Account):

Plain Text
 




xxxxxxxxxx
1
55


 
1
####################
2
## OpenID Connect ##
3
####################
4
data "tls_certificate" "main" {
5
  url = data.terraform_remote_state.eks_cluster.outputs.eks_oidc
6
}
7

           
8
resource "aws_iam_openid_connect_provider" "main" {
9
  url = data.terraform_remote_state.eks_cluster.outputs.eks_oidc
10

           
11
  client_id_list = [
12
    "sts.amazonaws.com",
13
  ]
14

           
15
  thumbprint_list = [
16
    data.tls_certificate.main.certificates.0.sha1_fingerprint
17
  ]
18
}
19

           
20
################
21
## IAM Policy ##
22
################
23
resource "aws_iam_policy" "main" {
24
  name        = var.policy_name
25
  path        = "/"
26
  description = "Allow AWS EKS PODs to get a specify S3 Object"
27

           
28
  policy = file("${path.module}/policies/s3_policy.json")
29
}
30

           
31
resource "aws_iam_role" "main" {
32
  name                  = var.role_name
33
  path                  = "/"
34
  assume_role_policy    = data.template_file.role_trust_relationship.rendered
35
  force_detach_policies = false
36
}
37

           
38
resource "aws_iam_role_policy_attachment" "main" {
39
  role       = aws_iam_role.main.name
40
  policy_arn = aws_iam_policy.main.arn
41
}
42

           
43
############
44
## K8s SA ##
45
############
46
resource "kubernetes_service_account" "main" {
47
  metadata {
48
    name      = var.role_name
49
    namespace = "matheus"
50
    annotations = {
51
      "eks.amazonaws.com/role-arn" = aws_iam_role.main.arn
52
    }
53
  }
54
  automount_service_account_token = true
55
}



The providers.tf: This code is to configure the TF providers:

Plain Text
 




xxxxxxxxxx
1
22


 
1
provider "aws" {
2
  region = var.aws_region
3
}
4

           
5
terraform {
6
  required_version = "~> 0.12.4"
7
  required_providers {
8
    aws = "~> 2"
9
    tls = "~> 3"
10
  }
11
  backend "s3" {
12
  }
13
}
14

           
15
provider "kubernetes" {
16
  host                   = data.terraform_remote_state.eks_cluster.outputs.endpoint                     ## aws_eks_cluster.main.endpoint
17
  cluster_ca_certificate = base64decode(data.terraform_remote_state.eks_cluster.outputs.ca_cert_base64) ## aws_eks_cluster.main.certificate_authority[0].data
18
  token                  = data.aws_eks_cluster_auth.cluster.token
19
  load_config_file       = false
20
  version                = "~> 1.9"
21
}



The data.tf: This will get the state of your EKS cluster (in case you create it in another TF), get the EKS Cluster ID, and configure the IAM Policy (to allow you to use this policy inside of the EKS Cluster):

Plain Text
 




xxxxxxxxxx
1
24


 
1
#################
2
## EKS Cluster ##
3
#################
4
data "terraform_remote_state" "eks_cluster" {
5
  # ...
6
}
7

           
8
data "aws_eks_cluster_auth" "cluster" {
9
  name = element(concat(data.terraform_remote_state.eks_cluster.outputs.*.id, list("")), 0) ## aws_eks_cluster.main.id
10
}
11

           
12
##################
13
## IAM Policies ##
14
##################
15
data "template_file" "role_trust_relationship" {
16
  template = file("${path.module}/policies/role_trust_relationship.json.tmpl")
17
  vars = {
18
    oidc_arn      = aws_iam_openid_connect_provider.main.arn
19
    oidc_url      = aws_iam_openid_connect_provider.main.url
20
    k8s_namespace = var.k8s_namespace
21
    role_name     = var.role_name
22
  }
23
}



The vars.tf: This is the TF file that contains the variables used by the TF. It will define the AWS Region (eu-west-1), set the Kubernetes namespace that the IAM Policy can be used, the IAM Role name, and the IAM Policy name.

Plain Text
 




x
16


 
1
variable "aws_region" {
2
  type    = string
3
  default = "eu-west-1"
4
}
5

           
6
variable "k8s_namespace" {
7
  default = "tips-and-tricks"
8
}
9

           
10
variable "role_name" {
11
  default = "s3-get-object-iam-role001"
12
}
13

           
14
variable "policy_name" {
15
  default = "s3-get-object-iam-policy001"
16
}



The policies/s3_policy.json: This is the policy that will allow the interaction between the K8s POD and AWS APIs. In this case, I'm allowing the POD to get objects from a specific S3 bucket in a specific path:

Plain Text
 




xxxxxxxxxx
1
12


 
1
{
2
    "Version": "2012-10-17",
3
    "Statement": [{
4
        "Effect": "Allow",
5
        "Action": [
6
            "s3:GetObject"
7
        ],
8
        "Resource": [
9
            "arn:aws:s3:::aws-s3-example/file001"
10
        ]
11
    }]
12
}



The policies/role_trust_relationship.json.tmpl: This is a template file and it will allow the POD to use the IAM role:

Plain Text
 




xxxxxxxxxx
1
16


 
1
{
2
    "Version": "2012-10-17",
3
    "Statement": [{
4
        "Effect": "Allow",
5
        "Principal": {
6
            "Federated": "${oidc_arn}"
7
        },
8
        "Action": "sts:AssumeRoleWithWebIdentity",
9
        "Condition": {
10
            "StringEquals": {
11
                "${oidc_url}:sub": "system:serviceaccount:${k8s_namespace}:${role_name}",
12
                "${oidc_url}:aud": "sts.amazonaws.com"
13
            }
14
        }
15
    }]
16
}



Now you can create all the resources:

Shell
 




x


 
1
## Planning
2
terraform plan
3

           
4
## Deploying
5
terraform apply



AWS pods Kubernetes Plain text

Published at DZone with permission of Matheus Lozano. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Production-Ready Kubernetes Service Checklist
  • KIAM vs AWS IAM Roles for Service Accounts (IRSA)
  • Streamline Microservices Development With Dapr and Amazon EKS
  • Container Checkpointing in Kubernetes With a Custom API

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!