In the following exam, you’re gonna implement a logical autoscaler software that pulls scaling configurations and scales relevant K8S deployments replicas.
The autoscaler can be written in any language (preferred Python)
The autoscaler will pull the scaling configurations with REST API:
url: http://wscdevopsexam.eastus.azurecontainer.io
path: /autoscale
method: GET
The scaling configuration is a list of deployments and the target replicas for each deployment.
Based on the configurations, the autoscaler will scale the deployment’s replicas
All the deployments are in “wsc” namespace
Bonus: Create a Dockerfile to pack your software
Bonus: Create a README.md file
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a comprehensive implementation of the logical autoscaler software in Python, as per your request. This solution includes:
1. Autoscaler Python Script (autoscaler.py)
This script uses the requests library to fetch scaling configurations from the provided API and the kubernetes library to interact with the Kubernetes (K8S) cluster for scaling deployments.
python
import requests
from kubernetes import client, config
import json
# Function to load Kubernetes configuration
def load_kubernetes_config():
try:
# Load local kubeconfig
config.load_kube_config()
except config.ConfigException:
# If local config fails, try in-cluster config (for pod execution)
print("Using in-cluster config")
config.load_incluster_config()
# Function to scale deployment
def scale_deployment(namespace, deployment_name, replicas):
load_kubernetes_config()
apps_api = client.AppsV1Api()
try:
# Patch the deployment scale
api_response = apps_api.patch_namespaced_deployment_scale(
name=deployment_name,
namespace=namespace,
body={"spec": {"replicas": replicas}}
)
print(f"Deployment {deployment_name} scaled to {replicas} replicas")
except client.ApiException as e:
# Handle Kubernetes API exceptions
print(f"Exception when scaling {deployment_name}: {e}")
# Fetch scaling configurations from API
def fetch_scaling_configurations(url):
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for HTTP errors
return response.json()
except requests.exceptions.RequestException as err:
# Handle request exceptions (e.g., network issues, invalid URL)
print(f"Error fetching configurations: {err}")
return []
# Validate and apply scaling configurations
def apply_scaling_configurations(namespace, configurations):
for config in configurations:
# Validate required fields
if 'deployment' not in config or 'targetReplicas' not in config:
print(f"Invalid configuration: {config}. Skipping...")
continue
deployment_name = config['deployment']
target_replicas = config['targetReplicas']
# Validate replica count
if not isinstance(target_replicas, int) or target_replicas < 0:
print(f"Invalid replica count for {deployment_name}. Skipping...")
continue
print(f"Scaling {deployment_name} to {target_replicas} replicas...")
scale_deployment(namespace, deployment_name, target_replicas)
# Main execution
if __name__ == "__main__":
api_url = "http://wscdevopsexam.eastus.azurecontainer.io/autoscale"
namespace = "wsc"
configurations = fetch_scaling_configurations(api_url)
apply_scaling_configurations(namespace, configurations)
2. Dockerfile
To containerize the autoscaler, create a Dockerfile in the same directory as autoscaler.py:
dockerfile
# Use an official lightweight Python image
FROM python:3.9-slim
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set work directory
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy project
COPY . .
# Make command to run on container start
CMD ["python", "autoscaler.py"]
3. requirements.txt
Create a requirements.txt file in the same directory, listing the dependencies:
code
requests
kubernetes
4. README.md
markdown
# Kubernetes Autoscaler
A Python-based autoscaler that fetches scaling configurations via REST API and scales Kubernetes deployments accordingly.
## Prerequisites
- Python 3.9+
- `requests` and `kubernetes` libraries
- Access to the target Kubernetes cluster
- REST API for scaling configurations (`http://wscdevopsexam.eastus.azurecontainer.io/autoscale`)
## Usage
### Local Execution
1. Clone the repository.
2. Install dependencies: `pip install -r requirements.txt`
3. Ensure your Kubernetes configuration is set up (e.g., `~/.kube/config`).
4. Run the autoscaler: `python autoscaler.py`
### Docker Container
1. Build the Docker image: `docker build -t k8s-autoscaler .`
2. Run the Docker container: `docker run k8s-autoscaler`
## Configuration
- **API URL**: Currently hardcoded to `http://wscdevopsexam.eastus.azurecontainer.io/autoscale`. Modify `api_url` in `autoscaler.py` as needed.
- **Kubernetes Namespace**: Set to `"wsc"` in `autoscaler.py`. Adjust the `namespace` variable if necessary.
- **Kubernetes Configuration**: Ensure your `~/.kube/config` is properly set up for local execution. For in-cluster execution, the pod needs appropriate permissions and a service account configured.
## Troubleshooting
- **API Connectivity Issues**: Verify the API URL and network connectivity.
- **Kubernetes Errors**: Check cluster access permissions and the status of target deployments.
- **Invalid Configurations**: Ensure all configurations contain `deployment` and `targetReplicas` with valid values.
Note: Ensure you have the necessary permissions and configurations set up to interact with your Kubernetes cluster, whether running the script locally or within a Docker container. Additionally, validate the API response structure to match the expected format.