What's under the hood of this website
A short tour of the stack behind andrewhorbach.com: what it is built with and where it runs.

A short tour of the stack behind andrewhorbach.com: what it is built with and where it runs.

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
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
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.
I ended up with a simple setup:
ansible-pull -U https://github.com/kb play.yml.
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.
#!/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
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"
]
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:
---
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: ~
...
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
I couldn't find any articles that helped with these examples.
cd as a context manager.Provisioning compute with IaC has two stages:
From my platform engineering post.
Let's solve a simple problem: create a VM and install NGINX on it.
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
Configure the provider:
provider "aws" {
region = "eu-west-1"
profile = var.aws_named_profile
}
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"]
}
}
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)
}
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"
}
}
terraform apply.provider "google" {
project = var.gcp_project_id
region = "europe-central2"
zone = "europe-central2-b"
}
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)
}
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
}
}
ansible-pull.ansible-playbook --inventory '34.118.12.194,' --private-key ansible --user ansbile playbook.yml locally after terraform apply.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.
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:
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_user" "this" {
name = "s3-manager"
}
resource "aws_iam_user_policy_attachment" "this" {
user = aws_iam_user.this.name
policy_arn = aws_iam_policy.this.arn
}
---
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 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.
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
}
module "iam_assumable_role_s3_app" {
source = "terraform-aws-modules/iam/aws//modules/iam-assumable-role-with-oidc"
version = "4.2.0"
create_role = true
role_name = "s3-app"
provider_url = replace(module.eks_cluster.cluster_oidc_issuer_url, "https://", "")
role_policy_arns = [
aws_iam_policy.this.arn
]
// NOTE: Trust entry format for the ServiceAccount
// system:serviceaccount:<ServiceAccount.metadata.namespace>:<ServiceAccount.metadata.name>
oidc_fully_qualified_subjects = [
"system:serviceaccount:dev:s3-app",
]
}
Use this if the ServiceAccount name is dynamic.
oidc_subjects_with_wildcards = [
"system:serviceaccount:crossplane-system:aws-provider-*"
]
⚠️ Use either oidc_fully_qualified_subjects or oidc_subjects_with_wildcards.
---
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)
iam-assumable-role-with-oidc module---
apiVersion: apps/v1
kind: Deployment
metadata:
namespace: dev
...
...
spec:
...
template:
...
spec:
serviceAccountName: s3-app
containers:
- name: s3-app
...
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.
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:

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.
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
}
locals {
oidc = replace(module.eks_cluster.cluster_oidc_issuer_url, "https://", "")
}
resource "aws_iam_role" "this" {
name = "s3-app-A"
assume_role_policy = <<EOF
// Establish trust between the role in account A and the EKS ServiceAccount
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Principal":{
"Federated":"arn:aws:iam::<aws_account_id_A>:oidc-provider/${local.oidc}"
},
"Action":"sts:AssumeRoleWithWebIdentity",
"Condition":{
"StringEquals":{
"${local.oidc}:sub":"system:serviceaccount:dev:s3-app"
}
}
}
]
}
EOF
}
resource "aws_iam_role_policy_attachment" "this" {
role = aws_iam_role.this.name # (2)
policy_arn = aws_iam_policy.this.arn # (1)
}
---
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)
---
apiVersion: apps/v1
kind: Deployment
metadata:
namespace: dev
...
...
spec:
...
template:
...
spec:
serviceAccountName: s3-app
containers:
- name: s3-app
...
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" "this" {
name = "s3-app-B"
assume_role_policy = <<EOF
// Gotcha: The role in account B must trust the role in account A
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Principal":{
"AWS":"arn:aws:iam::<aws_account_id_A>:role/s3-app-A"
},
"Action":"sts:AssumeRole"
}
]
}
EOF
}
resource "aws_iam_role_policy_attachment" "this" {
role = aws_iam_role.this.name
policy_arn = aws_iam_policy.this.arn
}
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 🔥
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:
provisioner.spec.kubeletConfiguration has other settings.Here's the validation code we ended up with:
# 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 }}
Test cases:
karpenter:
payload:
ahorbach:
foo: bar
result:
spec:
# Kubelet
# If Provisioner.kubeletConfiguration is not empty
kubeletConfiguration:
containerRuntime: dockerd
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
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
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
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 =============================================================
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.
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"

There's a legacy application running in an AWS account:
<my-company>.io, and a matching hosted zone.<my-service>.<my-company>.io points to <lb>.<my-company>.io.<my-service>.
We decide to move the application to Kubernetes, giving each team its own AWS account and cluster:
<lb-my-project>.<my-service>.
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.

*.<my-company>.io in that cluster.In the examples below, the role for mc-mgmt is called kubed-master and the role for each mc-project-* is called kubed-follower.
In the diagram, mc-mgmt is CI and mc-project is Target.

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-masterlocals {
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
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam:::<mc-mgmt_id>:oidc-provider/oidc.eks.<aws_region>.amazonaws.com/id/<mc-mgmt_oidc>"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"oidc.eks.<aws_region>.amazonaws.com/id/<mc-mgmt_oidc>:sub": "system:serviceaccount:kube-system:kubed"
}
}
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "kubedMaster",
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": [
"arn:aws:iam::<mc-project_id>:role/kubed-follower"
]
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "kubedEks",
"Effect": "Allow",
"Action": [
"eks:ListClusters",
"eks:DescribeCluster"
],
"Resource": "*"
}
]
}
mc-project aka kubed-followerlocals {
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]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "kubedFollowerAssume",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam:::<mc-mgmt_id>:role/kubed-master"
},
"Action": "sts:AssumeRole"
}
]
}
{
"Statement": [
{
"Action": [
"eks:ListClusters",
"eks:DescribeCluster"
],
"Effect": "Allow",
"Resource": "*",
"Sid": "kubedEks"
}
],
"Version": "2012-10-17"
}
Add this annotation to the kubed-master ServiceAccount:
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::<mc-mgmt_id>:role/kubed-master
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": ""
...
apiVersion: v1
kind: ConfigMap
metadata:
name: aws-auth
namespace: kube-system
data:
mapRoles: |
- "groups":
- "system:masters"
"rolearn": "arn:aws:iam::<mc-project_id>:role/kubed-follower"
"username": ""
...
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"]
The mc-mgmt cluster also runs a regular Kubed instance installed with the Helm chart. We reuse its Kubernetes RBAC configuration.
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
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: kubed-master
namespace: kube-system
labels:
app.kubernetes.io/name: kubed-master
app.kubernetes.io/instance: kubed-master
app.kubernetes.io/version: "v0.13.2"
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: kubed-master
app.kubernetes.io/instance: kubed-master
template:
metadata:
labels:
app.kubernetes.io/name: kubed-master
app.kubernetes.io/instance: kubed-master
spec:
serviceAccountName: kubed
# NOTE: kubeconfig-generator
initContainers:
- name: kubeconfig-generator
image: docker.io/my-company/kubed:v0.13.2
volumeMounts:
- name: kubeconfig
mountPath: /srv/kubed
- name: aws-config
mountPath: /home/app/.aws
- name: kubed-master-aws
mountPath: /home/app/scripts
command:
- sh
- -c
- |
mkdir -p /home/app/.aws &&
cp /home/app/scripts/credentials /home/app/.aws &&
sh /home/app/scripts/generate-kubeconfig.sh &&
cp /home/app/.kube/config /srv/kubed/kubeconfig
containers:
- name: kubed-master
image: docker.io/my-company/kubed:v0.13.2
args:
- run
- --v=3
- --secure-port=8443
- --audit-log-path=-
- --tls-cert-file=/var/serving-cert/tls.crt
- --tls-private-key-file=/var/serving-cert/tls.key
- --use-kubeapiserver-fqdn-for-aks=true
- --enable-analytics=false
- --cluster-name=mc-mgmt
- --kubeconfig-file=/srv/kubed/kubeconfig
- --config-source-namespace=prod
ports:
- containerPort: 8443
resources: {}
volumeMounts:
- name: kubeconfig
mountPath: /srv/kubed
- name: aws-config
mountPath: /home/app/.aws
- name: scratch
mountPath: /tmp
- name: serving-cert
mountPath: /var/serving-cert
volumes:
# NOTE: we'd like to generate kubeconfig during initContainer
- name: kubeconfig
emptyDir: {}
# secret:
# secretName: kubed # NOTE: contains data.kubeconfig
- name: aws-config
emptyDir: {}
- name: kubed-master-aws
configMap:
name: kubed-master-aws
defaultMode: 0550
- name: scratch
emptyDir: {}
- name: serving-cert
secret:
defaultMode: 420
secretName: kubed-apiserver-cert
securityContext:
fsGroup: 1000
---
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
Here, configuration means a ConfigMap or Secret.
.data triggers sync. Deleting the object from a follower cluster doesn't automatically recreate it..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 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.
$ 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.