The goal of this task is to enforce cloud governance by implementing Policy as Code (PaC) using HashiCorp Sentinel. Sentinel policies will be used to:
Create a main.tf file to define cloud infrastructure (e.g., EC2, S3, RDS).
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "web" {
ami = "ami-0abcdef1234567890"
instance_type = "t2.micro"
tags = {
Name = "WebServer"
Environment = "Production"
}
}
Define policies in the .sentinel format.
import "tfplan"
allowed_regions = ["us-east-1", "us-west-2"]
main = rule {
all tfplan.resources.aws_instance as _, instances {
all instances as instance {
instance.applied.region in allowed_regions
}
}
}
Purpose: Ensures that EC2 instances are launched only in approved AWS regions.
import "tfplan"
allowed_instance_types = ["t2.micro", "t3.micro"]
main = rule {
all tfplan.resources.aws_instance as _, instances {
all instances as instance {
instance.applied.instance_type in allowed_instance_types
}
}
}
Purpose: Ensures only cost-effective instance types are used.
import "tfplan"
required_tags = ["Environment", "Owner"]
main = rule {
all tfplan.resources.aws_instance as _, instances {
all instances as instance {
all required_tags as tag {
tag in instance.applied.tags
}
}
}
}
Purpose: Ensures every resource has Environment and Owner tags for cost tracking.
.sentinel
policies.Create a Jenkinsfile or GitHub Actions workflow to run Terraform with Sentinel checks.
pipeline {
agent any
stages {
stage('Checkout') {
steps {
git 'https://github.com/user/repo.git'
}
}
stage('Terraform Init') {
steps {
sh 'terraform init'
}
}
stage('Terraform Plan with Sentinel') {
steps {
sh 'terraform plan -out=tfplan'
sh 'terraform show -json tfplan > tfplan.json'
sh 'sentinel apply policy.sentinel tfplan.json'
}
}
stage('Terraform Apply') {
when {
expression {
return env.SENTINEL_CHECK == 'pass'
}
}
steps {
sh 'terraform apply -auto-approve'
}
}
}
}
This project provides a real-world, end-to-end implementation of Policy as Code (PaC) using HashiCorp Sentinel, Terraform, and CI/CD automation. 🚀