Integration GitLab avec l'ecosysteme DevOps 30 min de lecture

Integration Kubernetes et Terraform

Integration Kubernetes

GitLab Agent for Kubernetes

# Installation de l'agent
# 1. Infrastructure > Kubernetes clusters > Connect a cluster
# 2. Creer un agent dans le projet
# 3. Installer via Helm

helm repo add gitlab https://charts.gitlab.io
helm repo update

helm install gitlab-agent gitlab/gitlab-agent \
  --namespace gitlab-agent \
  --create-namespace \
  --set config.token="glagent-xxxxxxxxxx" \
  --set config.kasAddress="wss://kas.gitlab.example.com"

Deploiement Kubernetes dans le pipeline

deploy-k8s:
  stage: deploy
  image:
    name: bitnami/kubectl:latest
    entrypoint: [""]
  script:
    - kubectl config use-context my-group/my-project:my-agent
    - kubectl set image deployment/myapp \
        myapp=$CI_REGISTRY_IMAGE:$CI_COMMIT_TAG \
        --namespace=production
    - kubectl rollout status deployment/myapp --namespace=production
  environment:
    name: production
    kubernetes:
      namespace: production

Integration Terraform

Terraform State dans GitLab

# Backend Terraform utilisant GitLab comme stockage d'etat
terraform {
  backend "http" {
    address        = "https://gitlab.example.com/api/v4/projects/123/terraform/state/production"
    lock_address   = "https://gitlab.example.com/api/v4/projects/123/terraform/state/production/lock"
    unlock_address = "https://gitlab.example.com/api/v4/projects/123/terraform/state/production/lock"
    username       = "gitlab-ci"
    password       = ""    # Utilise $CI_JOB_TOKEN
    lock_method    = "POST"
    unlock_method  = "DELETE"
    retry_wait_min = 5
  }
}

Pipeline Terraform

include:
  - template: Terraform.latest.gitlab-ci.yml

variables:
  TF_ROOT: "terraform/"
  TF_STATE_NAME: "production"
  TF_ADDRESS: "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/terraform/state/${TF_STATE_NAME}"

# Les stages sont automatiquement configures :
# - validate : terraform validate
# - build : terraform plan (artefact sauvegarde)
# - deploy : terraform apply (manuel)

Pipeline custom Terraform

stages:
  - validate
  - plan
  - apply

terraform-validate:
  stage: validate
  image: hashicorp/terraform:1.7
  script:
    - cd terraform/
    - terraform init -backend=false
    - terraform validate
    - terraform fmt -check

terraform-plan:
  stage: plan
  image: hashicorp/terraform:1.7
  script:
    - cd terraform/
    - terraform init
    - terraform plan -out=tfplan
  artifacts:
    paths:
      - terraform/tfplan
  environment:
    name: production
    action: prepare

terraform-apply:
  stage: apply
  image: hashicorp/terraform:1.7
  script:
    - cd terraform/
    - terraform init
    - terraform apply -auto-approve tfplan
  dependencies:
    - terraform-plan
  environment:
    name: production
  when: manual
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
Avantage : Stocker le state Terraform dans GitLab evite de gerer un backend S3/GCS separe et profite du verrouillage integre.