Repository contains examples of policy as code with the use of OPA (Open Policy Agent).
Initialize Terraform:
cd examples/local-file/infra
terraform init
Prepare Terraform plan in JSON format in 2 steps:
terraform plan --out tfplan.binary
terraform show -json tfplan.binary > tfplan.json
or use below command:
terraform plan --out tfplan.binary && terraform show -json tfplan.binary > tfplan.json
Execute Rego policy for generated plan to get final result and score:
opa exec --decision terraform/analysis/allow --bundle ../policy tfplan.json
opa exec --decision terraform/analysis/score --bundle ../policy tfplan.json
or use below command to get full result:
opa exec --decision terraform/analysis --bundle ../policy tfplan.json
In order to execute Sentinel policy, prepare JSON in differet place:
mkdir ../policy/test/terraform_basic
terraform plan --out tfplan.binary && terraform show -json tfplan.binary > ../policy/test/terraform_basic/tfplan.json
terraform plan --out tfplan.binary && terraform show -no-color tfplan.binary > ../policy/test/terraform_basic/tfplan.hcl
and execute Sentinel policy:
cd ../policy
sentinel test terraform_basic.sentinel
- Deploy environment with Localhost, Jenkins, Terraform, Rego and AWS CLI tool installed by Docker Compose:
cd examples/aws/infra
docker build -t jenkins:jcasc .
docker-compose up -d
After opening http://localhost:8080/ and authenticating to Jenkins using login admin
and password admin123
, it can be also checked, that there is already project configured:
- name:
opa-policies
- type of project:
pipeline
- repository - local git:
file:///usr/local/src/opa-policies
- branch:
main
- pipeline:
from SCM
- script path:
examples/aws/infra/Jenkinsfile
- Execute Jenkins pipeline
opa-policies
and verify deplyoment on Jenkins container:
docker exec -it jenkins bash
aws --endpoint-url=http://localstack:4566 s3 ls
aws --endpoint-url=http://localstack:4566 s3 ls s3://localstack-s3-opa-example
- Destroy deployment:
docker exec -it jenkins bash
cd /var/jenkins_home/workspace/opa-policies/examples/aws/infra
terraform apply -auto-approve -destroy
exit
docker compose stop
docker compose rm
- OPA (Open Policy Agent) - Terraform
- Defining OPA Policies
- Validate Infrastructure and Enforce OPA Policies
- Pre-deployment Policy Checks for Terraform using OPA (Open Policy Agent)
- The Rego Playground
- Rego - How Do I Write Policies?
- What Is Policy-as-Code?
- Sentinel - Policy as Code
- What is Policy-as-Code? An Introduction to Open Policy Agent
- AWS Prescriptive Guidance - OPA and Rego
- LocalStack:
- Jenkins, Jenkins as a code, Jenkins Job DSL:
- OPA:
- Terraform plugin for Jenkins