|
| 1 | +# This policy is an example of using a Data Source in Sentinel evaluation |
| 2 | +# It restricts the creation of EC2 instances based on "Env" tag value |
| 3 | +# The allowable value of the "Env" tag is obtained from an aws_subnet Datasource |
| 4 | +# The Env tag from EC2 must match the Env tag of aws_subnet for the policy to pass. |
| 5 | + |
| 6 | +import "tfplan" |
| 7 | + |
| 8 | +# Get all aws_instance resources from all modules |
| 9 | +get_aws_instances = func() { |
| 10 | + aws_instances = [] |
| 11 | + for tfplan.module_paths as path { |
| 12 | + aws_instances += values(tfplan.module(path).resources.aws_instance) else [] |
| 13 | + } |
| 14 | + return aws_instances |
| 15 | +} |
| 16 | + |
| 17 | +aws_instances = get_aws_instances() |
| 18 | + |
| 19 | +# Search for Env tag value in aws_subnet |
| 20 | +get_subnet_env = func() { |
| 21 | + # Get all aws_subnet Data Sources |
| 22 | + aws_subnets = [] |
| 23 | + for tfplan.module_paths as path { |
| 24 | + aws_subnets += values(tfplan.state.module(path).data.aws_subnet) else [] |
| 25 | + } |
| 26 | + |
| 27 | + # Iterate through each subnet and return first Env tag value found (if any) |
| 28 | + for aws_subnets as _, subnets { |
| 29 | + for subnets as index, subnet { |
| 30 | + env_tag = subnet.attr.tags["Env"] |
| 31 | + if length(env_tag) >= 0 { |
| 32 | + print("Using subnet environment tag:", env_tag) |
| 33 | + return env_tag |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + # Return undefined if there were no aws_subnet or none with Env tag. |
| 39 | + return undefined |
| 40 | +} |
| 41 | + |
| 42 | +# Store aws_subnet Env tag value as a variable |
| 43 | +aws_subnet_env_tag = get_subnet_env() |
| 44 | + |
| 45 | +#Ensure Env tag from each aws_instance matches that of aws_subnet |
| 46 | +validate_vm_tags_from_subnet = rule { |
| 47 | + all aws_instances as _, instances { |
| 48 | + all instances as index, ec2 { |
| 49 | + ec2.applied.tags["Env"] == aws_subnet_env_tag |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +main = rule { |
| 55 | + (validate_vm_tags_from_subnet) else true |
| 56 | +} |
0 commit comments