diff --git a/.github/workflows/plan.yml b/.github/workflows/plan.yml index d3f9e81..2084a6e 100644 --- a/.github/workflows/plan.yml +++ b/.github/workflows/plan.yml @@ -46,9 +46,20 @@ jobs: - name: Terraform Format run: terraform fmt -check - # Generates an execution plan for Terraform + # Terraform Plan - name: Terraform Plan - run: terraform plan -input=false + id: plan + run: | + terraform plan -out=plan.tfplan + terraform show -json plan.tfplan > /tmp/plan.json + cat /tmp/plan.json - - name: View Terraform Plan - run: terraform plan -no-color -json + - name: Setup OPA + uses: open-policy-agent/setup-opa@v2 + with: + version: latest + + - name: Run OPA Tests + run: | + opaout=$(opa eval --data ../policies/plan.rego --input /tmp/plan.json "data.terraform.deny" | jq -r '.result[].expressions[].value[]') + [ -z "$opaout" ] && exit 0 || echo "$opaout" && gh pr comment ${{ github.event.pull_request.number }} --body "### $opaout" && exit 1 diff --git a/opa b/opa new file mode 100755 index 0000000..ce58033 Binary files /dev/null and b/opa differ diff --git a/policies/plan.rego b/policies/plan.rego new file mode 100644 index 0000000..21f17b5 --- /dev/null +++ b/policies/plan.rego @@ -0,0 +1,13 @@ +package terraform + +import future.keywords.in + +allowed_instance_types := {"t3.micro", "t3.small"} + +deny[msg] { + some resource in input.resource_changes + resource.type == "aws_instance" + instance_type := resource.change.after.instance_type + not instance_type in allowed_instance_types + msg := sprintf("AWS instance type '%s' is not allowed. Only 't3.micro' or 't3.small' are permitted.", [instance_type]) +} \ No newline at end of file