AWS CDK Asset Kubectl v20 Layer
The `aws-cdk-asset-kubectl-v20` library provides an AWS CDK construct for a Lambda Layer that contains the `kubectl` (v1.20) and `aws-iam-authenticator` (v0.5.2) binaries. This enables AWS Lambda functions to interact with Kubernetes clusters. It is designed for AWS CDK v2 applications and is actively maintained by cdklabs.
Warnings
- breaking This package is specifically for AWS CDK v2. If you are using AWS CDK v1, you should use the older `aws-cdk-asset-kubectl` package (without the `vXX` suffix), which is not compatible with CDK v2.
- gotcha This layer provides `kubectl v1.20` and `aws-iam-authenticator v0.5.2` ONLY. If your EKS cluster is running a significantly different Kubernetes version, you might encounter compatibility issues. Always try to match your `kubectl` client version with your cluster's server version.
- gotcha This specific `aws-cdk-asset-kubectl-v20` layer does NOT include the `helm` binary. Many users expect `kubectl` layers to also contain `helm`. If you need `helm` in your Lambda function, you must use a different layer such as `aws-cdk-asset-kubectl-helm-v20` (or a higher version depending on your `kubectl` requirements).
- gotcha The layer is compiled for the `x86_64` architecture. If your Lambda function is configured to use the `ARM64` architecture, this layer will not be compatible.
Install
-
pip install aws-cdk-asset-kubectl-v20
Imports
- KubectlV20Layer
from aws_cdk_asset_kubectl_v20 import KubectlV20Layer
Quickstart
import os
from aws_cdk import App, Stack
from aws_cdk.aws_lambda import Runtime, Function, Code
from aws_cdk_asset_kubectl_v20 import KubectlV20Layer
class MyKubectlStack(Stack):
def __init__(self, scope, id, **kwargs):
super().__init__(scope, id, **kwargs)
# Instantiate the Kubectl v1.20 layer
kubectl_layer = KubectlV20Layer(self, 'KubectlLayer')
# Example Lambda function using the layer
# Replace 'my_handler' with your actual handler code
# and ensure the runtime is compatible.
Function(self, 'MyKubectlFunction',
runtime=Runtime.PYTHON_3_9, # Use a compatible Python runtime
handler='index.handler',
code=Code.from_inline(
'import os\nimport subprocess\n\ndef handler(event, context):\n # Kubectl is available in /opt/kubectl\n kubectl_path = os.path.join(os.sep, 'opt', 'kubectl')\n try:\n result = subprocess.run([kubectl_path, 'version', '--client'], capture_output=True, text=True, check=True)\n print(f"Kubectl client version: {result.stdout}")\n return {'statusCode': 200, 'body': result.stdout}\n except subprocess.CalledProcessError as e:\n print(f"Error executing kubectl: {e.stderr}")\n return {'statusCode': 500, 'body': e.stderr}\n'
),
layers=[kubectl_layer]
)
app = App()
MyKubectlStack(app, "MyKubectlStackExample")
app.synth()