stages: - validate - plan - apply # Cache modules between jobs cache: key: ${CI_COMMIT_REF_SLUG} paths: - .terraform variables: TERRAFORM_VERSION: "1.10.5" TF_STATE_NAME: ${CI_PROJECT_NAME} before_script: - cd terraform - apk add --update curl jq python3 py3-pip - pip install checkov - curl -LO "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip" - unzip "terraform_${TERRAFORM_VERSION}_linux_amd64.zip" -d /usr/local/bin/ - curl -L "https://github.com/aquasecurity/trivy/releases/latest/download/trivy_$(uname -s)_$(uname -m).tar.gz" | tar xz - mv trivy /usr/local/bin/ - curl -s https://raw.githubusercontent.com/aquasecurity/tfsec/master/scripts/install_linux.sh | bash # Validate syntax and formatting terraform-validate: stage: validate image: hashicorp/terraform:${TERRAFORM_VERSION} script: - terraform init -backend=false - terraform validate - terraform fmt -check -recursive only: changes: - "terraform/**/*.tf" # Security check with trivy trivy: stage: validate image: alpine:latest script: - trivy config --format junit --output trivy.test.xml --check-namespaces proxmox . only: changes: - "terraform/**/*.tf" artifacts: reports: junit: "trivy.test.xml" paths: - "trivy.test.xml" # Security check with checkov checkov: stage: validate image: alpine:latest script: - checkov -d . --quiet only: changes: - "terraform/**/*.tf" # Policy validation with conftest policy-check: stage: validate image: alpine:latest script: - terraform init -backend=false - terraform plan -out=tfplan - terraform show -json tfplan > tfplan.json - conftest test tfplan.json -p policies/ only: changes: - "terraform/**/*.tf" - "terraform/policies/**/*.rego" # Create Terraform plan terraform-plan: stage: plan image: hashicorp/terraform:${TERRAFORM_VERSION} script: - terraform init - terraform plan -out=tfplan # Save the plan as an artifact - terraform show -json tfplan > tfplan.json artifacts: paths: - terraform/tfplan - terraform/tfplan.json expire_in: 1 week only: changes: - "terraform/**/*.tf" when: manual needs: - terraform-validate - trivy - checkov - policy-check # Apply the changes terraform-apply: stage: apply image: hashicorp/terraform:${TERRAFORM_VERSION} script: - terraform init - terraform apply -auto-approve tfplan dependencies: - terraform-plan only: changes: - "terraform/**/*.tf" when: manual needs: - terraform-plan