Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 138 additions & 0 deletions .sg/DOCUMENTATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# Documentation: test-terraform-cli

## 1. Overview

This stack manages one Azure resource: a **subscription-scoped Azure Policy assignment** (`SecurityCenterBuiltIn`), the default Microsoft Defender for Cloud (ASC Default) policy set on subscription `618c8e34-b87b-44e8-bb3a-b2de95df60ed`.

The workflow was:

1. Code was generated from discovered cloud resources (`azurerm_policy_assignment`, ID `SecurityCenterBuiltIn`).
2. The existing resource was imported into Terraform state via `imports.sh`.
3. The configuration was reconciled until `plan` reported no changes.

Final reconciliation result: **No changes. Your infrastructure matches the configuration.**

## 2. Resources

| Terraform address | Provider type | Real-world name / ID | Purpose |
|---|---|---|---|
| `module.policy_assignment["asc_default"].azurerm_policy_assignment.this` | `azurerm_policy_assignment` | Name `SecurityCenterBuiltIn`; ID `/subscriptions/618c8e34-b87b-44e8-bb3a-b2de95df60ed/providers/Microsoft.Authorization/policyAssignments/SecurityCenterBuiltIn` | Assigns the Azure built-in policy set `1f3afdf9-d0c9-4c3d-847f-89da613e70a8` (ASC Default, audit policies) to the subscription. |

Only one resource exists in the root configuration. The `policy_assignment` module is instantiated once, with `for_each` key `asc_default`.

## 3. Module structure

### Root (`./`)

- `main.tf`: one `module "policy_assignment"` block using `for_each = var.policy_assignments` and passing `name`, `scope`, `policy_definition_id`, `description`, `display_name` from each map entry.
- `variables.tf`: declares `policy_assignments` (a `map(object)`, default `{}`).
- `outputs.tf`: present but empty. No outputs are exported.
- `versions.tf`: requires provider `hashicorp/azurerm` `~> 2.99`.
- `providers.tf`: configures `azurerm` with `skip_provider_registration = true` and an empty `features {}` block.

### `modules/policy_assignment/`

- `main.tf`: a single `azurerm_policy_assignment` resource named `this`, with arguments taken directly from the module variables.
- `variables.tf`: `name`, `scope`, `policy_definition_id` (required strings); `description`, `display_name` (optional strings, default `null`).
- `outputs.tf`: output `id` = `azurerm_policy_assignment.this.id`.

### External modules

No external (`git::`) modules are called from the root configuration. The discovery metadata lists a `test-terraform-cli` module (`git::https://github.com/StackGuardian/test-terraform-cli.git?ref=main`) that covers `null_resource`. The root code does not reference it, and no `null_resource` exists in this stack. It is not used and is documented here only for completeness.

## 4. How import works

`imports.sh` runs one import command:

```sh
"$1" import -var-file environments/sg.tfvars \
'module.policy_assignment["asc_default"].azurerm_policy_assignment.this' \
'/subscriptions/618c8e34-b87b-44e8-bb3a-b2de95df60ed/providers/Microsoft.Authorization/policyAssignments/SecurityCenterBuiltIn'
```

- `$1` is the IaC binary path (for example, `tofu`). The script takes it as an argument.
- The first argument after `import` is the module-qualified Terraform address. The second is the Azure ARM resource ID. Use the full ARM ID, not the short name.
- The script was run once to populate state. It does not need to run again while state is intact.

**To re-import the resource if state is lost** (after `init`, with the same variables in place):

```sh
tofu import -var-file=environments/sg.tfvars \
'module.policy_assignment["asc_default"].azurerm_policy_assignment.this' \
'/subscriptions/618c8e34-b87b-44e8-bb3a-b2de95df60ed/providers/Microsoft.Authorization/policyAssignments/SecurityCenterBuiltIn'
```

Then run `plan` to confirm no changes.

## 5. How to use the code

Run these commands from the working directory. Replace `tofu` with your binary path if needed.

```sh
# 1. Initialise providers and modules
tofu init

# 2. Preview changes using the shipped variable values
tofu plan -var-file=environments/sg.tfvars

# 3. Apply changes
tofu apply -var-file=environments/sg.tfvars
```

### Targeting another environment (for example, dev → prod)

No `.tf` edits are required:

1. Copy `environments/sg.tfvars` to a new file, for example `environments/prod.tfvars`.
2. Edit the values in the copy. The key fields are `policy_assignments.<key>.name`, `scope` (subscription ID), `policy_definition_id`, `description`, and `display_name`. The map key (for example, `asc_default`) becomes the `for_each` key in the state address.
3. Plan against the new file:

```sh
tofu plan -var-file=environments/prod.tfvars
```

4. Note that the import in `imports.sh` targets the `asc_default` address and the `sg` subscription ID. For a different environment, the existing state is not reused. Import the target resource with the matching address and ARM ID before planning, or the plan will propose creating a new assignment.

## 6. Variables

| Variable | Type | Controls | Sensitive? |
|---|---|---|---|
| `policy_assignments` | `map(object({ name, scope, policy_definition_id, description?, display_name? }))` | The set of policy assignments to create. Each map key becomes a `for_each` instance (`module.policy_assignment["<key>"]`). | No |

Fields of each entry:

- `name`: the policy assignment name in Azure (`SecurityCenterBuiltIn`).
- `scope`: the ARM scope to assign to (`/subscriptions/618c8e34-…`).
- `policy_definition_id`: the policy or policy set definition ID (`/providers/Microsoft.Authorization/policySetDefinitions/1f3afdf9-…`).
- `description`: optional text. Set in `sg.tfvars`.
- `display_name`: optional label. Set in `sg.tfvars`.

**Secrets:** no variable in this configuration is marked `sensitive`. The shipped `environments/sg.tfvars` contains no secret values, and no `secrets.auto.tfvars` is required. If you add a sensitive variable later, provide its value in a `secrets.auto.tfvars` file or with `-var` before planning. Do not commit that file.

## 7. Infrastructure graph

```
subscription 618c8e34-b87b-44e8-bb3a-b2de95df60ed (scope, not managed by this stack)
└── policySetDefinitions/1f3afdf9-… (policy_definition_id, referenced, not managed)
▲
│ referenced by
│
module.policy_assignment["asc_default"] (module.policy_assignment, for_each key "asc_default")
└── azurerm_policy_assignment.this (name "SecurityCenterBuiltIn", scope = subscription)
```

There are no dependencies between managed resources. The only reference is that the assignment points at the subscription scope and at the policy set definition. Both of these are external to the stack.

## 8. Notable decisions & caveats

- **Provider version pinned to `~> 2.99`.** The `azurerm_policy_assignment` resource was removed in azurerm 3.0 and later. Do not upgrade the provider without rewriting this resource.
- **`skip_provider_registration = true`** is set in `providers.tf`. Automatic resource-provider registration returned HTTP 403 during discovery, so it is disabled.
- **Import ID format.** The import uses the full ARM resource ID, not the short name `SecurityCenterBuiltIn`.
- **Module wrapping.** The single resource is wrapped in `modules/policy_assignment` and called with `for_each` over `var.policy_assignments`. This keeps the stack extensible to more assignments, at the cost of longer state addresses.
- **Empty root outputs.** `outputs.tf` is empty. The module's `id` output is not surfaced at the root.
- **No `lifecycle { ignore_changes }` blocks.** Every attribute is managed. Any attribute changed out-of-band will show up as drift in `plan`.
- **Omitted computed attributes.** Only configurable arguments are declared. Read-only attributes (for example, the assignment `identity` and `location` when not set) are not modelled. Azure may return values for them that are not reflected in code.
- **Descriptive text is copied from Azure.** The `description` value in `sg.tfvars` is the default ASC text as returned by Azure, including the URL. Editing it in code causes an in-place update.
- **Local state file present.** `terraform.tfstate` is in the working directory. Treat it as sensitive and keep it out of version control unless you use a remote backend.
- **Stale discovery metadata.** The module index in the discovery data lists an unrelated `null_resource` module. It is not used by this stack (see section 3).
- **Current drift:** none. The final reconciliation reported no changes.
20 changes: 20 additions & 0 deletions .terraform.lock.hcl

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions environments/sg.tfvars
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
policy_assignments = {
asc_default = {
name = "SecurityCenterBuiltIn"
scope = "/subscriptions/618c8e34-b87b-44e8-bb3a-b2de95df60ed"
policy_definition_id = "/providers/Microsoft.Authorization/policySetDefinitions/1f3afdf9-d0c9-4c3d-847f-89da613e70a8"
description = "This is the default set of policies monitored by Azure Security Center. It was automatically assigned as part of onboarding to Security Center. The default assignment contains only audit policies. For more information please visit https://aka.ms/ascpolicies"
display_name = "ASC Default (subscription: 618c8e34-b87b-44e8-bb3a-b2de95df60ed)"
}
}
3 changes: 3 additions & 0 deletions imports.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh
set -e
"$1" import -var-file environments/sg.tfvars 'module.policy_assignment["asc_default"].azurerm_policy_assignment.this' '/subscriptions/618c8e34-b87b-44e8-bb3a-b2de95df60ed/providers/Microsoft.Authorization/policyAssignments/SecurityCenterBuiltIn'
152 changes: 9 additions & 143 deletions main.tf
Original file line number Diff line number Diff line change
@@ -1,144 +1,10 @@
module "stackguardian_workflow_group" {
for_each = toset(var.workflow_groups)
source = "./stackguardian_workflow_group"
workflow_group_name = each.value
}

locals {
aws_provider_region = try([
for connector in values(var.cloud_connectors) : coalesce(connector.aws_region, "eu-central-1")
if contains(["AWS_STATIC", "AWS_RBAC", "AWS_OIDC"], connector.kind)
][0], "eu-central-1")
has_gcp_connector = anytrue([for connector in values(var.cloud_connectors) : connector.kind == "GCP_OIDC"])
}

# Terraform 1.5 cannot express cross-variable validation. This resource makes
# collection-wide violations hard plan failures rather than advisory checks.
resource "terraform_data" "validate_onboarding" {
input = {
cloud_connector_keys = keys(var.cloud_connectors)
vcs_connector_keys = nonsensitive(keys(var.vcs_connectors))
}

lifecycle {
precondition {
condition = length(setintersection(toset(keys(var.cloud_connectors)), toset(nonsensitive(keys(var.vcs_connectors))))) == 0
error_message = "cloud_connectors and vcs_connectors must not use the same key."
}
}
}

module "aws_rbac" {
for_each = { for name, connector in var.cloud_connectors : name => connector if connector.kind == "AWS_RBAC" }

source = "./aws_rbac"

iam_role_name = each.value.iam_role_name
role_external_id = each.value.aws_external_id
policy_arn = coalesce(each.value.policy_arn, "arn:aws:iam::aws:policy/ReadOnlyAccess")
trusted_account_ids = coalesce(each.value.trusted_account_ids, ["476299211833", "163602625436"])
}

module "aws_static" {
for_each = { for name, connector in var.cloud_connectors : name => connector if connector.kind == "AWS_STATIC" }

source = "./aws_static"

aws_region = coalesce(each.value.aws_region, "eu-central-1")
iam_user = coalesce(each.value.iam_user_name, each.key)
allow_static_credentials = each.value.allow_static_credentials
}

module "aws_oidc" {
for_each = { for name, connector in var.cloud_connectors : name => connector if connector.kind == "AWS_OIDC" }

source = "./aws_oidc"

aws_region = coalesce(each.value.aws_region, "eu-central-1")
iam_role_name = each.value.iam_role_name
stackguardian_org_name = var.stackguardian_org_name
policy_arn = coalesce(each.value.policy_arn, "arn:aws:iam::aws:policy/ReadOnlyAccess")
}

module "azure_oidc" {
for_each = { for name, connector in var.cloud_connectors : name => connector if connector.kind == "AZURE_OIDC" }

source = "./azure_oidc"

subscription_id = each.value.azure_subscription_id
tenant_id = each.value.azure_tenant_id
application_display_name = coalesce(each.value.application_display_name, each.key)
stackguardian_org_name = var.stackguardian_org_name
role_definition_name = coalesce(each.value.role_definition_name, "Contributor")
}

module "azure_static" {
for_each = { for name, connector in var.cloud_connectors : name => connector if connector.kind == "AZURE_STATIC" }

source = "./azure_static"

subscription_id = each.value.azure_subscription_id
tenant_id = each.value.azure_tenant_id
application_display_name = coalesce(each.value.application_display_name, each.key)
role_definition_name = coalesce(each.value.role_definition_name, "Contributor")
allow_static_credentials = each.value.allow_static_credentials
}

module "gcp_oidc" {
for_each = { for name, connector in var.cloud_connectors : name => connector if connector.kind == "GCP_OIDC" }

source = "./gcp_oidc"

project_id = each.value.gcp_project_id
stackguardian_org_name = var.stackguardian_org_name
service_account_id = each.value.gcp_service_account_id
workload_identity_pool_id = each.value.gcp_workload_pool_id
workload_identity_pool_provider_id = each.value.gcp_provider_id
workload_identity_pool_display_name = each.key
project_role = coalesce(each.value.gcp_project_role, "roles/owner")
}

module "stackguardian_connector_cloud" {
for_each = var.cloud_connectors

source = "./stackguardian_connector_cloud"
connector_name = each.key
connector_kind = each.value.kind
allow_static_credentials = coalesce(each.value.allow_static_credentials, false)
aws_access_key_id = each.value.kind == "AWS_STATIC" ? module.aws_static[each.key].access_key_id : null
aws_secret_access_key = each.value.kind == "AWS_STATIC" ? module.aws_static[each.key].secret_access_key : null
aws_region = each.value.kind == "AWS_STATIC" ? coalesce(each.value.aws_region, "eu-central-1") : null
azure_tenant_id = contains(["AZURE_STATIC", "AZURE_OIDC"], each.value.kind) ? each.value.azure_tenant_id : null
azure_subscription_id = contains(["AZURE_STATIC", "AZURE_OIDC"], each.value.kind) ? each.value.azure_subscription_id : null
azure_client_id = contains(["AZURE_STATIC", "AZURE_OIDC"], each.value.kind) ? (each.value.kind == "AZURE_STATIC" ? module.azure_static[each.key].client_id : module.azure_oidc[each.key].client_id) : null
azure_client_secret = each.value.kind == "AZURE_STATIC" ? module.azure_static[each.key].client_secret_value : null
aws_role_arn = each.value.kind == "AWS_RBAC" ? module.aws_rbac[each.key].iam_role_arn : each.value.kind == "AWS_OIDC" ? module.aws_oidc[each.key].oidc_role_arn : null
aws_external_id = each.value.kind == "AWS_RBAC" ? each.value.aws_external_id : null
gcp_config_file_content = each.value.kind == "GCP_OIDC" ? module.gcp_oidc[each.key].external_account_config : null
}

module "stackguardian_connector_vcs" {
source = "./stackguardian_connector_vcs"
vcs_connectors = var.vcs_connectors
}

module "stackguardian_role" {
for_each = var.roles

source = "./stackguardian_role"
org_name = var.stackguardian_org_name
role_name = each.key
workflow_groups = [for name in each.value.workflow_groups : module.stackguardian_workflow_group[name].workflow_groups]
cloud_connectors = [for name in each.value.cloud_connectors : module.stackguardian_connector_cloud[name].connector_name]
vcs_connectors = [for name in each.value.vcs_connectors : nonsensitive(module.stackguardian_connector_vcs.connector_vcs[index(nonsensitive(keys(var.vcs_connectors)), name)])]
template_list = each.value.template_list
}

module "stackguardian_role_assignment" {
for_each = var.subjects

source = "./stackguardian_role_assignment"
roles = [for name in each.value.roles : module.stackguardian_role[name].role]
subject = each.key
entity_type = each.value.entity_type
module "policy_assignment" {
source = "./modules/policy_assignment"
for_each = var.policy_assignments

name = each.value.name
scope = each.value.scope
policy_definition_id = each.value.policy_definition_id
description = each.value.description
display_name = each.value.display_name
}
7 changes: 7 additions & 0 deletions modules/policy_assignment/main.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
resource "azurerm_policy_assignment" "this" {
name = var.name
scope = var.scope
policy_definition_id = var.policy_definition_id
description = var.description
display_name = var.display_name
}
3 changes: 3 additions & 0 deletions modules/policy_assignment/outputs.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
output "id" {
value = azurerm_policy_assignment.this.id
}
21 changes: 21 additions & 0 deletions modules/policy_assignment/variables.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
variable "name" {
type = string
}

variable "scope" {
type = string
}

variable "policy_definition_id" {
type = string
}

variable "description" {
type = string
default = null
}

variable "display_name" {
type = string
default = null
}
9 changes: 0 additions & 9 deletions outputs.tf
Original file line number Diff line number Diff line change
@@ -1,9 +0,0 @@
output "role_permissions" {
description = "Generated permission documents keyed by role name."
value = { for name, role in module.stackguardian_role : name => role.allowed_permissions }
}

output "subject_roles" {
description = "Assigned role names keyed by subject."
value = { for subject, assignment in module.stackguardian_role_assignment : subject => assignment.roles }
}
4 changes: 4 additions & 0 deletions providers.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
provider "azurerm" {
skip_provider_registration = true
features {}
}
Loading
Loading