Skip to main content

πŸ“š Automation Examples

πŸ“‹ Table of Contents​

  1. Overview
  2. RabbitMQ Automation
  3. Kafka/Strimzi Automation
  4. FastAPI Automation
  5. k6 Load Testing Automation
  6. External Source Code Automation
  7. Image Base Automation
  8. Best Practices
  9. Additional Resources

Overview​

This chapter provides real-world examples of service automation and relationships generated by Stacktic. These examples demonstrate how Stacktic automates configurations based on best-practice patterns, creating the necessary resources, documentation, and relationships to support full-stack demands.

Important Notes​

⚠️ Scope Notice: These are examples only, not complete automation implementations.
The full automation is generated into your target repository's documentation with all configurations, secrets, and operational procedures.

What Gets Automated​

ServiceAutomated ComponentsKey Features
RabbitMQExchanges, queues, bindings, usersMessage flow configuration
KafkaTopics, bridges, connectors, sinksEvent streaming setup
FastAPIRoutes, endpoints, documentationAPI gateway integration
k6Test scripts, CRDs, pluginsPerformance testing
External SourceGit integration, CI/CD, deploymentsAutomated builds from source
Image BasePre-built deployments, init containersDirect image deployment

πŸ‡ RabbitMQ Automation​

Component Architecture​

RabbitMQ automation demonstrates how Stacktic handles message queue patterns with sub-components and relationships.

Sub-Component Creation​

You can create sub-components such as:

  • Exchanges - Message routing logic
  • Queues - Message storage
  • Bindings - Flow definitions between exchanges and queues
alt text

Relationship Configuration​

The link between an exchange and a queue represents the binding configuration:

alt text

Generated Configuration​

Secret Configuration Example​

The automation generates a complete RabbitMQ configuration stored as a Kubernetes secret:

cat k8s/deploy/base/rabbitmq/secret/definitions.json
{
"vhosts": [
{ "name": "/" }
],
"users": [
{
"name": "user",
"password_hash": "EJBKv6SgKs6UFaLurzia3tPUIxQ/d4NIfwXG0OUWD2ayoCRd",
"tags": "management"
},
{
"name": "admin",
"password_hash": "C5pNaWoy+Fb7WeHsIgtP/6DvaimpRJkdo4BQQYlO+yluv0b/",
"tags": "administrator"
}
],
"permissions": [
{ "user": "user", "vhost": "/", "configure": ".*", "write": ".*", "read": ".*" },
{ "user": "admin", "vhost": "/", "configure": ".*", "write": ".*", "read": ".*" }
],
"parameters": [],
"global_parameters": [
{ "name": "cluster_name", "value": "rabbit@my-rabbit" }
],
"policies": [],
"bindings": [{
"source": "api-system",
"destination": "systems",
"destination_type": "queue",
"vhost": "/",
"routing_key": "#"
}],
"queues": [{
"name": "systems",
"vhost": "/",
"durable": true,
"auto_delete": false,
"arguments": {}
}],
"exchanges": [{
"name": "api-system",
"type": "topic",
"vhost": "/",
"durable": true,
"auto_delete": false,
"internal": false,
"arguments": {}
}]
}

Additional Configurations​

Configuration TypeLocationPurpose
VersioningComponent levelRabbitMQ version management
ResourcesComponent attributesCPU/Memory allocation
SecurityComponent & linksAuthentication, TLS, network policies
MonitoringAuto-generatedPrometheus metrics, Grafana dashboards

πŸ“ Note: Additional configuration related to versioning, resources, and security exists within the RabbitMQ component itself.


πŸ¦„ Kafka Automation​

Advanced Event Streaming​

Kafka Strimzi is a more complex component but follows similar automation principles.

Sub-Component Types​

alt text
Sub-ComponentPurposeAutomation Features
TopicsEvent streamsPartitions, replication, retention
BridgesHTTP integrationREST API exposure
ConnectorsExternal systemsDatabase sinks, source connectors
UsersAccess controlACLs, authentication

Integration Capabilities​

API Gateway Integration​

  • Bridge connects to API gateway
  • Integrates with OIDC via Keycloak
  • Automatic authentication setup

Database Integration​

  • Topic sub-components connect to databases for sink operations
  • Automated Kafka Connect configuration
  • End-to-end setup including connectors and secrets

Example Resources​

Demo Repository​

Explore a sample implementation (not full automation):
πŸ”— Basic Strimzi Setup

Connectors Example​

Review automated connector configurations:
πŸ”— Kafka Connectors

Automated Components​

ComponentGenerated Assets
Kafka ClusterStatefulSets, services, config
Kafka ConnectDeployment, connector definitions
Schema RegistryDeployment, schemas
MonitoringJMX exporters, dashboards

⚑ FastAPI Automation​

API Development Acceleration​

FastAPI automation streamlines API configuration and documentation through intelligent relationship management.

Automatic Configuration​

When you connect FastAPI to a queue or database, Stacktic automatically:

ActionGenerated Assets
Adds dependenciesPython packages, requirements.txt
Configures routesAPI endpoints, middleware
Creates servicesBusiness logic templates
Generates endpointsGET, POST, DELETE, PUT methods
Documents APIsOpenAPI/Swagger specs
alt text

API Gateway Integration​

Connect FastAPI to APISIX API Gateway for production-ready deployment:

  • Automatic route registration
  • Load balancing configuration
  • Health check setup
  • Rate limiting rules

Validation & Testing​

Validate the configuration by testing the FastAPI endpoints and viewing generated documentation:

alt text

sub_component for custom API​

Stacktic acts as version control for your stack.
You can:

  • Create your own API on the existing FastAPI service in the main branch.
  • Modify an existing API.
  • Or use sub-components to define APIs.

When you add a sub-component, Stacktic automatically generates the API code inside the existing structure.
You don't need to manually touch mainβ€”just add the route and basic service definition.

βœ… Advantages of Using Sub-Component APIs​

  • Saved as part of Stacktic's version control, making it easy to track changes.
  • Minimizes direct code editingβ€”no need to manage dependencies or modify main; simply provide the API definition.
  • Gives Stacktic additional metadata about your logic, enabling smarter automation and insights.
alt text

Security Best Practices​

πŸ”’ Security Recommendation:
We recommend external authentication instead of relying solely on FastAPI's built-in API key system.

OIDC Integration with APISIX & Keycloak​

Use APISIX and Keycloak for enterprise-grade authentication:

alt text

Benefits:

  • βœ… Centralized authentication
  • βœ… OIDC/OAuth2 support
  • βœ… Single Sign-On (SSO)
  • βœ… Token-based security
  • βœ… Role-based access control

Configuration Details​

ConfigurationLevelDescription
VersioningComponentPython version, FastAPI version
Admin CredentialsComponentInitial admin setup
ResourcesComponentCPU/Memory limits
Build ImageLinkRequired when linking APIs

πŸ’‘ Build Note: Build image is required when linking APIs to ensure dependency compatibility.


πŸ“ˆ k6 Load Testing Automation​

Performance Testing Framework​

To quickly assess your stack's performance and scaling configuration, link k6 to any service component.

alt text

Automated Test Generation​

When k6 is linked to services, Stacktic automatically:

ActionGenerated Output
Creates test filesk6 JavaScript test scripts
Builds CRDsKubernetes custom resources
Configures pluginsDatabase, queue, API plugins
Sets up reportingMetrics collection, dashboards

Example k6 Structure​

tree k8s/deploy/base/k6
k8s/deploy/base/k6
β”œβ”€β”€ k6.yaml # k6 operator configuration
β”œβ”€β”€ kustomization.yaml # Kustomize manifest
β”œβ”€β”€ mongodb_collector.yaml # MongoDB metrics collector
β”œβ”€β”€ namespace.yaml # k6 namespace
β”œβ”€β”€ secret
β”‚ β”œβ”€β”€ cloud.env # Cloud configuration
β”‚ └── registry.json # Registry credentials
β”œβ”€β”€ test-run.yaml # Test execution definitions
└── tests
β”œβ”€β”€ cnpg.js # PostgreSQL tests
β”œβ”€β”€ kafka.js # Kafka tests
β”œβ”€β”€ mongo.js # MongoDB tests
β”œβ”€β”€ psql.js # PostgreSQL tests
└── rabbitmq.js # RabbitMQ tests

Test Execution Configuration​

Sample test-run.yaml​

apiVersion: k6.io/v1alpha1
kind: TestRun
metadata:
name: mongo-test
namespace: k6-operator-system
spec:
parallelism: 1
paused: "false"
quiet: "false"
script:
configMap:
name: k6-test-scripts
file: mongo.js
runner:
image: index.docker.io/asauer/k6:0.0.1-SNAPSHOT
imagePullSecrets:
- name: registry-credential
envFrom:
- secretRef:
name: k6-cm
resources:
limits:
cpu: 1000m
memory: 1Gi
requests:
cpu: 250m
memory: 256Mi
---
apiVersion: k6.io/v1alpha1
kind: TestRun
metadata:
name: rabbitmq-test
namespace: k6-operator-system
spec:
parallelism: 1
paused: "false"
quiet: "false"
script:
configMap:
name: k6-test-scripts
file: rabbitmq.js
runner:
image: index.docker.io/asauer/k6:0.0.1-SNAPSHOT
imagePullSecrets:
- name: registry-credential
envFrom:
- secretRef:
name: k6-cm
resources:
limits:
cpu: 1000m
memory: 1Gi
requests:
cpu: 250m
memory: 256Mi

Loading your full stack with single JSON​

Add Sub_componenets Endpoints

alt text

enter your json URL to the "Load Test Json" attribute. for example:

[
{
"url": "https://prod.stack.source-lab.io/",
"insecure": true
},
{
"url": "https://dev.stack.source-lab.io/",
"insecure": true,
"method": "POST",
"payload": {"key": "value"}
},
{
"url": "https://secure-endpoint.com",
"insecure": false
}
]

Execute the tests (k8s/deploy/base/k6/test-run.yaml)

kubectl logs endpoints-test-1-4p7ff  -n k6-operator-system

/\ Grafana /β€Ύβ€Ύ/
/\ / \ |\ __ / /
/ \/ \ | |/ / / β€Ύβ€Ύ\
/ \ | ( | (β€Ύ) |
/ __________ \ |_|\_\ \_____/

execution: local
script: /test/generic-test.js
output: -

scenarios: (100.00%) 1 scenario, 1 max VUs, 10m30s max duration (incl. graceful stop):
* default: 1 iterations for each of 1 VUs (maxDuration: 10m0s, gracefulStop: 30s)



β–ˆ TOTAL RESULTS

checks_total.......: 1 6.352779/s
checks_succeeded...: 100.00% 1 out of 1
checks_failed......: 0.00% 0 out of 1

βœ“ status OK

HTTP
http_req_duration..............: avg=26.3ms min=26.3ms med=26.3ms max=26.3ms p(90)=26.3ms p(95)=26.3ms
{ expected_response:true }...: avg=26.3ms min=26.3ms med=26.3ms max=26.3ms p(90)=26.3ms p(95)=26.3ms
http_req_failed................: 0.00% 0 out of 1
http_reqs......................: 1 6.352779/s

EXECUTION
iteration_duration.............: avg=157.29ms min=157.29ms med=157.29ms max=157.29ms p(90)=157.29ms p(95)=157.29ms
iterations.....................: 1 6.352779/s

NETWORK
data_received..................: 3.7 kB 24 kB/s
data_sent......................: 1.7 kB 11 kB/s

Performance Testing Benefits​

FeatureBenefit
Automated test creationTests generated from topology
One-time image buildReusable across all tests
Integrated reportingResults in Grafana dashboards
Scaling validationVerify autoscaling configurations

πŸ“Š Pro Tip: You only need to build the k6 image onceβ€”test definitions are referenced directly in the deployment through ConfigMaps.


πŸ”§ External Source Code Automation​

Export Code to automate CI & CD​

External Source Code automation enables ** integration of existing codebases** with automated build and deployment pipelines.

Component Configuration​

When creating an External Source Code component, Stacktic automatically:

ActionGenerated Assets
Configures Git integrationGit credentials, branch management
Sets up build pipelineKaniko jobs, Dockerfile processing
Creates deploymentsKubernetes manifests, services
Manages secretsRegistry credentials, environment variables
Implements securityRBAC, service accounts, security contexts

Quick setup​

Configuration Tips: Define your Git Repository

Configmap: make sure to add ENV needed for the container code to come up

Docker_file_path: default is "/". if you move Dockerfiel , please update the path

Git_folder: same as above. build expect root sturcture where Dockerfile is in the root , src folder,etc...

UID/GID: make sure the UID/GID match the Dockerfile

alt text

Deployment Tips

Rarget port: should be identical to the Dockerfile port

Pvc mount path: if PVC enabled make sure it fit your code path

mount file folder: if you want to add from deployment level files to the container and mount it to PVC

configMapGenerator:
- name: staging-static-files
namespace: staging
files:
- files/test_file.text
options:
disableNameSuffixHash: true

- name: staging-startup
namespace: staging
files:
- files/startup.sh
options:
disableNameSuffixHash: true

alt text

Kaniko Build Process​

The automation generates a complete CI using Kaniko or buildkit for containerless builds:

alt text
k8s/build/base/stage/buildkit.yaml
or
k8s/build/base/stage/kaniko.yaml

Configuration Options​

ConfigurationPurposeAutomation Impact
Git OwnerRepository ownerDetermines Git URL construction
ProjectRepository nameSets build context
BranchTarget branchControls source version
Git FolderSubdirectory pathSets context sub-path
DockerfileCustom Dockerfile pathOptional build customization
VersionImage tagDeployment version control
RegistryContainer registryBuild destination
NamespaceKubernetes namespaceDeployment location

Security Features​

Pod Security Standards​

When security context is enabled, the deployment automatically implements:

spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000 # Configurable user ID
runAsGroup: 1000 # Configurable group ID
seccompProfile:
type: RuntimeDefault
hostNetwork: false
hostPID: false
hostIPC: false
containers:
- securityContext:
allowPrivilegeEscalation: false
privileged: false
readOnlyRootFilesystem: true
capabilities:
drop: [ALL]

Supply Chain Security​

When signature validation (sig) is enabled:

  • Cosign integration for image signing
  • Signature verification jobs
  • RBAC policies for validation
  • Key management through Kubernetes secrets
  • Automated validation on deployment

Advanced Features​

FeatureConfigurationGenerated Components
Auto-scalinghpa: trueHorizontalPodAutoscaler resources
Persistent storagepvc: truePersistentVolumeClaim manifests
MonitoringPrometheus integrationServiceMonitor resources
Image updatesimageupdater_update_enable: trueAutomatic version tracking
Static filesfiles_mount_pathConfigMap with mounted files
Health checksprobes: trueLiveness/Readiness probe patches
IngressKong integrationIngress rules and routes

Resource Management​

Flexible resource configuration with defaults:

resources:
requests:
cpu: "1000m"
memory: "512Mi"
limits:
cpu: "2000m"
memory: "1024Mi"

Volume Management​

Volume TypeUse CaseConfiguration
PVCPersistent datapvc_name, mount_path
EmptyDirTemporary storage/tmp, writable directories
ConfigMapStatic filesRead-only file mounts
SecretsSensitive dataEnvironment variables

Build Process Options​

Build FeatureDescriptionConfiguration
SonarQubeCode quality analysisAutomated scanning
Multi-stage buildsOptimized imagesDockerfile support
Build cachingFaster buildsLayer caching
Custom base imagesCorporate standardsRegistry configuration

🐳 Image Base Automation​

Pre-Built Image Deployment​

Image Base automation provides streamlined deployment of existing container images without requiring source code access.

Component Architecture​

Image Base components support deployment of any containerized application with automated configuration:

ComponentAutomated Features
Init ContainersStartup scripts, initialization logic
Main ContainerApplication deployment
Startup ScriptsCustom initialization via ConfigMap
Security PoliciesPod and container security contexts
Service AccountsRBAC and permissions

Startup Automation​

Init Container Configuration​

The automation includes sophisticated initialization capabilities:

initContainers:
- name: startup
image: application-image:version
command: ["/bin/sh", "-c"]
args: ["/startup/startup.sh"]
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 200m
memory: 256Mi
envFrom:
- secretRef:
name: component-external-source-secrets
volumeMounts:
- mountPath: /startup
name: startup-scripts
readOnly: true
- mountPath: /tmp
name: tmp-volume

Configuration Management​

Startup Script Integration​

Automatically mounts custom startup scripts via ConfigMap:

configMapGenerator:
- name: component-startup
namespace: namespace
files:
- files/startup.sh
options:
disableNameSuffixHash: true

Image Management Features​

FeatureConfigurationBenefit
Direct image deploymentImage URL/tagNo build required
Version controlversion attributeConsistent deployments
Registry authenticationPull secretsPrivate registry support
Update automationimageupdater_update_enableAutomatic version updates
Multi-registry supportRegistry configurationFlexibility in image sources

Resource Allocation​

Flexible resource configuration with separate init container limits:

# Init Container Resources
initContainers:
- resources:
requests: {cpu: 100m, memory: 128Mi}
limits: {cpu: 200m, memory: 256Mi}

# Main Container Resources
containers:
- resources:
requests:
cpu: "{{ cpu_request }}"
memory: "{{ mem_request }}"
limits:
cpu: "{{ cpu_limit }}"
memory: "{{ mem_limit }}"

Security Implementation​

Multi-Level Security​

Both pod-level and container-level security contexts:

# Pod Level Security (when pod_level_security: true)
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000 # Configurable
runAsGroup: 1000 # Configurable
seccompProfile:
type: RuntimeDefault
hostNetwork: false
hostPID: false
hostIPC: false

# Container Level Security (when securityContext: true)
containers:
- securityContext:
allowPrivilegeEscalation: false
privileged: false
readOnlyRootFilesystem: true
runAsNonRoot: true
capabilities:
drop: [ALL]

Deployment Patterns​

PatternImplementationUse Case
Init + MainStartup container + appDatabase migrations, config setup
Sidecar ReadyMultiple container supportLogging, monitoring agents
StatefulSet CompatiblePVC integrationDatabases, stateful services
Job PatternOne-time executionBatch processing, migrations
DaemonSet ReadyNode-level deploymentsSystem agents, monitoring

Monitoring & Observability​

When Prometheus is configured:

  • Automatic ServiceMonitor creation
  • Metrics endpoint configuration
  • Namespace-aware monitoring
  • Standard Kubernetes labels
  • Custom metrics path support

Advanced Configurations​

ConfigurationPurposeGenerated Resources
Affinity RulesPod distributionAnti-affinity policies
Service TypesNetwork exposureClusterIP, NodePort, LoadBalancer
Ingress IntegrationExternal accessKong ingress rules
Cosign ValidationImage verificationSignature check jobs
Image Pull SecretsPrivate registriesDocker config secrets
Service AccountRBAC permissionsRoles and bindings

Comparison: External Source vs Image Base​

AspectExternal Source CodeImage Base
Build ProcessKaniko from sourcePre-built images
Startup LogicIn DockerfileInit containers
FlexibilityFull source controlImage-level control
SpeedBuild + deployDeploy only
Use CaseCustom applicationsThird-party/pre-built apps
Git IntegrationRequiredNot needed
CI/CD PipelineFull automationDeployment only
Resource UsageBuild resources neededDeployment resources only

Secret Management​

Both automation types handle secrets securely:

secretGenerator:
- name: registry-credential
namespace: namespace
files:
- .dockerconfigjson=secret/registry.json
type: kubernetes.io/dockerconfigjson

- name: component-external-source-secrets
namespace: namespace
envs:
- secret/cloud.env

- name: component-cosign-key-secret
namespace: namespace
files:
- secret/cosign/cosign.key
- secret/cosign/cosign.pub
- secret/cosign/password

πŸ“š Best Practices​

General Automation Guidelines​

PracticeDescriptionBenefit
Start SimpleBegin with basic componentsEasier troubleshooting
Use Sub-ComponentsLeverage hierarchical structureBetter organization
Define RelationshipsConnect components properlyAutomatic configuration
Test in StagesDev β†’ Staging β†’ ProductionRisk mitigation
Review Generated DocsCheck automation outputsUnderstanding & validation
Version EverythingTag images and codeRollback capability
Use Security ContextsEnable pod/container securityDefense in depth

Security Recommendations​

  1. External Authentication - Use OIDC providers over built-in auth
  2. Secret Management - Let Stacktic handle secret generation
  3. Network Policies - Enable auto-generated policies
  4. TLS Everywhere - Use encrypted connections
  5. Regular Updates - Keep component versions current
  6. Image Signing - Enable Cosign for supply chain security
  7. RBAC - Use service accounts with minimal permissions

Performance Optimization​

  • βœ… Use k6 for baseline performance testing
  • βœ… Configure resource limits appropriately
  • βœ… Enable horizontal pod autoscaling
  • βœ… Implement caching strategies
  • βœ… Monitor with Prometheus/Grafana
  • βœ… Use init containers for one-time setup
  • βœ… Optimize image sizes

🎯 Summary​

Key Takeaways​

βœ… Pattern-Based Automation - Best practices built into every component
βœ… Relationship Intelligence - Connections drive configuration
βœ… Complete Stack Coverage - From messaging to testing
βœ… Security by Default - Authentication, encryption, policies
βœ… Production Ready - Generated configurations are deployment-ready
βœ… Flexible Deployment - Support for both source code and pre-built images
βœ… GitOps Native - All configurations in Git-friendly formats

What's Automated vs. What You Control​

Stacktic AutomatesYou Control
Infrastructure configurationBusiness logic
Service connectionsApplication code
Security policiesData schemas
Monitoring setupBusiness rules
Testing frameworksCustom algorithms
Build pipelinesSource code
Deployment manifestsConfiguration values

These examples demonstrate the power of Stacktic's automation. The full automation in your repository will include complete configurations, documentation, and operational procedures tailored to your specific stack.

Version: 2.0
Last Updated: September 2025
Β© Stacktic - Intelligent Stack Automation