dbaplus社群 4小时前
生产数据库泄露、P0重大事故!我劝你不要把AI用在DevOps上……
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

使用AI生成基础设施代码存在五大错误,可能导致严重安全风险。本文介绍了如何识别和修复这些错误,确保基础设施安全可靠。

🔒AI生成的基础设施≠安全基础设施:AI模型优先考虑系统运行而非安全,常使用'0.0.0.0/0'入口规则,需明确要求安全、生产就绪、遵循最小特权原则的基础设施配置。

👥像DevOps而非开发人员提问:AI应被视为高级DevOps顾问,而非初级开发人员。需提供详细需求,如蓝绿部署、OIDC认证、安全扫描等,而非模糊的即时需求。

🤔虚假信心问题:AI输出看似完美,但缺乏安全检查表(最小特权、秘密处理、网络分段等)和可靠性检查表(健康检查、资源限制等),需人工核实。

🧠没有教AI像SRE一样思考:通过系统提示设定上下文,要求AI从SRE角度设计基础设施,考虑安全、可用性、可观察性、成本优化和合规性,包含错误处理、监控等。

📜盲目信任AI生成的YAML:AI生成的Kubernetes YAML可能存在严重安全漏洞,如以root身份运行、泄露秘密、无资源限制等,需严格审核和验证。

原创 Zudonu Osomudeya 2025-08-11 07:16 广东

警惕!这5个AI错误正威胁基础设施,赶紧修复你的提示词!

我们都陷入了陷阱

那晚,我的手机响个不停……

“严重事故:生产数据库暴露在公共互联网上” 

“所有客户数据都可能受到损害”

“CEO 要求立即得到答案”

我手忙脚乱地想弄清楚到底出了什么灾难性的错误,通知却接踵而至。我们的安全监控工具发出了警报。保存着每条客户记录、每笔付款明细以及我们发誓要保护的每一条敏感数据的数据库,现在完全暴露在互联网上。

但有一件事让我感到心痛:我清楚地知道是什么导致了这场灾难。

两天前,我一直在赶着部署我们新的 PostgreSQL RDS 实例。截止日期的压力越来越大,手动编写 Terraform 代码感觉非常慢。所以我做了一件感觉很聪明、很现代的事情:我请 Claude 帮我生成基础设施代码。

输出看起来很漂亮。语法清晰,资源命名恰当,所有格式都完美无缺。我大概浏览了三十秒,心想“这 AI 的东西太厉害了”,然后毫不犹豫地直接把它合并到了主代码中。

这段看似完美的代码背后隐藏着一个包含0.0.0.0/0入口规则的安全组配置。我的“效率黑客”刚刚把我们最敏感的数据库变成了互联网上所有攻击者都能看到的公共公告牌。

那天晚上,我们花了 5 万美元用于事件响应,经历了数周的监管难题,甚至差点丢掉了工作。但它教会了我一个至关重要的东西:人工智能不仅改变了 DevOps 工程师的工作方式,还创造了全新的灾难性故障方式。

如果您使用 ChatGPT、Claude 或 GitHub Copilot 来生成基础架构代码、部署脚本或 CI/CD 工作流,那么您可能犯了和我一样的错误。说实话?只要一个错误的提示,您就离安全噩梦只有一步之遥。


错误1:人工智能生成的基础设施≠安全基础设施

残酷的现实是:AI 模型需要使用来自 GitHub、Stack Overflow 和随机教程的数百万个代码示例进行训练。猜猜这些示例的优先级是什么?是让系统正常运行,而不是确保系统安全。


“快乐路径”问题

AI 喜欢生成能够立即生效的配置。但在 DevOps 中,“可运行”和“生产就绪”是完全不同的两个世界。

糟糕的 AI 输出(我实际发布的):

    resource "aws_security_group" "web_sg" {
      name = "web-server-sg"


      ingress {
        from_port   = 80
        to_port     = 80
        protocol    = "tcp"
        cidr_blocks = ["0.0.0.0/0"]  # DANGER ZONE
      }


      ingress {
        from_port   = 22
        to_port     = 22
        protocol    = "tcp"
        cidr_blocks = ["0.0.0.0/0"]  # SSH TO THE WORLD
      }
    }

    安全基础设施实际上是什么样的:

      resource "aws_security_group" "web_sg" {
        name_prefix = "web-server-sg-"
        ingress {
          description = "HTTP from ALB only"
          from_port   = 80
          to_port     = 80
          protocol    = "tcp"
          security_groups = [aws_security_group.alb_sg.id]
        }


        # NO direct SSH - use Systems Manager Session Manager


        egress {
          description = "HTTPS outbound only"
          from_port   = 443
          to_port     = 443
          protocol    = "tcp"
          cidr_blocks = ["0.0.0.0/0"]
        }


        tags = {
          Name = "web-server-sg"
          Environment = var.environment
        }
      }


      解决方法:安全第一提示

      不要只要求基础设施。要要求安全、可用于生产、遵循最小特权原则的基础设施。

      而不是: “为 Web 服务器创建 AWS 安全组”

      尝试一下: “为遵循安全最佳实践的 Web 服务器创建一个可用于生产的 AWS 安全组:无直接 Internet SSH 访问、最小入口规则、明确的出口规则以及适当的合规标记。”


      错误2:像开发人员那样而不是像 DevOps 工程师那样提出问题

      大多数工程师请求 AI 就像请求初级开发人员帮忙一样。但 DevOps 不仅仅是编写代码,它还涉及构建可靠、可观察、安全的大规模系统。


      模糊的即时灾难

      糟糕的提示: “为我写一个 Python 版 GitHub Actions 工作流程”

      这会让你得到一个可能在别人的笔记本电脑上运行的基本工作流程。它无法正确处理机密信息,无法进行适当的错误处理,当然也没有回滚逻辑。

      DevOps 级提示:

        Create a production-ready GitHub Actions workflow for a Python FastAPI application with these requirements:


        - Deploy to AWS ECS using blue/green deployment
        - Use OIDC for AWS authentication (no stored secrets)
        - Run security scanning with Snyk
        - Execute integration tests against a staging environment
        - Implement automatic rollback if health checks fail
        - Store deployment artifacts in S3 with 90-day retention
        - Send Slack notifications for deployment status
        - Include proper error handling and timeout configurations

        发现区别了吗?第二个提示将 AI 视为高级 DevOps 顾问,而不是编程训练营的毕业生。


        真实示例:实际有效的 CI/CD 管道

        以下是详细提示生成的内容(经过一些清理):

          name: Production Deploy
          on:
            push:
              branches: [main]
          env:
            AWS_REGION: us-east-1
            ECS_CLUSTER: production
            ECS_SERVICE: api-service
          jobs:
            security-scan:
              runs-on: ubuntu-latest
              steps:
                - uses: actions/checkout@v4
                
                - name: Run Snyk Security Scan
                  uses: snyk/actions/python@master
                  env:
                    SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
                  with:
                    args: --severity-threshold=high --fail-on=upgradable
            deploy:
              needs: security-scan
              runs-on: ubuntu-latest
              permissions:
                id-token: write
                contents: read
              
              steps:
                - name: Configure AWS Credentials
                  uses: aws-actions/configure-aws-credentials@v4
                  with:
                    role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
                    aws-region: ${{ env.AWS_REGION }}
                
                - name: Deploy with Blue/Green
                  run: |
                    # Update ECS service with new task definition
                    aws ecs update-service \
                      --cluster $ECS_CLUSTER \
                      --service $ECS_SERVICE \
                      --task-definition $NEW_TASK_DEF_ARN \
                      --deployment-configuration "minimumHealthyPercent=50,maximumPercent=200"
                    
                    # Wait for deployment to stabilize
                    aws ecs wait services-stable \
                      --cluster $ECS_CLUSTER \
                      --services $ECS_SERVICE \
                      --cli-read-timeout 600
                
                - name: Health Check & Rollback
                  run: |
                    # Check application health
                    for i in {1..10}; do
                      if curl -f https://api.example.com/health; then
                        echo "Health check passed"
                        exit 0
                      fi
                      sleep 30
                    done
                    
                    echo " Health check failed - rolling back"
                    aws ecs update-service \
                      --cluster $ECS_CLUSTER \
                      --service $ECS_SERVICE \
                      --task-definition $PREVIOUS_TASK_DEF_ARN
                    exit 1
                
                - name: Notify Slack
                  if: always()
                  uses: 8398a7/action-slack@v3
                  with:
                    status: ${{ job.status }}
                    channel: '#deployments'
                  env:
                    SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}

          这就是“它在我的计算机上运行”和“当一切正常时它在生产中运行”之间的区别。


          错误3:虚假信心问题

          AI 输出拥有超能力:它总是看起来自信满满。没有// TODO: fix this later注释,没有不确定的变量名。只有简洁、权威的代码,仿佛在说:“相信我,我知道自己在做什么。”

          这在 DevOps 极其危险。

          上个月,一位队友请 ChatGPT 为我们的微服务编写一个 Kubernetes 部署。输出看起来很漂亮:

            apiVersion: apps/v1
            kind: Deployment
            metadata:
              name: user-service
            spec:
              replicas: 3
              selector:
                matchLabels:
                  app: user-service
              template:
                metadata:
                  labels:
                    app: user-service
                spec:
                  containers:
                  - name: user-service
                    image: user-service:latest
                    ports:
                    - containerPort: 8080
                    resources:
                      requests:
                        memory: "64Mi"
                        cpu: "250m"
                      limits:
                        memory: "128Mi"
                        cpu: "500m"

            看起来不错吧?错了。这种配置很快就会引发生产灾难:

              没有健康检查→ Kubernetes 会将流量路由到损坏的 Pod

              latest标签→ 零部署可重复性

              微小的资源限制→ 负载下即时 OOMKills

              无安全上下文→ 容器以 root 身份运行

              无环境分离→ 将部署到任何命名空间


            现实检验框架

            永远不要轻信人工智能的输出。相反,你应该在心里核对一下:

            安全检查表:

              是否应用了最小特权原则?

              秘密处理得当吗?

              网络分段是否到位?

              已启用安全扫描?

            可靠性检查表:

              健康检查配置了吗?

              资源限制设置是否适当?

              包含重试和超时逻辑?

              监控和警报是否涵盖?

            操作清单:

              日志配置好了没有?

              部署策略已定义?

              回滚计划存在吗?

              特定于环境的配置?


            错误4:你没有教AI像SRE一样思考

            这是一个令人费解的认识:人工智能实际上可以模拟高级站点可靠性工程师的思维过程。但前提是你必须正确地构建上下文。

            大多数人把人工智能当成花哨的自动完成工具。但如果你能让它像你认识的最偏执、最有经验的 DevOps 工程师一样思考,那会怎样呢?


            系统提示的秘密

            在询问任何基础设施代码之前,先从设置上下文的系统提示开始:

              You are a Senior Site Reliability Engineer at a Fortune 500 company. 
              You're responsible for systems that handle millions of requests per day 
              and cannot afford downtime. Every piece of infrastructure you design 
              must be:


              - Secure by default (zero-trust principles)
              - Highly available (99.99% uptime SLA)
              - Observable (comprehensive monitoring/logging)
              - Cost-optimized (company is watching cloud spend)
              - Compliant (SOC2, PCI-DSS requirements)
              When generating infrastructure code, always include:
              - Proper error handling and retry logic
              - Security best practices and least privilege access
              - Monitoring, alerting, and logging configurations
              - Disaster recovery considerations
              - Cost optimization strategies
              Think through potential failure modes before responding.

              现在请求你的 Terraform 模块。观察一下区别。


              之前与之后:真实的例子

              无系统提示‘基本’ RDS:

                resource "aws_db_instance" "database" {
                  identifier = "myapp-db"
                  engine     = "postgres"
                  engine_version = "13.7"
                  instance_class = "db.t3.micro"
                  allocated_storage = 20
                  db_name = "myapp"
                  username = "admin"
                  password = "password123"
                  skip_final_snapshot = true
                }

                使用 SRE 系统提示“生产”RDS:

                  # Production PostgreSQL with high availability and security
                  resource "aws_db_subnet_group" "main" {
                    name       = "${var.project}-db-subnet-group"
                    subnet_ids = var.private_subnet_ids


                  tags = {
                      Name = "${var.project} DB Subnet Group"
                      Environment = var.environment
                    }
                  }
                  resource "aws_db_parameter_group" "main" {
                    family = "postgres14"
                    name   = "${var.project}-postgres-params"
                    parameter {
                      name  = "log_statement"
                      value = "all"
                    }
                    parameter {
                      name  = "log_min_duration_statement"
                      value = "1000"  # Log queries taking >1s
                    }
                  }
                  resource "aws_db_instance" "main" {
                    identifier = "${var.project}-${var.environment}-primary"


                    # Engine configuration
                    engine         = "postgres"
                    engine_version = "14.9"  # Specific version for reproducibility
                    instance_class = var.db_instance_class


                    # Storage configuration
                    allocated_storage     = var.allocated_storage
                    max_allocated_storage = var.max_allocated_storage
                    storage_type         = "gp3"
                    storage_encrypted    = true
                    kms_key_id          = aws_kms_key.rds.arn


                    # Database configuration
                    db_name  = var.database_name
                    username = var.master_username
                    password = var.master_password  # Should use AWS Secrets Manager in real implementation
                    port     = 5432


                    # High Availability
                    multi_az               = var.environment == "production" ? true : false
                    backup_retention_period = var.environment == "production" ? 30 : 7
                    backup_window          = "03:00-04:00"  # During low traffic
                    maintenance_window     = "sun:04:00-sun:05:00"


                    # Security
                    db_subnet_group_name   = aws_db_subnet_group.main.name
                    vpc_security_group_ids = [aws_security_group.rds.id]
                    parameter_group_name   = aws_db_parameter_group.main.name


                    # Monitoring & Logging
                    monitoring_interval = 60
                    monitoring_role_arn = aws_iam_role.rds_monitoring.arn
                    enabled_cloudwatch_logs_exports = ["postgresql"]


                    # Maintenance
                    auto_minor_version_upgrade = false  # Manual control for production
                    deletion_protection        = var.environment == "production" ? true : false
                    skip_final_snapshot       = var.environment == "production" ? false : true
                    final_snapshot_identifier = "${var.project}-${var.environment}-final-snapshot-${formatdate("YYYY-MM-DD-hhmm", timestamp())}"
                    tags = {
                      Name           = "${var.project} ${var.environment} Database"
                      Environment    = var.environment
                      Project        = var.project
                      BackupRequired = "true"
                      Compliance     = "SOC2"
                    }
                  }


                  # CloudWatch Alarms for monitoring
                  resource "aws_cloudwatch_metric_alarm" "database_cpu" {
                    alarm_name          = "${var.project}-${var.environment}-db-cpu"
                    comparison_operator = "GreaterThanThreshold"
                    evaluation_periods  = "2"
                    metric_name         = "CPUUtilization"
                    namespace           = "AWS/RDS"
                    period              = "120"
                    statistic           = "Average"
                    threshold           = "80"
                    alarm_description   = "This metric monitors db cpu utilization"
                    dimensions = {
                      DBInstanceIdentifier = aws_db_instance.main.id
                    }


                    alarm_actions = [aws_sns_topic.alerts.arn]
                  }
                  resource "aws_cloudwatch_metric_alarm" "database_connections" {
                    alarm_name          = "${var.project}-${var.environment}-db-connections"
                    comparison_operator = "GreaterThanThreshold"
                    evaluation_periods  = "2"
                    metric_name         = "DatabaseConnections"
                    namespace           = "AWS/RDS"
                    period              = "120"
                    statistic           = "Average"
                    threshold           = "80"
                    alarm_description   = "This metric monitors database connection count"


                    dimensions = {
                      DBInstanceIdentifier = aws_db_instance.main.id
                    }


                    alarm_actions = [aws_sns_topic.alerts.arn]
                  }

                  两者之间存在着天壤之别。第二个问题实际上考虑的是当事情出错时会发生什么。


                  错误5:盲目信任AI生成的YAML

                  Kubernetes YAML 是 AI 真正危险的地方。一个配置错误的 Pod 规范就可能毁掉整个集群。然而,我看到工程师们复制粘贴 AI 生成的清单,就像从官方文档中复制配置一样。


                  YAML噩梦

                  危险的AI输出:

                    apiVersion: v1
                    kind: Pod
                    metadata:
                      name: payment-processor
                    spec:
                      containers:
                      - name: payment-app
                        image: payment-service:latest
                        ports:
                        - containerPort: 8080
                        env:
                        - name: DATABASE_URL
                          value: "postgresql://admin:password123@db:5432/payments"
                        - name: STRIPE_SECRET_KEY
                          value: "sk_live_..." # SECRETS IN PLAIN TEXT

                    此 YAML 将:

                      以 root 身份运行容器(巨大的安全风险)

                      以纯文本形式泄露秘密(合规噩梦)

                      没有资源限制(一次内存泄漏就会导致节点死亡)

                      使用最新标签(零部署可重复性)

                      没有健康检查(损坏的 pod 仍在轮换)


                    生产就绪替代方案

                    安全、可观察的 Pod 规范:

                      apiVersion: apps/v1
                      kind: Deployment
                      metadata:
                        name: payment-processor
                        namespace: payments
                        labels:
                          app: payment-processor
                          version: v1.2.3
                      spec:
                        replicas: 3
                        strategy:
                          type: RollingUpdate
                          rollingUpdate:
                            maxUnavailable: 1
                            maxSurge: 1
                        selector:
                          matchLabels:
                            app: payment-processor
                        template:
                          metadata:
                            labels:
                              app: payment-processor
                              version: v1.2.3
                            annotations:
                              prometheus.io/scrape: "true"
                              prometheus.io/port: "8080"
                              prometheus.io/path: "/metrics"
                          spec:
                            serviceAccountName: payment-processor
                            securityContext:
                              runAsNonRoot: true
                              runAsUser: 10001
                              fsGroup: 10001
                            containers:
                            - name: payment-app
                              image: payment-service:v1.2.3  # Specific version tag
                              imagePullPolicy: Always
                              ports:
                              - name: http
                                containerPort: 8080
                                protocol: TCP
                              - name: metrics
                                containerPort: 9090
                                protocol: TCP
                              
                              # Resource management
                              resources:
                                requests:
                                  memory: "256Mi"
                                  cpu: "100m"
                                limits:
                                  memory: "512Mi"
                                  cpu: "500m"
                              
                              # Health checks
                              livenessProbe:
                                httpGet:
                                  path: /health
                                  port: http
                                initialDelaySeconds: 30
                                periodSeconds: 10
                                timeoutSeconds: 5
                                failureThreshold: 3
                              
                              readinessProbe:
                                httpGet:
                                  path: /ready
                                  port: http
                                initialDelaySeconds: 5
                                periodSeconds: 5
                                timeoutSeconds: 3
                                failureThreshold: 3
                              
                              # Environment variables (secrets handled separately)
                              env:
                              - name: PORT
                                value: "8080"
                              - name: ENVIRONMENT
                                value: "production"
                              - name: LOG_LEVEL
                                value: "info"
                              
                              # Secrets from external secret management
                              envFrom:
                              - secretRef:
                                  name: payment-processor-secrets
                              - configMapRef:
                                  name: payment-processor-config
                              
                              # Security context
                              securityContext:
                                allowPrivilegeEscalation: false
                                readOnlyRootFilesystem: true
                                capabilities:
                                  drop:
                                  - ALL
                              
                              # Volume mounts for temporary files
                              volumeMounts:
                              - name: tmp
                                mountPath: /tmp
                              - name: cache
                                mountPath: /app/cache
                            
                            volumes:
                            - name: tmp
                              emptyDir: {}
                            - name: cache
                              emptyDir: {}
                            
                            # Node selection and tolerations
                            nodeSelector:
                              kubernetes.io/arch: amd64
                            tolerations:
                            - key: "workload"
                              operator: "Equal"
                              value: "payments"
                              effect: "NoSchedule"

                      Claude提示拯救了我的堆栈

                      那次数据库泄露事件几乎终结了我的职业生涯,此后我开始痴迷于寻找一种安全使用人工智能的方法。我需要一种能够在我的错误演变成灾难之前发现它们的方法。

                      然后我发现了要求人工智能审核自身工作的力量。

                      上个月,我正在为我们的支付处理服务搭建一个新的 EKS 集群。我已经吸取了教训,不要盲目相信 AI 的输出,但我仍然希望获得速度上的优势。所以我尝试了一些不同的方法。

                      首先,我让 Claude 生成初始的 Kubernetes 清单。输出看起来还不错,但我没有直接部署,而是使用了以下后续提示:

                        ou are a Senior Security Engineer conducting a security audit of the Kubernetes manifests you just generated. Your job is to find every possible security vulnerability, compliance issue, and operational risk.


                        Assume the worst-case scenario: this application handles PCI-compliant payment data, runs in a shared cluster with other workloads, and will be targeted by sophisticated attackers.
                        Review each manifest and provide:
                        1. A severity rating (Critical/High/Medium/Lowfor each issue found
                        2. The specific line or configuration causing the problem
                        3. The exact fix needed
                        4. Why this matters in a production environment
                        Be paranoid. Be thorough. Pretend you're the one who gets fired if this gets hacked.

                        结果令人大开眼界。

                        Claude立即发现了我完全忽略的七个安全问题:

                          严重:以 root (uid 0) 身份运行的容器

                          严重:无资源限制(可能造成集群范围的 DoS)

                          高:缺少安全上下文和功能下降

                          高:机密作为环境变量而不是卷挂载

                          中等:无网络策略(横向移动风险)

                          中:服务帐户权限过于宽泛

                          低:缺少吊舱中断预算

                        但关键在于,Claude 不仅发现了问题,还提供了确切的解决方案:

                        原始AI输出:

                          apiVersion: apps/v1
                          kind: Deployment
                          metadata:
                            name: payment-service
                          spec:
                            template:
                              spec:
                                containers:
                                - name: payment-app
                                  image: payment-service:v1.0.0
                                  env:
                                  - name: STRIPE_SECRET
                                    value: "sk_live_..." # SECRET IN PLAIN TEXT
                                  resources: {} # NO LIMITS

                          Claude的安全审计版本:

                            apiVersion: apps/v1
                            kind: Deployment
                            metadata:
                              name: payment-service
                              namespace: payments
                            spec:
                              template:
                                spec:
                                  serviceAccountName: payment-service-sa
                                  securityContext:
                                    runAsNonRoot: true
                                    runAsUser: 10001
                                    fsGroup: 10001
                                    seccompProfile:
                                      type: RuntimeDefault
                                  containers:
                                  - name: payment-app
                                    image: payment-service:v1.0.0
                                    securityContext:
                                      allowPrivilegeEscalation: false
                                      readOnlyRootFilesystem: true
                                      capabilities:
                                        drop:
                                        - ALL
                                    resources:
                                      requests:
                                        memory: "256Mi"
                                        cpu: "100m"
                                      limits:
                                        memory: "512Mi"
                                        cpu: "500m"
                                    volumeMounts:
                                    - name: stripe-secrets
                                      mountPath: /etc/secrets
                                      readOnly: true
                                    env:
                                    - name: STRIPE_SECRET_PATH
                                      value: "/etc/secrets/stripe_key"
                                  volumes:
                                  - name: stripe-secrets
                                    secret:
                                      secretName: stripe-secrets
                                      defaultMode: 0400

                            结果如何?我们的自动扫描仪没有发现任何安全问题。安全团队也没有任何投诉。最重要的是,凌晨三点的叫醒电话也零了。

                            这种“AI 审计 AI”的方法已经成为我的秘密武器。我用 AI 快速生成基础设施代码,然后立即让它从安全角度剖析自己的工作。这就像让一位偏执的高级工程师审查每一行代码,只不过它永远不会疲倦,从不错过任何明显的错误,也不会因为我要求它检查两次同一件事而责怪我。

                            我现在为每个 AI 生成的基础设施使用的提示模板:

                              Act as a security-focused Senior Site Reliability Engineer reviewing the [RESOURCE TYPE] you just generated. Your company has strict security requirements and you've seen too many breaches caused by misconfigurations.


                              Audit this configuration for:
                              - Security vulnerabilities and attack vectors
                              - Compliance issues (SOC2, PCI-DSS where applicable)  
                              - Operational risks and failure modes
                              - Cost optimization opportunities
                              - Performance bottlenecks
                              For each issue found, provide:
                              - Severity level and business impact
                              - Root cause explanation
                              - Specific remediation steps
                              - Prevention strategies for future deployments
                              Be ruthlessly thorough. This goes to production tomorrow.

                              有时验证人工智能的最好方法就是让它与自己争论。

                              但这是关键的现实检验

                              即使拥有所有这些人工智能验证技术,有一件事你绝对不能外包:你自己的工程判断。

                              我看到太多工程师把AI当成可以盲目跟从的高级架构师。这种想法很危险。AI无法理解你具体的架构约束、公司的风险承受能力,也无法理解在你的用例中,某个解决方案优于另一个解决方案的细微之处。

                              人工智能是你的编码加速器,而不是你的思维替代品。

                              我的意思是:

                                错误方法: “AI,为我的微服务构建一个完整的 CI/CD 管道” ,然后部署它提供的任何内容


                                正确方法: “我需要一个能够处理蓝绿部署、拥有完善的机密管理并包含回滚机制的流水线。我先设计架构,然后让人工智能实现具体的部分,同时我根据需求验证每个组件。”

                              你的大脑需要掌控全局。利用人工智能来:

                                更快地生成样板代码

                                探索实施方案

                                发现你可能错过的错误

                                研究不熟悉的技术的最佳实践

                              但您仍然需要:

                                了解生成的代码实际上做什么

                                验证其是否满足您的特定安全要求

                                确保它适合您现有的架构

                                在您的环境中进行彻底测试

                                根据具体情况做出架构决策

                              我曾经经历过惨痛的教训:AI 生成了一个“完美”的自动扩展配置,但由于它不理解我们的流量模式,每月要花费我们 1 万美元。代码在技术上是正确的,但对我们的业务来说却完全错误。

                              60/40 规则: AI 应该处理 60% 的打字工作,但你应该负责 100% 的思考。一旦你发现自己在不理解 AI 输出的情况下就直接复制粘贴,那就麻烦了。

                              请记住:当生产中断时,没有人工智能可以接听事件电话并解释为什么它的建议在当时看起来是个好主意。


                              DevOps 工程师如何安全地使用 AI

                              好了,恐怖故事讲得够多了。接下来,我们将教你如何真正利用人工智能,提升 DevOps 工作效率,避免意外毁掉生产。


                              1. 安全第一的模板系统

                              创建一组提示模板,将安全性融入到每个请求中:

                              基础设施模板:

                                Act as a Senior Cloud Security Engineer. Generate [RESOURCE_TYPE] for [USE_CASE] following these non-negotiable requirements:


                                Security:
                                - Implement principle of least privilege
                                - Enable encryption at rest and in transit
                                - Use security groups/NACLs with minimal required access
                                - Include WAF rules if web-facing
                                - Enable detailed logging and monitoring
                                Reliability:
                                - Include health checks and auto-scaling
                                - Implement proper retry logic and circuit breakers
                                - Plan for multi-AZ/region deployment
                                - Set appropriate resource limits and requests
                                Compliance:
                                - Add required tags for cost allocation and compliance
                                - Include data classification labels
                                - Ensure GDPR/SOC2 compliance where applicable
                                - Enable audit logging
                                Operations:
                                - Include monitoring and alerting configurations
                                - Plan deployment and rollback strategies
                                - Document environment-specific configurations
                                - Include cost optimization recommendations
                                [YOUR_SPECIFIC_REQUEST]


                                2. 验证流程

                                永远不要发布没有经过以下考验的 AI 生成的代码:

                                  #!/bin/bash
                                  # AI Code Validation Pipeline


                                  echo "Running security scans..."
                                  tfsec . --format json > tfsec_results.json
                                  snyk iac test . --json > snyk_results.json
                                  checkov -f main.tf --framework terraform --output json > checkov_results.json
                                  # Policy validation (Open Policy Agent)
                                  echo "Validating against company policies..."
                                  opa test policies/ --explain fails
                                  # Kubernetes validation (if applicable)
                                  if [[ -f *.yaml ]]; then
                                      echo "Validating Kubernetes manifests..."
                                      kube-score score *.yaml
                                      kubeval *.yaml
                                      kubectl --dry-run=client apply -f .
                                  fi
                                  # Cost estimation
                                  echo "Estimating costs..."
                                  infracost breakdown --path .
                                  # Generate security report
                                  echo "Generating security report..."
                                  python generate_security_report.py
                                  echo "Validation complete. Review reports before proceeding."


                                  3. AI结对编程方法

                                  不要用人工智能来取代你的思考,而要用它来加速你的思考。

                                  良好做法:

                                    设计优先:在纸上勾勒出你的架构

                                    具体提示:要求人工智能在特定约束条件下实现你的设计

                                    批判性地审查:假设人工智能至少犯了 3 个安全错误

                                    快速迭代:使用人工智能探索不同的方法

                                    严格验证:通过自动化安全工具运行所有内容

                                  示例工作流程:

                                    You: "I need a CI/CD pipeline that builds a Node.js app, runs security scans, and deploys to EKS with blue/green deployment"


                                    AI: [Generates basic workflow]
                                    You: "Add Snyk scanning, SAST with SemGrep, image scanning with Trivy, and implement proper RBAC for the EKS deployment"
                                    AI: [Generates enhanced workflow]
                                    You: "Now add proper secret management using AWS Secrets Manager and implement deployment notifications to Slack"
                                    AI: [Final enhanced workflow]
                                    Then: Run through validation pipeline before using


                                    4.紧急制动系统

                                    设置自动护栏,防止危险的人工智能输出进入生产:

                                    GitHub Actions 护栏:

                                      name: AI Code Safety Check
                                      on:
                                        pull_request:
                                          paths:
                                          - '**/*.tf'
                                          - '**/*.yaml'
                                          - '**/*.yml'
                                      jobs:
                                        safety-check:
                                          runs-on: ubuntu-latest
                                          steps:
                                            - uses: actions/checkout@v4
                                            
                                            - name: Scan for Common AI Mistakes
                                              run: |
                                                # Check for overly permissive security groups
                                                if grep -r "0.0.0.0/0" . --include="*.tf"then
                                                  echo "Found overly permissive CIDR blocks"
                                                  exit 1
                                                fi
                                                
                                                # Check for hardcoded secrets
                                                if grep -rE "(password|secret|key).*=.*['\"][^'\"]{8,}" . --include="*.tf" --include="*.yaml"then
                                                  echo "Found potential hardcoded secrets"
                                                  exit 1
                                                fi
                                                
                                                # Check for latest tags in Kubernetes
                                                if grep -r "image:.*:latest" . --include="*.yaml"then
                                                  echo "Found 'latest' image tags"
                                                  exit 1
                                                fi
                                                
                                                # Check for missing resource limits
                                                if grep -A 20 "kind: Deployment" . --include="*.yaml" | grep -L "resources:"then
                                                  echo "Found deployments without resource limits"
                                                  exit 1
                                                fi
                                            
                                            - name: Run tfsec
                                              uses: aquasecurity/tfsec-action@v1.0.0
                                              with:
                                                soft_fail: false


                                      奖励:验证AI输出的工具

                                      不要相信,要验证。以下是每个 DevOps 工程师的 AI 验证工具包中都应该包含的工具:

                                      安全扫描仪

                                        tfsec — Terraform 安全扫描器

                                        Checkov——多语言基础设施安全

                                        Snyk——代码和容器的漏洞扫描

                                        Trivy——容器和文件系统漏洞扫描器

                                        SemGrep — 自定义安全规则的静态分析

                                      Kubernetes 验证器

                                        kube-score ——Kubernetes 对象分析

                                        kubeval — YAML 模式验证

                                        OPA Gatekeeper——政策执行

                                        Falco——运行时安全监控

                                      基础设施验证器

                                        开放策略代理(OPA) ——策略即代码

                                        Sentinel ——Terraform 策略框架(HashiCorp)

                                        Cloud Custodian——云资源策略执行

                                        Infracost——成本估算和预算

                                      AI 生成的 Terraform 的 OPA 策略示例

                                        package terraform.security


                                        # Deny security groups with overly permissive ingress
                                        deny[msg] {
                                            resource := input.resource.aws_security_group[_]
                                            ingress := resource.ingress[_]
                                            "0.0.0.0/0" in ingress.cidr_blocks
                                            msg := sprintf("Security group '%s' has overly permissive ingress rule", [resource.name])
                                        }


                                        # Require encryption for RDS instances
                                        deny[msg] {
                                            resource := input.resource.aws_db_instance[_]
                                            not resource.storage_encrypted
                                            msg := sprintf("RDS instance '%s' must have storage encryption enabled", [resource.identifier])
                                        }


                                        # Require versioned S3 buckets
                                        deny[msg] {
                                            resource := input.resource.aws_s3_bucket[_]
                                            not resource.versioning[_].enabled
                                            msg := sprintf("S3 bucket '%s' must have versioning enabled", [resource.bucket])
                                        }


                                        底线

                                        对于 DevOps 工程师来说,AI 是一个非凡的工具。它能够以比人类更快的速度生成基础设施代码,提出你意想不到的优化建议,并帮助你以闪电般的速度探索新技术。

                                        但它也能比任何人类更快地产生安全漏洞,建议看起来正确但在负载下灾难性地失败的配置,并让你有信心部署你不完全理解的代码。

                                        “人工智能让我的工作效率提高了 10 倍”和“人工智能让我丢了工作”之间的区别可以归结为一件事:将人工智能的输出视为由才华横溢但鲁莽的初级工程师编写的代码。

                                        你不会合并初级成员未经审核的 PR。也不要合并 AI 未经验证的输出。


                                        行动计划

                                          审核您当前的 AI 使用情况——您在没有经过适当审查的情况下部署了哪些内容?

                                          创建安全第一的提示模板——将安全输出设为默认

                                          设置自动验证管道——让工具捕捉你错过的内容

                                          实施紧急制动系统——防患于未然

                                          实践人工智能结对编程方法——用人工智能来加速而不是取代你的思维

                                        记住:我们的目标不是避免使用人工智能,而是在构建不会在凌晨 3 点用生产警报叫醒你的系统时负责任地使用人工智能。

                                        因为归根结底,当生产过程中出现问题时,没有人工智能可以为你承担责任。

                                        下次你发现自己要复制粘贴AI生成的基础架构代码时,请先深呼吸,并将其通过验证管道运行。你未来的自己(以及你的运维团队)会感谢你。


                                        作者丨Zudonu Osomudeya

                                        来源丨网址:https://medium.com/@osomudeyazudonu/youre-using-ai-as-a-devops-engineer-wrong-and-it-s-putting-your-entire-stack-at-risk-ef9a083d8b62

                                        dbaplus社群欢迎广大技术人员投稿,投稿邮箱:editor@dbaplus.cn

                                        阅读原文

                                        跳转微信打开

                                        Fish AI Reader

                                        Fish AI Reader

                                        AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

                                        FishAI

                                        FishAI

                                        鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

                                        联系邮箱 441953276@qq.com

                                        相关标签

                                        AI DevOps 基础设施安全 提示词 错误修复
                                        相关文章