Skip to main content

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.

Automating macOS setup with Ansible Pull

· 2 min read

The problem​

I've been using macOS for three years and I'm on my fifth laptop replacement across two jobs. Moving to a new one is always a bit of a hassle, especially without a spare personal laptop :)

I'm not keen on restoring from Time Machine snapshots. I like treating my workstation more like a server: keep it as stateless as practical and configure it with IaC.

The setup​

I ended up with a simple setup:

  1. A local cron job runs ansible-pull -U https://github.com/kb play.yml.
  2. Ansible clones the repository and runs the playbook at the specified path. In my setup it applies to localhost.

Takeaways​

  • Keeping my workstation setup in IaC, including software, GUI apps, and config files, feels like a good investment.
  • It's convenient to apply IaC in a GitOps style, with configuration applied automatically to maintain the desired state. Here Ansible provides the automation without a full GitOps controller.

xonsh - python-powered shell

· 5 min read

img

Why? That's a recipe for a debate. In my case, xonsh helped me finish a tedious task at work faster than I could in Bash or Python alone.

Is that a good idea? Probably not as a general rule. AWS, for example, writes its EC2 bootstrap script in Bash, though I find it hard to read. For one-off jobs I think xonsh can be useful. I'd be careful about putting those scripts in Git or CI and leaving colleagues to debug them.

Example 1: a CLI to restart Kubernetes workloads​

#!/usr/bin/env xonsh
# PYTHON_ARGCOMPLETE_OK
import argparse
import argcomplete
from argcomplete.completers import ChoicesCompleter

import json
import yaml
import os

# save all kubernetes contextes
with open(os.environ["KUBECONFIG"]) as y: contexts = tuple([ctx["name"] for ctx in yaml.safe_load(y)["contexts"]])
# WARNING: terminal freezes during autocompletion of something like bellow
# contexts = $(kubectl config view | yq e '.contexts[].name' - | sort).strip().split)('\n')

example_text = "Example: xonsh restart-pods.xsh --context sandbox"
parser = argparse.ArgumentParser(description="Restart Argo CD workloads", epilog=example_text)
parser.add_argument('--context', required=True, help="Kubernetes contexts").completer=ChoicesCompleter((contexts))
parser.add_argument('-n', '--namespace', help="argocd namespace", default="argocd")
argcomplete.autocomplete(parser)
args = parser.parse_args()

k_all: str = $(kubectl --context @(args.context) -n @(args.namespace) get all --output json)
k_all: dict = json.loads(k_all)["items"]

for obj in k_all:
if obj["kind"] in ["Deployment", "StatefulSet"]:
kubectl --context @(args.context) --namespace @(args.namespace) \
rollout restart @(obj["kind"].lower()) @(obj["metadata"]["name"]) -o name

Run the script:

$ xonsh restart-cli.xsh --context sandbox
deployment.apps/argocd-applicationset-controller
deployment.apps/argocd-image-updater
deployment.apps/argocd-notifications-controller
deployment.apps/argocd-redis
deployment.apps/argocd-repo-server
deployment.apps/argocd-server
statefulset.apps/argocd-application-controller

Example 2: an API to restart Kubernetes workloads​

import uvicorn
from fastapi import FastAPI

import typing as t
import json

app = FastAPI()


@app.get("/restart-pods/{context}")
async def restart_pods(context: str, namespace: str = "argocd"):
"""
Restart Deployments and StatefulSets in the selected namespace using `kubectl rollout restart`.
"""
k_all: str = $(kubectl --context @(context) -n @(namespace) get all --output json)
k_all: dict = json.loads(k_all)["items"]

result = list()

for obj in k_all:
if obj["kind"] in ["Deployment", "StatefulSet"]:
restarted = $(kubectl --context @(context) --namespace @(namespace) \
rollout restart @(obj["kind"].lower()) @(obj["metadata"]["name"]) -o name).strip()
result.append(restarted)
return result


if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
# Start Uvicorn
xonsh api.xsh
INFO: Started server process [9467]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
# A successful request returns a response like this
INFO: 127.0.0.1:64893 - "GET /restart-pods/sandbox?namespace=argocd HTTP/1.1" 200 OK

# Send the request from another terminal
curl -X 'GET' \
'http://127.0.0.1:8000/restart-pods/sandbox?namespace=argocd' \
-H 'accept: application/json' | jq
[
"deployment.apps/argocd-applicationset-controller",
"deployment.apps/argocd-image-updater",
"deployment.apps/argocd-notifications-controller",
"deployment.apps/argocd-redis",
"deployment.apps/argocd-repo-server",
"deployment.apps/argocd-server",
"statefulset.apps/argocd-application-controller"
]

Example 3: Typer CLI with xonsh​

I wanted to see how quickly I could write and share scripts with xonsh, as an alternative to Warp workflows or Taskfile.

Let's recreate this workflow:

warp​

---

name: Terminate AWS EC2 by k8s Node name
command: |
ec2_id=$(kubectl --context {{ctx}} get nodes {{node}} \
-o jsonpath="{.spec.providerID}" \
| /usr/bin/grep -Eo "i-\w*")

echo "DEBUG: <node-name={{node}}>,<ec2_id=${ec2_id}>"

aws ec2 terminate-instances \
--profile {{awsProfile}} \
--region {{awsRegion}} \
--instance-ids ${ec2_id} \
| jq

tags:
- aws
- kubernetes
- k8s
- karma
description: Terminate AWS EC2 by k8s Node name
arguments:
- name: ctx
description: kubernetes context
default_value: ~
- name: node
description: kubernetes Node
default_value: ~
- name: awsProfile
description: aws named profile
default_value: ~
...

xsh​

def k8s_node_aws_instance_id(context: str, node: str):
"""
The input is the Kubernetes node name ip-10-51-38-27.eu-west-1.compute.internal
We need to find the AWS instance ID
The API returns a provider ID of aws:///eu-west-1b/i-086fd4feb458ecde3
Result: i-086fd4feb458ecde3
"""
provider_id = !(kubectl --context @(context) get node @(node) -o jsonpath="{.spec.providerID}")
provider_id = str(provider_id)
logging.debug(f"providerID {provider_id}")
ec2_id = provider_id.split('/')[-1].replace('"', '')
return ec2_id

# TODO: encapsulate arguments
@app.command(help=":ship: Terminate a node")
def k8s_terminate_node(
node: str = typer.Argument(None, help="kubernetes Node name"),
context: str = typer.Option(None, "--context", "-ctx", help="kubernetes context"),
profile: str = typer.Option("default", "--profile", "-p", help="aws named profile"),
region: str = typer.Option("eu-west-1", "--region", "-r", help="aws region"),
):
# Look up the node's instance ID
ec2_id = k8s_node_aws_instance_id(context, node)
print(f"node {node}, aws ec2 instance_id {ec2_id}")

# Drain the node and shut it down
kubectl --context @(context) drain @(node) --delete-local-data --ignore-daemonsets --force
aws ec2 terminate-instances --profile @(profile) --region eu-west-1 --instance-ids @(ec2_id) | jq


@app.command(help=":ship: Connect to a node")
def k8s_ssm_node(
node: str = typer.Argument(None, help="kubernetes Node name"),
context: str = typer.Option(None, "--context", "-ctx", help="kubernetes context"),
profile: str = typer.Option("default", "--profile", "-p", help="aws named profile"),
region: str = typer.Option("eu-west-1", "--region", "-r", help="aws region"),
):
# Look up the node's instance ID
ec2_id = k8s_node_aws_instance_id(context, node)
print(f"node {node}, aws ec2 instance_id {ec2_id}")

# Connect through SSM
aws ssm start-session --profile @(profile) --region @(region) --target @(ec2_id)

To import objects from .xsh files, add this to init.py:

from xonsh.main import setup
setup()
del setup

Result​

asciicast

I couldn't find any articles that helped with these examples.

Ansible as a Terraform provisioner

· 4 min read

Provisioning compute with IaC has two stages:

  • Bootstrapping provisions resources from a cloud provider on demand using Terraform.
  • Provisioning configures the resources you created, usually at the OS level.

From my platform engineering post.

Let's solve a simple problem: create a VM and install NGINX on it.

common​

The two examples share Terraform locals and an Ansible playbook.

locals {
// $ ssh-keygen -t ed25519 -f ~/.ssh/ansible -C ansible
ssh_keys = [
{
user = "ansible"
private_key_path = "~/.ssh/ansible"
public_key_path = "~/.ssh/ansible.pub"
},
]
// ansible alias
ssh = local.ssh_keys[0]

author = "ahorbach"
}

---

- name: Workshop aws,gcp,terraform,ansible
hosts: all
vars: {}

become: true
become_method: sudo

tasks:
- name: Ensure Nginx is at the latest version
apt:
name: nginx
state: latest
update_cache: true

- name: Make sure Nginx is running
systemd:
name: nginx
state: started

AWS​

1. provider​

Configure the provider:

provider "aws" {
region = "eu-west-1"
profile = var.aws_named_profile
}

2. data​

Use data sources to look up the default VPC, its subnet, and a recent Ubuntu AMI:

data "aws_vpc" "default" {
default = true
}

data "aws_subnet_ids" "default" {
vpc_id = data.aws_vpc.default.id
}

data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] // Canonical

filter {
name = "description"
values = ["Canonical, Ubuntu, 20.04 LTS, amd64 focal image build on*"]
}

filter {
name = "virtualization-type"
values = ["hvm"]
}
}

3. aws_security_group, aws_key_pair​

Create a security group. The server can send outbound traffic to the internet and accepts inbound connections on ports 22 (SSH) and 80 (HTTP).

resource "aws_security_group" "this" {
name = "${local.author}-sg"
description = "Allow ssh and web on port 80, and answer to everyone"
vpc_id = data.aws_vpc.default.id

ingress {
// ssh
protocol = "tcp"
from_port = 22
to_port = 22
cidr_blocks = ["0.0.0.0/0"]
}

ingress {
// web
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}

egress {
// Allow outgoing traffic from all ports
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}

Upload the public part of our SSH key to AWS:

resource "aws_key_pair" "this" {
key_name = "${local.author}-ansible"
public_key = file(local.ssh.public_key_path)
}

4. aws_instance​

resource "aws_instance" "this" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"

vpc_security_group_ids = [aws_security_group.this.id]
availability_zone = "eu-west-1b"

associate_public_ip_address = true
key_name = aws_key_pair.this.key_name

provisioner "remote-exec" { # (1)
script = <<EOF
#!/bin/bash

while [ ! -f /var/lib/cloud/instance/boot-finished ]; do
echo -e "\033[1;36mWaiting for cloud-init..."
sleep 1
done
EOF

connection {
type = "ssh"
host = self.public_ip
user = "ubuntu"
private_key = file(local.ssh.private_key_path)
}
}

provisioner "local-exec" { # (2)
command = <<EOF
ansible-playbook \
--inventory '${self.public_ip},' \
--private-key ${local.ssh.private_key_path} \
--user ubuntu \
./playbook.yml
EOF

}
tags = {
Name = "${local.author}-nginx"
}
}
  1. Wait until AWS says the VM is ready before running the Ansible playbook.
  2. Run the playbook from the machine that runs terraform apply.

GCP​

1. provider​

provider "google" {
project = var.gcp_project_id
region = "europe-central2"
zone = "europe-central2-b"
}

2. google_compute_firewall, google_os_login_ssh_public_key​

Create a service account and a firewall rule equivalent to the AWS security group:

data "google_client_openid_userinfo" "ahorbach" {}


resource "google_service_account" "this" {
account_id = "${var.gcp_project_id}-nginx"
}

resource "google_compute_firewall" "web" {
name = "web-access"
network = local.network

allow {
protocol = "tcp"
ports = ["80"]
}
source_ranges = ["0.0.0.0/0"]

target_service_accounts = [google_service_account.this.email]
}

Upload the public part of our SSH key to GCP:

resource "google_os_login_ssh_public_key" "this" {
project = var.gcp_project_id
user = data.google_client_openid_userinfo.ahorbach.email
key = file(local.ssh.public_key_path)
}

3. google_compute_instance​

Start the VM:

resource "google_compute_instance" "this" {
name = "${local.author}-nginx"
machine_type = "e2-micro"
zone = "europe-central2-b"

boot_disk {
initialize_params {
image = "ubuntu-2004-focal-v20230213"
}
}

network_interface {
network = local.network
access_config {}
}

service_account {
email = google_service_account.this.email
scopes = ["cloud-platform"]
}

// creater users and put public keys
metadata = {
ssh-keys = join("\n", [for key in local.ssh_keys : "${key.user}:${file(key.public_key_path)}"])
}

provisioner "remote-exec" {
inline = ["echo 'Waint until SSH is ready'"]

connection {
type = "ssh"
user = local.ssh.user
private_key = file(local.ssh.private_key_path)
host = self.network_interface.0.access_config.0.nat_ip
}
}

provisioner "local-exec" {
command = <<EOF
ansible-playbook \
--inventory '${self.network_interface.0.access_config.0.nat_ip},' \
--private-key ${local.ssh.private_key_path} \
--user ${local.ssh.user} \
./playbook.yml
EOF
}
}
  • You can configure VM operating systems across clouds using the same Ansible playbooks.
  • Other options include building an image with Packer and Ansible for reuse, or using pull-based configuration management such as ansible-pull.
  • The Ansible provisioner is equivalent to running ansible-playbook --inventory '34.118.12.194,' --private-key ansible --user ansbile playbook.yml locally after terraform apply.
  • Source code.

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 🔥

Helm vs Python validation

· 3 min read

My colleagues and I needed to generate Karpenter Provisioner manifests in a loop. The container runtime choice had significant consequences. If we left provisioner.spec.kubeletConfiguration.containerRuntime unset in a Provisioner paired with an AWSNodeTemplate, Karpenter would default to containerd (see the test).

We came up with these requirements:

  • If the Provisioner omits the CRI, pick our default, which was dockerd.
  • If the Provisioner specifies a CRI, use it.
  • Handle the case where the CRI is omitted but provisioner.spec.kubeletConfiguration has other settings.

Here's the validation code we ended up with:

helm​

# Kubelet
# If Provisioner.kubeletConfiguration is not empty
{{- if .kubeletConfiguration }}
kubeletConfiguration:
# If containerRuntime has been configured in Provisioner.kubeletConfiguration
{{- if hasKey .kubeletConfiguration "containerRuntime" -}}
{{- toYaml .kubeletConfiguration | nindent 4 }}
# ElseIf containerRuntime has not been configured in Provisioner.kubeletConfiguration
{{- else }}
# Pick default CRI from karpenter.default.kubeletConfiguration and add it to current .kubeletConfiguration
{{- $CRI := dict "containerRuntime" $.Values.karpenter.default.kubeletConfiguration.containerRuntime -}}
{{- $kubeletConfiguration := merge $CRI .kubeletConfiguration }}
{{- toYaml $kubeletConfiguration | nindent 4 }}
{{- end }}
# ElseIf Provisioner.kubeletConfiguration is empty
{{- else }}
kubeletConfiguration:
{{- toYaml $.Values.karpenter.default.kubeletConfiguration | nindent 4 }}
{{- end }}
Tests

Test cases:

    1. The Provisioner omits the CRI values.yml
karpenter:
payload:
ahorbach:
foo: bar

result:

spec:
# Kubelet
# If Provisioner.kubeletConfiguration is not empty
kubeletConfiguration:
containerRuntime: dockerd
    1. The Provisioner specifies the CRI

values.yml

karpenter:
payload:
ahorbach:
kubeletConfiguration:
bar: baz
containerRuntime: rocket

result:

spec:
# Kubelet
# If Provisioner.kubeletConfiguration is not empty
kubeletConfiguration:
# If containerRuntime has been configured in Provisioner.kubeletConfiguration
bar: baz
containerRuntime: rocket
# ElseIf containerRuntime has not been configured in Provisioner.kubeletConfiguration
# ElseIf Provisioner.kubeletConfiguration is empty
    1. The Provisioner omits the CRI but provides other configuration

values.yml

payload:
ahorbach:
kubeletConfiguration:
spam: eggs

result:

spec:
# Kubelet
# If Provisioner.kubeletConfiguration is not empty
kubeletConfiguration:
# If containerRuntime has been configured in Provisioner.kubeletConfiguration
# Pick default CRI from karpenter.default.kubeletConfiguration and add it to current .kubeletConfiguration
containerRuntime: dockerd
spam: eggs

python​

from pydantic import BaseModel, validator

DEFAULT_CRI = {"containerRuntime": "dockerd"}

class karpenterPayloadProvisioner(BaseModel):
name: str
kubelet_configuration: dict = DEFAULT_CRI

@validator('kubelet_configuration')
def kubelet_container_runtime(cls, v):
cri = v.get("containerRuntime")
# option two - Mutating
if cri not in ["dockerd", "containerd"]:
v.update(DEFAULT_CRI)
return v
Tests
import typing as t

import pytest

from karpenter import karpenterPayloadProvisioner

# without selected CRI in Provisioner
case1 = ("foo", {}, "dockerd")

# with containerd as a CRI for Provisioner

case2 = ("bar", {"kubeReserved": "testMe", "containerRuntime": "containerd"}, "containerd")

# with typo in CRI for Provisioner
case3 = ("baz", {"kubeReserved": "testMe", "containerRuntime": "qwerty"}, "dockerd")

test_cases = [
case1,
case2,
case3,
]

@pytest.mark.parametrize("name, kubelet_configuration, expected_CRI", test_cases)
def test_cri_provisioner(name: str, kubelet_configuration: t.Optional[dict], expected_CRI: str):

provisioner = karpenterPayloadProvisioner(name=name, kubelet_configuration=kubelet_configuration)
assert provisioner.kubelet_configuration["containerRuntime"] == expected_CRI

pytest .
=========================================================== test session starts ============================================================
platform darwin -- Python 3.10.0, pytest-6.2.5, py-1.11.0, pluggy-1.0.0
rootdir: /Users/a.horbach/repository-self/python-monorepo/pydantic-karpenter
plugins: django-4.4.0, cov-3.0.0
collected 3 items

test_karpenter.py ... [100%]

============================================================ 3 passed in 0.08s =============================================================

Terraformer - reverse Terraform

· One min read

What it does​

https://github.com/GoogleCloudPlatform/terraformer

Terraformer turns existing cloud resources into Terraform code. It's useful when you're learning AWS and Terraform and want to export resources you created in the console for a course. It's also handy when bringing existing infrastructure under IaC.

Usage​

info

Here's what worked for me. I wouldn't call it best practice.

Export the AWS API credentials.

export AWS_DEFAULT_PROFILE=my-profile # ~/.aws/credentials
export AWS_ACCESS_KEY_ID=id
export AWS_SECRET_ACCESS_KEY=key

You'll also need the Terraform aws provider:

terraform {
required_version = ">= 1.3.0"

required_providers {
aws = {
source = "hashicorp/aws"
version = "4.42.0"
}
}
}

Initialize the provider, then run Terraformer against the AWS resource you want to import.

terraform init # Initialize the provider in ./.terraform
terraformer import aws --resources=route53 --regions=us-east-1 --profile my-profile
terraformer import aws --resources=route53 --regions=us-east-1 --profile my-profile --filter="Type=route53_zone;Name=tags.Name;Value=my.example.com"

Kubed - secret sync between k8s clusters in different aws accounts

· 9 min read

Background and architecture​

1) aws account mc-legacy​

img

There's a legacy application running in an AWS account:

  1. Route 53 has a registered domain, <my-company>.io, and a matching hosted zone.
  2. The record for <my-service>.<my-company>.io points to <lb>.<my-company>.io.
  3. The load balancer sends traffic to an Auto Scaling group (ASG).
  4. The ASG manages the EC2 instances that run <my-service>.

2) aws account mc-project​

img

We decide to move the application to Kubernetes, giving each team its own AWS account and cluster:

  1. Create a Network Load Balancer in AWS named <lb-my-project>.
  2. Its target groups point to EC2 instances running the ingress controller pods.
  3. Once a request reaches the ingress controller, the Ingress routes it through a Kubernetes Service to the pods behind <my-service>.

3) combine​

img

The Route 53 record for <my-service>.<my-company>.io now points to the CNAME for <lb-my-project>. Traffic gets through, but TLS isn't terminated.

The <my-company>.io zone is too important to hand over to controllers like external-dns or cert-manager.

At the same time, there can be many project accounts and Kubernetes clusters, and I don't want to copy the TLS Secret by hand.

4) Concept​

img

  1. Create a dedicated management AWS account and Kubernetes cluster.
  2. Install the Secret containing the wildcard TLS certificate for *.<my-company>.io in that cluster.
  3. The Kubed controller syncs the Secret to the other Kubernetes clusters using annotations.
  4. The Ingress references that Secret and terminates TLS traffic.

Configuration​

info

In the examples below, the role for mc-mgmt is called kubed-master and the role for each mc-project-* is called kubed-follower.

AWS IAM RBAC​

info

In the diagram, mc-mgmt is CI and mc-project is Target.

img

Set up cross-account IAM roles and Kubernetes RBAC so Kubed in mc-mgmt can manage Secrets in clusters in other AWS accounts, such as mc-project.

mc-mgmt aka kubed-master​

locals {
kubed_followers_arns = [
for _, id in local.aws_accounts_map : "arn:aws:iam::${id}:role/kubed-follower"
]
}

module "iam_assumable_role_kubed_master" {
source = "terraform-aws-modules/iam/aws//modules/iam-assumable-role-with-oidc"
version = "4.2.0"

create_role = true
role_name = "kubed-master"

provider_url = replace(local.cluster_oidc_issuer_url, "https://", "")

role_policy_arns = [
aws_iam_policy.kubed_master.arn,
aws_iam_policy.kubed_eks.arn,
]

oidc_fully_qualified_subjects = [
"system:serviceaccount:kube-system:kubed"
]
}

data "aws_iam_policy_document" "kubed_master" {
statement {
sid = "kubedMaster"
effect = "Allow"
actions = [
"sts:AssumeRole",
]
resources = local.kubed_followers_arns
}
}

resource "aws_iam_policy" "kubed_master" {
name = "kubed-master"
policy = data.aws_iam_policy_document.kubed_master.json
}

data "aws_iam_policy_document" "kubed_eks" {
statement {
sid = "kubedEks"
effect = "Allow"
actions = [
"eks:DescribeCluster",
"eks:ListClusters"
]
resources = ["*"]
}
}

resource "aws_iam_policy" "kubed_eks" {
name = "kubed-eks"
policy = data.aws_iam_policy_document.kubed_eks.json
}

mc-project aka kubed-follower​

locals {
mc_mgmt_id = "<mc-mgmt_id>"
}

data "aws_iam_policy_document" "kubed_follower_assume" {
statement {
sid = "kubedFollowerAssume"
effect = "Allow"
principals {
identifiers = toset(["arn:aws:iam::${local.mc_mgmt_id}:role/kubed-master"])
type = "AWS"
}
actions = [
"sts:AssumeRole",
]
}
}

data "aws_iam_policy_document" "kubed_follower" {
statement {
sid = "kubedEks"
effect = "Allow"
actions = [
"eks:DescribeCluster",
"eks:ListClusters"
]
resources = ["*"]
}
}


resource "aws_iam_policy" "kubed_follower" {
name = "kubed-follower"
policy = data.aws_iam_policy_document.kubed_follower.json
}


resource "aws_iam_role" "kubed_follower" {
name = "kubed-follower"
description = "IAM role which allows kubed sync secrets from mc-mgmt to this account"
assume_role_policy = data.aws_iam_policy_document.kubed_follower_assume.json
managed_policy_arns = [aws_iam_policy.kubed_follower.arn]
}

ServiceAccount kubed​

Add this annotation to the kubed-master ServiceAccount:

annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::<mc-mgmt_id>:role/kubed-master

ConfgiMap aws-auth​

apiVersion: v1
kind: ConfigMap
metadata:
name: aws-auth
namespace: kube-system
data:
mapRoles: |
- "groups":
- "system:masters"
"rolearn": "arn:aws:iam::<mc-mgmt_id>:role/kubed-master"
"username": ""
...

Docker image​

The upstream image is based on scratch and contains just the Kubed binary. We also need AWS CLI tools to generate the kubeconfig.

FROM appscode/kubed:v0.13.2 as downloader

FROM alpine:3.17

COPY --from=downloader /kubed /usr/bin/kubed

RUN apk add --no-cache \
curl~=7.86 \
py3-pip~=22.3 \
&& pip install --no-cache-dir \
awscli~=1.27 \
&& curl -Lo aws-iam-authenticator https://github.com/kubernetes-sigs/aws-iam-authenticator/releases/download/v0.5.9/aws-iam-authenticator_0.5.9_linux_amd64 \
&& chmod +x aws-iam-authenticator \
&& mv aws-iam-authenticator /usr/bin/

RUN addgroup --gid 1950 app \
&& addgroup --gid 1000 app \
&& adduser \
--uid 1000 \
--home /home/app \
--shell /bin/ash \
--ingroup app \
--disabled-password \
app \
&& addgroup app app

USER 1000
WORKDIR /home/app

ENTRYPOINT ["/usr/bin/kubed"]

K8s controller​

The mc-mgmt cluster also runs a regular Kubed instance installed with the Helm chart. We reuse its Kubernetes RBAC configuration.

danger

This method can be destructive. A misconfigured kubed-master can reverse the direction of Secret synchronization between namespaces. I recommend running kubed-master in a dedicated cluster.

---
apiVersion: v1
kind: ConfigMap
metadata:
name: kubed-master-aws
namespace: kube-system
data:
credentials: |-
[mc-mgmt]
role_arn = arn:aws:iam::<mc-mgmt_id>:role/kubed-master
web_identity_token_file = /var/run/secrets/eks.amazonaws.com/serviceaccount/token
[mc-project]
role_arn = arn:aws:iam::<mc-project_id>:role/kubed-follower
source_profile = mc-mgmt
role_session_name = mc-project
generate-kubeconfig.sh: |-
#!/bin/bash
set -eux

aws eks update-kubeconfig --name mc-project-k8s --alias mc-project-k8s --profile mc-project

# NOTE: mc-mgmt-k8s should the last due to current-context
aws eks update-kubeconfig --name mc-mgmt-k8s --alias mc-mgmt-k8s --profile mc-mgmt

Synchronizing configuration​

---

apiVersion: v1
kind: ConfigMap
metadata:
name: cross-acc-sync-demo
namespace: prod
annotations:
kubed.appscode.com/sync-contexts: "mc-project-k8s"
data:
foo: bar
spam: eggs

Synchronization behavior​

info

Here, configuration means a ConfigMap or Secret.

  • Sync runs from the namespace named in the controller flags to a namespace with the same name in each follower cluster. Annotations and labels from the source aren't copied to the followers.
  • Restarting the controller pod or updating the source object's .data triggers sync. Deleting the object from a follower cluster doesn't automatically recreate it.
  • Deleting the source object in the master account deletes it from all followers.
  • If a follower runs its own Kubed instance to sync across namespaces, you can annotate the object manually and let that controller distribute it. Updating .data in the master syncs the Secret without overwriting that annotation.

Add the annotation in the follower cluster:

kubectl --context mc-project annotate cm cross-acc-sync-demo "kubed.appscode.com/sync=sync/kubed-master=true"

Label another namespace in the follower cluster so the local Kubed instance syncs the ConfigMap into it.

---

kind: Namespace
apiVersion: v1
metadata:
name: env-ahorbach
labels:
name: env-ahorbach
sync/kubed-master: "true"

Lens - build from source

· One min read

Background​

Lens 6 wouldn't start. I couldn't fix it quickly, so I decided to roll back to an earlier version.

DEBUG=true /Applications/Lens.app/Contents/MacOS/Lens

The debug logs showed errors, but I couldn't find anything helpful in the Lens GitHub issues.

Earlier releases weren't easy to download. One option was to build from source.

Building Lens​

$ git clone https://github.com/lensapp/lens.git
$ git checkout v5.5.4 # Last stable 5.x release
$ make build

This is where I ran into trouble, mostly around incompatible Node.js and package versions.

I used nvm to change Node.js versions and followed this macOS guide.

nvm ls-remote # List available Node.js versions
nvm install lts/fermium # node 15.x
nvm use lts/fermium # Select the Node.js version for this shell

Pinning the Node.js version was enough for me to build the .dmg package.