How to Use GitHub Copilot for Infrastructure Code: Terraform, Ansible, and K8s Manifests

Posted: | Last updated: | 4 minute read

GitHub Copilot for Infrastructure Code

GitHub Copilot is not just for application code. It is remarkably effective at generating infrastructure code — Terraform modules, Ansible playbooks, Kubernetes manifests, Helm charts, and CI/CD pipelines. The key is knowing how to prompt it effectively. Infrastructure code is highly declarative and pattern-heavy, which is exactly what LLMs excel at.

Why Copilot Works Well for Infrastructure Code

Infrastructure code is:

  1. Declarative — you describe what you want, not how to do it
  2. Pattern-heavy — an S3 bucket looks like an S3 bucket everywhere
  3. Well-documented — Terraform providers, K8s API docs are in the training data
  4. Repetitive — similar resources with slight variations

These properties make infrastructure code an ideal fit for AI code generation.

Terraform with Copilot

Technique 1: Comment-Driven Generation

Write a comment describing what you want. Copilot generates the resource.

# Create a VPC with CIDR 10.0.0.0/16, DNS support enabled,
# and 3 public subnets across availability zones

Copilot generates:

resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = "${var.project}-vpc"
  }
}

resource "aws_subnet" "public" {
  count             = 3
  vpc_id            = aws_vpc.main.id
  cidr_block        = cidrsubnet(aws_vpc.main.cidr_block, 8, count.index)
  availability_zone = data.aws_availability_zones.available.names[count.index]

  map_public_ip_on_launch = true

  tags = {
    Name = "${var.project}-public-${count.index + 1}"
  }
}

Technique 2: Variable File First

Create variables.tf first. Copilot uses variable names to infer intent in main.tf.

# variables.tf
variable "project" { type = string }
variable "environment" { type = string }
variable "db_engine" { default = "postgres" }
variable "db_instance_class" { default = "db.t3.medium" }
variable "db_allocated_storage" { default = 50 }
variable "db_multi_az" { default = true }

When you open main.tf and start typing resource "aws_db, Copilot generates a complete RDS instance using your variable names.

Technique 3: Module Scaffolding

# modules/ecs-service/main.tf
# ECS Fargate service with ALB target group, task definition,
# CloudWatch log group, and auto-scaling policy

Copilot generates the full module with all four resources, wired together correctly.

Tips for Terraform

  • Name your files descriptively. networking.tf prompts better network resources than main.tf.
  • Keep provider and backend configured. Copilot infers the cloud provider from your config.
  • Accept, then refine. Generate the skeleton, then adjust values and add lifecycle rules.
  • Use Copilot Chat for complex logic. Ask: “Write a for_each that creates one S3 bucket per team with different lifecycle policies.”

Ansible with Copilot

Playbook Generation

# playbook.yml
# Install and configure Nginx as a reverse proxy for a Node.js
# application running on port 3000. Enable SSL with Let's Encrypt.
---

Copilot generates:

- name: Configure Nginx reverse proxy with SSL
  hosts: webservers
  become: true
  vars:
    domain: example.com
    backend_port: 3000

  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: present
        update_cache: true

    - name: Install Certbot
      apt:
        name:
          - certbot
          - python3-certbot-nginx
        state: present

    - name: Create Nginx config
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/sites-available/
      notify: Reload Nginx

    - name: Enable site
      file:
        src: /etc/nginx/sites-available/
        dest: /etc/nginx/sites-enabled/
        state: link
      notify: Reload Nginx

    - name: Obtain SSL certificate
      command: >
        certbot --nginx -d 
        --non-interactive --agree-tos
        --email admin@
      args:
        creates: /etc/letsencrypt/live//fullchain.pem

  handlers:
    - name: Reload Nginx
      service:
        name: nginx
        state: reloaded

Role Generation

Create the directory structure first:

roles/
  docker/
    tasks/
      main.yml    ← start typing here
    handlers/
    defaults/
    templates/

Copilot infers from the directory name (docker) and generates installation tasks.

Kubernetes Manifests with Copilot

Deployment + Service

# k8s/api-deployment.yaml
# Deployment for a Node.js API with 3 replicas, resource limits,
# readiness/liveness probes on /health, and anti-affinity rules

Copilot generates a complete Deployment with:

  • Container spec with resource requests/limits
  • Readiness and liveness probes
  • Pod anti-affinity for high availability
  • Environment variables from ConfigMap/Secret references

Copilot Chat for Complex K8s

Ask Copilot Chat:

“Generate a Kubernetes CronJob that runs a database backup script every night at 2 AM, uses a specific service account, mounts a PVC for backup storage, and has a TTL of 24 hours for completed jobs.”

The response includes the CronJob spec with schedule, volume mounts, service account, ttlSecondsAfterFinished, and backoffLimit.

Helm Charts with Copilot

# templates/deployment.yaml
# Helm templated deployment using values for image, replicas,
# resources, env vars from values.yaml

Copilot generates Helm-templated YAML with {{ .Values.image.repository }}, conditionals, and range loops.

CI/CD Pipelines

# .github/workflows/deploy.yml
# GitHub Actions workflow that:
# 1. Runs tests on PR
# 2. Builds and pushes Docker image on merge to main
# 3. Deploys to ECS Fargate in production
# 4. Sends Slack notification on success/failure

Copilot generates the complete multi-job workflow.

Best Practices

  1. Always review generated code. Copilot generates plausible code, not guaranteed-correct code. Check security groups, IAM policies, and resource sizing.
  2. Use comments as prompts. Detailed comments produce better results. “Create an S3 bucket” gives a basic bucket. “Create an S3 bucket with versioning, encryption, lifecycle policy, and public access block” gives a production-ready bucket.
  3. Validate with tools. Run terraform validate, ansible-lint, kubeval on generated code.
  4. Do not trust IAM policies blindly. Copilot may generate overly permissive policies (* actions). Always scope to least privilege.
  5. Use Copilot Chat for explanations. Highlight a Terraform resource and ask “What does this do?” or “Is this secure?”

Limitations

  • No cloud state awareness. Copilot does not know what resources exist in your AWS account.
  • May use outdated syntax. Terraform provider APIs change. Verify against current docs.
  • Security review required. Generated IAM policies, security groups, and RBAC rules need manual review.
  • No cost awareness. Copilot does not know pricing. It may suggest expensive instance types.

Conclusion

GitHub Copilot accelerates infrastructure code writing by 2-3x. The key is treating it as a knowledgeable pair programmer, not an autonomous agent. Write descriptive comments, provide context through file names and variable definitions, generate the skeleton, and then review and refine. For Terraform, Ansible, and Kubernetes — all highly declarative and pattern-based — Copilot is an excellent productivity tool.


Related posts: