AWS CDK Asset Kubectl v20 Layer

2.1.4 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to add the `KubectlV20Layer` to an AWS Lambda function within an AWS CDK stack. The example Lambda function simply runs `kubectl version --client` to confirm the binary's presence and version. Remember to adjust the Lambda runtime for compatibility with your function code and the layer.

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()

view raw JSON →