File size: 7,657 Bytes
eca5751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""DevOps Skill - Sinh Dockerfile, k8s manifests, Terraform, CI/CD pipelines.

Tạo artifacts DevOps từ mô tả tự nhiên: container images, Kubernetes
deployments, infrastructure-as-code, và CI/CD pipeline templates.

Author: Hieu Louis (2026)
"""
from __future__ import annotations

from typing import Dict, List

from .base import Skill, SkillContext, SkillCategory, SkillPriority, SkillResult


class DevOpsSkill(Skill):
    """Sinh DevOps artifacts: Docker, Kubernetes, Terraform, CI/CD."""

    category = SkillCategory.DEVOPS
    priority = SkillPriority.HIGH
    keywords: List[str] = [
        "docker", "dockerfile", "container", "kubernetes", "k8s",
        "terraform", "ansible", "ci/cd", "cicd", "jenkins",
        "github actions", "gitlab ci", "helm", "deploy",
        "pod", "deployment", "service", "ingress", "manifest",
    ]
    examples = [
        "Tạo Dockerfile cho FastAPI app",
        "Generate k8s deployment manifest for Redis",
        "Write Terraform to provision an EC2 instance",
        "Setup GitHub Actions CI/CD pipeline for Python project",
    ]

    @property
    def name(self) -> str:
        return "devops"

    @property
    def description(self) -> str:
        return (
            "Sinh DevOps artifacts: Dockerfile (multi-stage), Kubernetes "
            "manifests (Deployment/Service/Ingress), Terraform modules, "
            "Helm charts, và CI/CD pipelines (GitHub Actions / GitLab CI)."
        )

    def can_handle(self, prompt: str, context: SkillContext = None) -> float:
        prompt_lower = prompt.lower()
        score = 0.0
        for kw in self.keywords:
            if kw in prompt_lower:
                score += 0.25
        if any(tag in prompt_lower for tag in ("yaml", "yml", ".tf", "manifest")):
            score += 0.2
        return min(1.0, score)

    def _detect_target(self, prompt: str) -> str:
        p = prompt.lower()
        if "dockerfile" in p or "docker" in p and "image" in p:
            return "dockerfile"
        if "kubernetes" in p or "k8s" in p or "manifest" in p or "helm" in p:
            return "k8s"
        if "terraform" in p or ".tf" in p or "infrastructure" in p:
            return "terraform"
        if "ci/cd" in p or "cicd" in p or "github actions" in p or "gitlab" in p or "jenkins" in p:
            return "cicd"
        if "ansible" in p:
            return "ansible"
        return "dockerfile"

    def execute(self, context: SkillContext) -> SkillResult:
        target = self._detect_target(context.prompt)
        artifact = self._build_artifact(target, context)

        return SkillResult(
            success=True,
            output=f"[DevOps/{target}] Artifact ready for: {context.prompt[:180]}",
            artifacts=[artifact],
            metadata={
                "skill": self.name,
                "target": target,
                "language": context.language or "yaml",
                "tools": ["docker", "kubectl", "terraform", "helm", "act"],
            },
            suggestions=[
                "Pin base image digests for reproducible builds (e.g. python:3.12-slim@sha256:...)",
                "Scan images for CVEs (trivy, grype) before pushing",
                "Use multi-stage builds to shrink final image size",
                "Apply least-privilege RBAC and network policies in k8s",
                "Store secrets in a vault (Vault, AWS SM, Sealed Secrets)",
                "Enable image signature verification (cosign) in CI",
            ],
        )

    def _build_artifact(self, target: str, context: SkillContext) -> Dict[str, str]:
        if target == "k8s":
            return {
                "path": "k8s/deployment.yaml",
                "content": _K8S_MANIFEST,
            }
        if target == "terraform":
            return {
                "path": "infra/main.tf",
                "content": _TERRAFORM_SNIPPET,
            }
        if target == "cicd":
            return {
                "path": ".github/workflows/ci.yml",
                "content": _GITHUB_ACTIONS,
            }
        if target == "ansible":
            return {
                "path": "ansible/playbook.yml",
                "content": _ANSIBLE_PLAYBOOK,
            }
        return {"path": "Dockerfile", "content": _DOCKERFILE}


_DOCKERFILE = """# Multi-stage Dockerfile — Python service
FROM python:3.12-slim AS builder
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1
COPY requirements.txt .
RUN pip install --user -r requirements.txt

FROM python:3.12-slim AS runtime
RUN useradd -m -u 10001 appuser
WORKDIR /app
COPY --from=builder /root/.local /home/appuser/.local
COPY . .
USER appuser
ENV PATH=/home/appuser/.local/bin:$PATH
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s CMD python -c "import urllib.request;urllib.request.urlopen('http://127.0.0.1:8000/health')"
CMD ["uvicorn", "app:main", "--host", "0.0.0.0", "--port", "8000"]
"""

_K8S_MANIFEST = """apiVersion: apps/v1
kind: Deployment
metadata:
  name: nexus-api
  labels: {app: nexus-api}
spec:
  replicas: 3
  selector:
    matchLabels: {app: nexus-api}
  template:
    metadata:
      labels: {app: nexus-api}
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
        fsGroup: 10001
      containers:
        - name: api
          image: ghcr.io/nexus/api:0.3.0
          ports: [{containerPort: 8000}]
          resources:
            requests: {cpu: "250m", memory: "256Mi"}
            limits:   {cpu: "1000m", memory: "1Gi"}
          livenessProbe:
            httpGet: {path: /health, port: 8000}
            initialDelaySeconds: 10
          readinessProbe:
            httpGet: {path: /ready, port: 8000}
---
apiVersion: v1
kind: Service
metadata:
  name: nexus-api
spec:
  selector: {app: nexus-api}
  ports: [{port: 80, targetPort: 8000}]
  type: ClusterIP
"""

_TERRAFORM_SNIPPET = """# Infrastructure as Code — AWS EC2
terraform {
  required_version = ">= 1.7"
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 5.0" }
  }
}

provider "aws" {
  region = var.region
}

variable "region"  { default = "ap-southeast-1" }
variable "instance_type" { default = "t3.small" }

resource "aws_instance" "nexus" {
  ami                    = data.aws_ami.ubuntu.id
  instance_type          = var.instance_type
  vpc_security_group_ids = [aws_security_group.nexus.id]
  tags                   = { Name = "nexus-coder" }
}

resource "aws_security_group" "nexus" {
  name = "nexus-sg"
  ingress {
    from_port = 443
    to_port   = 443
    protocol  = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
"""

_GITHUB_ACTIONS = """name: CI
on:
  push: { branches: [main] }
  pull_request: { branches: [main] }
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: { python-version: "3.12" }
      - run: pip install -r requirements.txt -r requirements-dev.txt
      - run: ruff check .
      - run: mypy src
      - run: pytest --cov --cov-report=xml
      - uses: codecov/codecov-action@v4
"""

_ANSIBLE_PLAYBOOK = """---
- name: Provision Nexus Coder host
  hosts: webservers
  become: true
  vars:
    app_version: "0.3.0"
  tasks:
    - name: Install system deps
      apt:
        name: [python3, python3-pip, nginx]
        update_cache: true
    - name: Create app user
      user: { name: nexus, shell: /sbin/nologin, system: true }
    - name: Deploy app
      copy:
        src: ../dist/
        dest: /opt/nexus/
        owner: nexus
    - name: Ensure nginx running
      service: { name: nginx, state: started, enabled: true }
"""