#!/bin/bash # Security Check Script for Terraform # This script runs all security checks on your Terraform configuration set -e # Colors for output GREEN='\033[0;32m' RED='\033[0;31m' YELLOW='\033[0;33m' NC='\033[0m' # No Color echo -e "${YELLOW}Starting Terraform Security Checks...${NC}" # Check if we're in the terraform directory if [ ! -f "main.tf" ]; then echo -e "${RED}Error: Please run this script from the terraform directory${NC}" exit 1 fi # Function to check if a command exists command_exists() { command -v "$1" >/dev/null 2>&1 } # Check for required tools echo -e "\n${YELLOW}Checking for required tools...${NC}" MISSING_TOOLS=0 if ! command_exists terraform; then echo -e "${RED}❌ terraform not found. Please install terraform.${NC}" MISSING_TOOLS=1 fi if ! command_exists conftest; then echo -e "${RED}❌ conftest not found. Please install conftest.${NC}" echo " curl -L https://github.com/open-policy-agent/conftest/releases/download/v0.42.1/conftest_0.42.1_Linux_x86_64.tar.gz | tar xz" echo " sudo mv conftest /usr/local/bin/" MISSING_TOOLS=1 fi if [ $MISSING_TOOLS -eq 1 ]; then echo -e "${RED}Please install missing tools before running security checks.${NC}" exit 1 fi echo -e "${GREEN}✅ All required tools are installed.${NC}" # Step 1: Terraform validation echo -e "\n${YELLOW}Running Terraform validation...${NC}" terraform validate TERRAFORM_EXIT=$? if [ $? -eq 0 ]; then echo -e "${GREEN}✅ Terraform validation passed.${NC}" else echo -e "${RED}❌ Terraform validation failed.${NC}" exit 1 fi echo -e "\n${YELLOW}Generating Terraform plan...${NC}" terraform plan -var-file="variables.tfvars" -out=tfplan terraform show -json tfplan | jq > tfplan.json echo -e "\n${YELLOW}Running OPA policy checks...${NC}" if [ -d "policy" ]; then conftest test tfplan.json -p policy/ CONFTEST_EXIT=$? if [ $CONFTEST_EXIT -eq 0 ]; then echo -e "${GREEN}✅ OPA policy checks passed.${NC}" else echo -e "${RED}❌ OPA policy checks found issues.${NC}" # We continue execution to show summary fi else echo -e "${RED}❌ Policies directory not found. Skipping OPA checks.${NC}" CONFTEST_EXIT=1 fi # Summary echo -e "\n${YELLOW}Security Check Summary:${NC}" echo -e "Terraform Validation: $([ $? -eq 0 ] && echo -e "${GREEN}PASSED${NC}" || echo -e "${RED}FAILED${NC}")" echo -e "OPA Policy Checks: $([ $CONFTEST_EXIT -eq 0 ] && echo -e "${GREEN}PASSED${NC}" || echo -e "${RED}FAILED${NC}")" # Final result if [ $CONFTEST_EXIT -eq 0 ] && [ $TERRAFORM_EXIT -eq 0 ]; then echo -e "\n${GREEN}All security checks passed!${NC}" exit 0 else echo -e "\n${RED}Some security checks failed. Please address the issues before proceeding.${NC}" exit 1 fi