Skip to main content

3 posts tagged with "kubernetes"

View All Tags

An asynchronous Kubernetes client for Python

· 2 min read

The problem​

Running the same kubectl command against many clusters in a sequential loop takes a long time. For example:

for ctx in $(kubectl config view | yq '.contexts.[].name');
do echo $ctx;
kubectl --context $ctx get cm aws-auth -n kube-system -o yaml | yq e '.data.mapUsers' - | yq -;
done

The solution​

Use an asynchronous Kubernetes client in Python:

pip3 install kubernetes_asyncio

Let's define a class that launches the tasks and waits for them to finish:

import asyncio
from kubernetes_asyncio import client, config
from kubernetes_asyncio.client.api_client import ApiClient

import typing as t


class k8sAsyncTask:
def __init__(self, contexts: list, task: t.Callable):
self._ctxs = contexts
self._task = task

async def _task_runner(self, ctx):
try:
# Load the cluster configuration
await config.load_kube_config(context=ctx)

# use the context manager to close http sessions automatically
async with ApiClient() as api:
result = await self._task(api)
return ctx, result

except Exception as e:
# Handle errors as needed
print(f"Error in cluster {ctx}: {str(e)}")
return ctx, None

async def tasks_results(self):
tasks = []

for ctx in self._ctxs:
task = asyncio.create_task(self._task_runner(ctx))
tasks.append(task)

# Wait for all tasks to finish
completed_tasks = await asyncio.gather(*tasks)
# Turn the lists of results into dictionaries
zipped = dict(zip(self._ctxs, completed_tasks))
result = {k: zipped[k][1] for k in zipped}

return result

Define a task that reads the ConfigMap containing the AWS users:

import yaml


async def k8s_get_aws_auth(api):
v1 = client.CoreV1Api(api)
result = await v1.read_namespaced_config_map(name="aws-auth", namespace="kube-system")
users = yaml.safe_load(result.data["mapUsers"])
users_groups = [{"username": user["username"], "group": user["groups"]} for user in users]
return users_groups

Start the tasks and wait for the results:

CLUSTERS = ["dev", "prod"]


async def main():
k = k8sAsyncTask(CLUSTERS, k8s_get_aws_auth)
r = await k.tasks_results()
return r


if __name__ == "__main__":
r = asyncio.run(main())
print(r)

Done

Takeaway​

  • With many clusters, running ad hoc tasks concurrently can save time.

IRSA: accessing the AWS API from an EKS pod

· 6 min read

Suppose an application running in an EKS pod needs access to a private S3 bucket in the same AWS account.

Here are some ways to do it.

IAM user​

This option lets you debug the application locally.

The application calls the AWS API through an SDK. Pass the client the aws_access_key_id and aws_secret_access_key for an IAM user with access to the resource.

Configure the AWS IAM resources as follows:

AWS configuration​

resource "aws_iam_policy" "this" {
name = "s3-app"
policy = <<EOF
{
"Version":"2012-10-17",
"Statement":[
{
"Sid":"",
"Effect":"Allow",
"Action": "s3:*",
"Resource":[
"arn:aws:s3:::${aws_s3_bucket.this.bucket}",
"arn:aws:s3:::${aws_s3_bucket.this.bucket}/*"
]
}
]
}
EOF
}

k8s configuration​

---

apiVersion: apps/v1
kind: Deployment
...
spec:
...
template:
...
spec:
containers:
- name: s3-app
...
env:
- name: AWS_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: s3-app
key: aws_access_key_id
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: s3-app
key: aws_secret_access_key

IRSA​

IRSA stands for IAM Roles for Service Accounts. It establishes trust between an AWS IAM role and a Kubernetes ServiceAccount through the EKS cluster's OIDC provider.

Attach the same IAM policy to the role that you attached to the user in the previous example. Containers in a pod using that ServiceAccount can then obtain the credentials they need.

AWS configuration​

Configure IAM as follows:

resource "aws_iam_policy" "this" {
name = "s3-app"
policy = <<EOF
{
"Version":"2012-10-17",
"Statement":[
{
"Sid":"",
"Effect":"Allow",
"Action": "s3:*",
"Resource":[
"arn:aws:s3:::${aws_s3_bucket.this.bucket}",
"arn:aws:s3:::${aws_s3_bucket.this.bucket}/*"
]
}
]
}
EOF
}

k8s configuration​

---

apiVersion: v1
kind: ServiceAccount
metadata:
name: s3-app
namespace: dev
annotations:
eks.amazonaws.com/role-arn: 'arn:aws:iam::<aws_account_id>:role/s3-app' # (1)
  1. ARN of the IAM role created by the iam-assumable-role-with-oidc module

Verification​

Open a shell in the pod and look for these environment variables:

env | grep AWS
AWS_DEFAULT_REGION=<aws_region>
AWS_REGION=<aws_region>
AWS_ROLE_ARN=arn:aws:iam::<aws_account_id>:role/s3-app
AWS_WEB_IDENTITY_TOKEN_FILE=/var/run/secrets/eks.amazonaws.com/serviceaccount/token

Decode the token at /var/run/secrets/eks.amazonaws.com/serviceaccount/token on https://jwt.io/ to see these claims:

{
"aud": [
"sts.amazonaws.com"
],
"exp": 1673637993,
"iat": 1673551593,
"iss": "https://oidc.eks.<aws_region>.amazonaws.com/id/<HEX_HASH>",
"kubernetes.io": {
"namespace": "test",
"pod": {
"name": "s3-app-<replicaSet>-<random-hash>",
"uid": "47a2e254-d0d3-44bc-acdc-ef8f07a9f63e"
},
"serviceaccount": {
"name": "s3-app",
"uid": "91bb19bc-dab8-4c72-9718-eac7adbc4b59"
}
},
"nbf": 1673551593,
"sub": "system:serviceaccount:dev:s3-app"
}

Check access to the bucket:

aws s3 ls --recursive s3://bucket-s3-app
2021-12-14 15:07:52 47134393 app/my-cool.stuff
...

The Amazon EKS pod identity webhook sets this up.

Cross account irsa​

Now suppose the application runs in an EKS pod in AWS account A and needs access to a private S3 bucket in AWS account B.

The diagram shows the CI account as A and the target account as B:

img

warning

In most cases, I'd try to avoid designing a system where a pod in account A has to call the AWS API for a resource in account B.

AWS account A​

AWS configuration​

resource "aws_iam_policy" "this" {
name = "s3-app"
policy = <<EOF
// This policy allows assuming the role in account B
{
"Version":"2012-10-17",
"Statement":[
{
"Action":"sts:AssumeRole",
"Resource":"arn:aws:iam::<aws_account_id_B>:role/s3-app-B",
"Effect":"Allow",
"Sid":""
}
]
}
EOF
}

k8s configuration​

---

apiVersion: v1
kind: ServiceAccount
metadata:
name: s3-app
namespace: dev
annotations:
eks.amazonaws.com/role-arn: 'arn:aws:iam::<aws_account_id_A>:role/s3-app-A' # (1)
  1. ARN of the IAM role that trusts this ServiceAccount and can assume the role in account B

AWS account B​

resource "aws_iam_policy" "this" {
name = "s3-app"
policy = <<EOF
{
"Version":"2012-10-17",
"Statement":[
{
"Sid":"",
"Effect":"Allow",
"Action": "s3:*",
"Resource":[
"arn:aws:s3:::${aws_s3_bucket.this.bucket}",
"arn:aws:s3:::${aws_s3_bucket.this.bucket}/*"
]
}
]
}
EOF
}
resource "aws_iam_role_policy_attachment" "this" {
role = aws_iam_role.this.name
policy_arn = aws_iam_policy.this.arn
}

Verification​

Open a shell in the pod and look for the same environment variables:

# env
env | grep AWS
AWS_DEFAULT_REGION=<aws_region>
AWS_REGION=<aws_region>
AWS_ROLE_ARN=arn:aws:iam::<aws_account_id_A>:role/s3-app-A
AWS_WEB_IDENTITY_TOKEN_FILE=/var/run/secrets/eks.amazonaws.com/serviceaccount/token

The JWT has the same claims as before.

Trying to access the S3 bucket returns an error:

aws s3 ls --recursive s3://bucket-s3-app
An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied

Add this configuration:

cat <<EOF >>~/.aws/config
[profile A]
role_arn = arn:aws:iam::<aws_account_id_A>:role/s3-app-A
web_identity_token_file = /var/run/secrets/eks.amazonaws.com/serviceaccount/token
[profile B]
role_arn = arn:aws:iam::<aws_account_id_B>:role/s3-app-B
source_profile = A
role_session_name = xactarget
EOF

Try again with the named profile:

aws s3 ls --recursive s3://bucket-s3-app --profile B
2021-12-14 15:07:52 47134393 app/my-cool.stuff
...

Done 🔥

Platform Engineering

· 3 min read

I came across Puppet's 2020 State of DevOps report and noticed how closely it mapped to questions I ask candidates. I've been helping with hiring lately.

We ask a deliberately broad question. The wording varies, but it usually comes down to this:

note

How would you build a highly available Kubernetes cluster on bare metal or in a public cloud, with enough capacity for heavy workloads and room to scale across development teams? Walk us through your reasoning and what you'd do in practice, starting from the very first step.

We want to deliver a platform at the push of a button. That takes IaC and a few other pieces. I'd break the work into three steps that fit together well enough to make deployment a roughly one-button operation:

  1. compute bootstrapping provisions the physical servers or VMs, networks, and other resources that will host the OS and Kubernetes. In most cases I'd use Terraform with the AWS, GCP, VMware, or OpenStack provider.

  2. provisioning configures the OS and installs a highly available Kubernetes cluster on that compute using configuration management. Managed Kubernetes in a public cloud can handle this step for you.

  3. cluster configuration adds the pieces a bare cluster needs to be useful, including public ingress, metrics and logs, and secret storage and delivery. There are two ways to install those components:

    • CiOps stores the infrastructure application definitions in Git. A pipeline runner with cluster access applies the manifests or installs the charts. Kubernetes is declarative, but the operation itself is imperative and may fail to be idempotent.
    • GitOps adds a controller that compares the running cluster with the manifests or Helm charts in Git. It reports configuration drift and can correct it automatically when self-healing is enabled.

Deployment on AWS with GitOps​

Terraform provisions the AWS infrastructure and creates an Amazon EKS cluster. EKS supplies the managed Kubernetes control plane, so there is no separate step to install it. Once the cluster is up, bootstrap Argo CD inside it. Argo CD pulls the desired state from Git and syncs platform components into Kubernetes; Git doesn't push changes to the cluster.

Takeaway: At the time, this looked like the most promising way to build Kubernetes infrastructure and worth exploring in more depth.

Links