Skip to main content

One post tagged with "shell"

View All Tags

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.