Development of an AI-based generation system for Infrastructure as Code
IaC AI generation – automatically creates Terraform, Ansible, and Kubernetes manifests based on a textual description of the infrastructure. Lowers the barrier to entry for IaC deployments and accelerates the creation of standard configurations.
Terraform generation
def generate_terraform(description: str, cloud: str = "aws") -> str:
prompt = f"""Сгенерируй Terraform конфигурацию для {cloud}.
Описание: {description}
Требования:
- Используй последние stable provider версии
- variables.tf для всех параметров
- outputs.tf для ключевых ресурсов
- Теги для всех ресурсов
- Комментарии к нетривиальным блокам
- Backend S3 + DynamoDB для state locking"""
terraform_code = llm.generate(prompt, max_tokens=3000)
return terraform_code
# Пример: "Создай ECS кластер с ALB, 2-4 инстанции Fargate, RDS PostgreSQL"
# Результат: полный Terraform модуль с VPC, ECS, ALB, RDS, security groups, IAM
Validation of the generated IaC
import subprocess
def validate_terraform(tf_dir: str) -> ValidationResult:
# terraform fmt
fmt_result = subprocess.run(["terraform", "fmt", "-check", tf_dir],
capture_output=True, text=True)
# terraform validate
init_result = subprocess.run(["terraform", "init", "-backend=false", tf_dir],
capture_output=True, text=True)
validate_result = subprocess.run(["terraform", "validate", tf_dir],
capture_output=True, text=True)
# tflint — дополнительные проверки
tflint_result = subprocess.run(["tflint", "--format=json", tf_dir],
capture_output=True, text=True)
# checkov — security checks
checkov_result = subprocess.run(
["checkov", "-d", tf_dir, "--framework", "terraform", "-o", "json"],
capture_output=True, text=True
)
return ValidationResult(
fmt_ok=fmt_result.returncode == 0,
valid=validate_result.returncode == 0,
validation_errors=validate_result.stderr,
security_issues=json.loads(checkov_result.stdout).get("results", {}).get("failed_checks", []),
)
Generating Kubernetes manifests
def generate_k8s_manifests(app_config: AppConfig) -> dict[str, str]:
prompt = f"""Сгенерируй Kubernetes манифесты для деплоя приложения.
Приложение: {app_config.name}
Image: {app_config.image}
Порт: {app_config.port}
Реплики: {app_config.replicas}
CPU: {app_config.cpu_request}/{app_config.cpu_limit}
Memory: {app_config.memory_request}/{app_config.memory_limit}
Environment vars: {app_config.env_vars}
Needs: {app_config.needs} # "database", "redis", "ingress"
Создай: Deployment, Service, HPA, ConfigMap, PodDisruptionBudget, NetworkPolicy."""
return parse_k8s_yaml(llm.generate(prompt, max_tokens=4000))
Drift detection
After implementing IaC, regularly check for drift: the actual infrastructure versus the configuration in code. The terraform plan is run in dry-run mode. If there are any discrepancies, an alert is issued and an automatic PR is sent with a suggested fix.
The Pitfalls of IaC AI Generation
- Deprecated syntax: LLM is trained on older versions of Terraform and uses deprecated resources. Solution: explicitly specify the target provider version in the prompt + validation.
- Security anti-patterns: open security groups, no encryption at all. Solution: checkov after generation + security-focused post-instruction.
-
Hardcoded credentials: LLM sometimes inserts a placeholder like
access_key = "AKIAXXXXXXXX". Solution: grep for credentials patterns before the PR.







