code-snippets
Skill4 starsChanged 9 months agoMITView on GitHub
Common code snippets and patterns for DevOps automation scripts. Trigger: When writing automation scripts, utilities, or DevOps tooling.
In this repository5 other files it gives its agents.
- devops-notionSkill
- devops-prSkill
- github-actionsSkill
- kubernetes-helmSkill
- terraformSkill
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 5 are distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 593
Use colors for better readability
- Distinctive: line 596
Use readonly for constants
- Distinctive: line 602
Use try/except blocks
- Distinctive: line 604
Follow PEP 8 style guide
- Distinctive: line 611
Use commander for CLI args
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Purpose
You are a specialist in DevOps automation scripts. You provide commonly used code snippets for infrastructure automation, CI/CD, and DevOps workflows.
Bash Scripts
Script Template with Error Handling
#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
# Colors for output
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly NC='\033[0m' # No Color
# Script metadata
readonly SCRIPT_NAME="$(basename "${0}")"
readonly SCRIPT_DIR="$(cd "$(dirname "${0}")" && pwd)"
# Logging functions
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1" >&2
}
# Error handler
error_handler() {
log_error "Error occurred in ${SCRIPT_NAME} at line $1"
exit 1
}
trap 'error_handler ${LINENO}' ERR
# Usage function
usage() {
cat << EOF
Usage: ${SCRIPT_NAME} [OPTIONS]
Options:
-e, --environment ENV Environment (dev|staging|prod)
-v, --version VERSION Version to deploy
-h, --help Show this help message
Example:
${SCRIPT_NAME} --environment prod --version v1.2.3
EOF
exit 1
}
# Parse arguments
parse_args() {
while [[ $# -gt 0 ]]; do
case $1 in
-e|--environment)
ENVIRONMENT="$2"
shift 2
;;
-v|--version)
VERSION="$2"
shift 2
;;
-h|--help)
usage
;;
*)
log_error "Unknown option: $1"
usage
;;
esac
done
# Validate required arguments
if [[ -z "${ENVIRONMENT:-}" ]]; then
log_error "Environment is required"
usage
fi
if [[ -z "${VERSION:-}" ]]; then
log_error "Version is required"
usage
fi
}
# Main function
main() {
log_info "Starting deployment to ${ENVIRONMENT} with version ${VERSION}"
# Your logic here
log_info "Deployment completed successfully"
}
# Run main function
parse_args "$@"
mainAWS CLI Automation
#!/bin/bash
# Deploy to AWS ECS
deploy_to_ecs() {
local cluster="$1"
local service="$2"
local image="$3"
log_info "Updating ECS service ${service} in cluster ${cluster}"
# Get current task definition
local task_def=$(aws ecs describe-services \
--cluster "${cluster}" \
--services "${service}" \
--query 'services[0].taskDefinition' \
--output text)
# Get task definition JSON
local task_def_json=$(aws ecs describe-task-definition \
--task-definition "${task_def}" \
--query 'taskDefinition')
# Update image in task definition
local new_task_def=$(echo "${task_def_json}" | jq \
--arg IMAGE "${image}" \
'.containerDefinitions[0].image = $IMAGE |
del(.taskDefinitionArn, .revision, .status, .requiresAttributes, .compatibilities, .registeredAt, .registeredBy)')
# Register new task definition
local new_task_def_arn=$(aws ecs register-task-definition \
--cli-input-json "${new_task_def}" \
--query 'taskDefinition.taskDefinitionArn' \
--output text)
log_info "Registered new task definition: ${new_task_def_arn}"
# Update service
aws ecs update-service \
--cluster "${cluster}" \
--service "${service}" \
--task-definition "${new_task_def_arn}" \
--force-new-deployment
log_info "Service update initiated"
# Wait for deployment to complete
aws ecs wait services-stable \
--cluster "${cluster}" \
--services "${service}"
log_info "Deployment completed successfully"
}Azure CLI Automation
#!/bin/bash
# Deploy to Azure AKS
deploy_to_aks() {
local resource_group="$1"
local cluster_name="$2"
local namespace="$3"
local image="$4"
log_info "Deploying to AKS cluster ${cluster_name}"
# Login to Azure (if not already logged in)
if ! az account show &>/dev/null; then
log_info "Logging in to Azure..."
az login
fi
# Get AKS credentials
log_info "Getting AKS credentials..."
az aks get-credentials \
--resource-group "${resource_group}" \
--name "${cluster_name}" \
--overwrite-existing
# Deploy with Helm
log_info "Deploying with Helm..."
helm upgrade --install myapp ./helm/my-app \
--namespace "${namespace}" \
--create-namespace \
--set image.tag="${image}" \
--wait \
--timeout 10m
# Verify deployment
kubectl rollout status deployment/myapp -n "${namespace}"
log_info "Deployment completed successfully"
}Health Check Script
#!/bin/bash
# Health check for deployed service
check_health() {
local url="$1"
local max_attempts="${2:-30}"
local sleep_time="${3:-10}"
log_info "Checking health of ${url}"
for ((i=1; i<=max_attempts; i++)); do
log_info "Attempt ${i}/${max_attempts}"
if curl -sf "${url}/health" > /dev/null; then
log_info "Health check passed"
return 0
fi
log_warn "Health check failed, retrying in ${sleep_time}s..."
sleep "${sleep_time}"
done
log_error "Health check failed after ${max_attempts} attempts"
return 1
}Python Scripts
AWS SDK (Boto3) Automation
#!/usr/bin/env python3
import boto3
import logging
import sys
from typing import Dict, List
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class AWSDeployment:
def __init__(self, region: str = 'us-east-1'):
self.region = region
self.ecs_client = boto3.client('ecs', region_name=region)
self.ecr_client = boto3.client('ecr', region_name=region)
def get_latest_image(self, repository_name: str) -> str:
"""Get latest image from ECR repository"""
try:
response = self.ecr_client.describe_images(
repositoryName=repository_name,
maxResults=1,
filter={'tagStatus': 'TAGGED'}
)
image_tags = response['imageDetails'][0].get('imageTags', [])
if not image_tags:
raise ValueError(f"No tagged images found in {repository_name}")
latest_tag = image_tags[0]
image_uri = f"{response['imageDetails'][0]['registryId']}.dkr.ecr.{self.region}.amazonaws.com/{repository_name}:{latest_tag}"
logger.info(f"Latest image: {image_uri}")
return image_uri
except Exception as e:
logger.error(f"Failed to get latest image: {e}")
raise
def update_ecs_service(self, cluster: str, service: str, image: str) -> bool:
"""Update ECS service with new image"""
try:
# Get current task definition
service_desc = self.ecs_client.describe_services(
cluster=cluster,
services=[service]
)
if not service_desc['services']:
raise ValueError(f"Service {service} not found in cluster {cluster}")
task_def_arn = service_desc['services'][0]['taskDefinition']
# Get task definition
task_def = self.ecs_client.describe_task_definition(
taskDefinition=task_def_arn
)['taskDefinition']
# Update container image
task_def['containerDefinitions'][0]['image'] = image
# Remove unnecessary fields
for key in ['taskDefinitionArn', 'revision', 'status', 'requiresAttributes',
'compatibilities', 'registeredAt', 'registeredBy']:
task_def.pop(key, None)
# Register new task definition
new_task_def = self.ecs_client.register_task_definition(**task_def)
new_task_def_arn = new_task_def['taskDefinition']['taskDefinitionArn']
logger.info(f"Registered new task definition: {new_task_def_arn}")
# Update service
self.ecs_client.update_service(
cluster=cluster,
service=service,
taskDefinition=new_task_def_arn,
forceNewDeployment=True
)
logger.info(f"Updated service {service} with new task definition")
# Wait for service to be stable
waiter = self.ecs_client.get_waiter('services_stable')
logger.info("Waiting for service to stabilize...")
waiter.wait(
cluster=cluster,
services=[service],
WaiterConfig={'Delay': 15, 'MaxAttempts': 40}
)
logger.info("Service deployment completed successfully")
return True
except Exception as e:
logger.error(f"Failed to update ECS service: {e}")
raise
def main():
import argparse
parser = argparse.ArgumentParser(description='Deploy to AWS ECS')
parser.add_argument('--cluster', required=True, help='ECS cluster name')
parser.add_argument('--service', required=True, help='ECS service name')
parser.add_argument('--repository', required=True, help='ECR repository name')
parser.add_argument('--region', default='us-east-1', help='AWS region')
args = parser.parse_args()
try:
deployer = AWSDeployment(region=args.region)
image = deployer.get_latest_image(args.repository)
deployer.update_ecs_service(args.cluster, args.service, image)
logger.info("Deployment completed successfully")
sys.exit(0)
except Exception as e:
logger.error(f"Deployment failed: {e}")
sys.exit(1)
if __name__ == '__main__':
main()Azure SDK Automation
#!/usr/bin/env python3
from azure.identity import DefaultAzureCredential
from azure.mgmt.containerinstance import ContainerInstanceManagementClient
from azure.mgmt.containerregistry import ContainerRegistryManagementClient
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class AzureDeployment:
def __init__(self, subscription_id: str):
self.credential = DefaultAzureCredential()
self.subscription_id = subscription_id
self.aci_client = ContainerInstanceManagementClient(
self.credential,
self.subscription_id
)
self.acr_client = ContainerRegistryManagementClient(
self.credential,
self.subscription_id
)
def restart_container_group(self, resource_group: str, container_group_name: str):
"""Restart Azure Container Instance"""
try:
logger.info(f"Restarting container group {container_group_name}")
self.aci_client.container_groups.begin_restart(
resource_group,
container_group_name
).result()
logger.info("Container group restarted successfully")
except Exception as e:
logger.error(f"Failed to restart container group: {e}")
raise
def main():
import argparse
import os
parser = argparse.ArgumentParser(description='Azure Container Management')
parser.add_argument('--subscription-id',
default=os.getenv('AZURE_SUBSCRIPTION_ID'),
help='Azure subscription ID')
parser.add_argument('--resource-group', required=True,
help='Resource group name')
parser.add_argument('--container-group', required=True,
help='Container group name')
args = parser.parse_args()
deployer = AzureDeployment(args.subscription_id)
deployer.restart_container_group(args.resource_group, args.container_group)
if __name__ == '__main__':
main()Node.js Scripts
Kubernetes Automation
#!/usr/bin/env node
const k8s = require('@kubernetes/client-node');
const { program } = require('commander');
class K8sDeployer {
constructor() {
this.kc = new k8s.KubeConfig();
this.kc.loadFromDefault();
this.k8sApi = this.kc.makeApiClient(k8s.AppsV1Api);
this.coreApi = this.kc.makeApiClient(k8s.CoreV1Api);
}
async deployImage(namespace, deployment, image) {
try {
console.log(`Updating deployment ${deployment} in namespace ${namespace}`);
// Get current deployment
const { body: currentDeployment } = await this.k8sApi.readNamespacedDeployment(
deployment,
namespace
);
// Update image
currentDeployment.spec.template.spec.containers[0].image = image;
// Apply update
await this.k8sApi.replaceNamespacedDeployment(
deployment,
namespace,
currentDeployment
);
console.log('Deployment updated successfully');
// Wait for rollout
await this.waitForRollout(namespace, deployment);
console.log('Rollout completed successfully');
} catch (error) {
console.error('Deployment failed:', error.message);
throw error;
}
}
async waitForRollout(namespace, deployment, timeout = 600000) {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const { body } = await this.k8sApi.readNamespacedDeploymentStatus(
deployment,
namespace
);
const ready = body.status.readyReplicas || 0;
const desired = body.spec.replicas || 0;
console.log(`Ready: ${ready}/${desired}`);
if (ready === desired) {
return true;
}
await new Promise(resolve => setTimeout(resolve, 5000));
}
throw new Error('Rollout timeout exceeded');
}
async getPodLogs(namespace, labelSelector, tailLines = 100) {
const { body } = await this.coreApi.listNamespacedPod(
namespace,
undefined,
undefined,
undefined,
undefined,
labelSelector
);
if (body.items.length === 0) {
throw new Error('No pods found');
}
const podName = body.items[0].metadata.name;
const logs = await this.coreApi.readNamespacedPodLog(
podName,
namespace,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
tailLines
);
return logs.body;
}
}
async function main() {
program
.name('k8s-deploy')
.description('Deploy to Kubernetes')
.requiredOption('-n, --namespace <namespace>', 'Kubernetes namespace')
.requiredOption('-d, --deployment <deployment>', 'Deployment name')
.requiredOption('-i, --image <image>', 'Container image');
program.parse();
const options = program.opts();
const deployer = new K8sDeployer();
try {
await deployer.deployImage(
options.namespace,
options.deployment,
options.image
);
console.log('✅ Deployment completed successfully');
process.exit(0);
} catch (error) {
console.error('❌ Deployment failed:', error.message);
process.exit(1);
}
}
if (require.main === module) {
main();
}
module.exports = K8sDeployer;Best Practices
Shell Scripts
- Always use
set -euo pipefail - Implement proper error handling
- Use colors for better readability
- Include usage/help functions
- Validate input arguments
- Use readonly for constants
- Quote all variables
Python Scripts
- Use type hints
- Implement proper logging
- Use try/except blocks
- Create reusable classes
- Follow PEP 8 style guide
- Use virtual environments
- Pin dependencies
Node.js Scripts
- Use async/await
- Implement error handling
- Use commander for CLI args
- Follow ESLint rules
- Use environment variables
- Handle process signals
- Exit with proper codes
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

