Terraform on SAP BTP – Best Practices & Conventions
Core Principles
Keep Terraform code minimal, modular, repeatable, secure, and auditable.
Always version control Terraform HCL and never version control generated state.
Security
Mandatory:
- Use the latest stable Terraform CLI and provider versions; upgrade proactively for security patches.
- Do NOT commit secrets, credentials, certificates, Terraform state, or plan output artifacts.
- Mark all secret variables and outputs as
sensitive = true.
- Prefer ephemeral / write‑only provider auth (Terraform >= 1.11) so secrets never persist in state.
- Minimize sensitive outputs; emit only what downstream automation truly needs.
- Continuously scan with
tfsec, trivy, checkov (pick at least one) in CI.
- Periodically review provider credentials, rotate keys, and enable MFA where supported.
Modularity
Structure for clarity and speed:
- Split by logical domain (e.g., entitlements, service instances) – NOT by environment.
- Use modules for reusable multi‑resource patterns only; avoid single‑resource wrapper modules.
- Keep module hierarchy shallow; avoid deep nesting and circular dependencies.
- Expose only essential cross‑module data via
outputs (mark sensitive when required).
Maintainability
Aim for explicit > implicit.
- Comment WHY, not WHAT; avoid restating obvious resource attributes.
- Parameterize (variables) instead of hard‑coding; provide defaults only when sensible.
- Prefer data sources for external existing infra; never for resources just created in same root – use outputs.
- Avoid data sources in generic reusable modules; require inputs instead.
- Remove unused / slow data sources; they degrade plan time.
- Use
locals for derived or repeated expressions to centralize logic.
Style & Formatting
General
- Descriptive, consistent names for resources, variables, outputs.
- snake_case for variables & locals.
- 2 spaces indentation; run
terraform fmt -recursive.
Layout & Files
Recommended structure:
my-sap-btp-app/
├── infra/ # Root module
│ ├── main.tf # Core resources (split by domain when large)
│ ├── variables.tf # Inputs
│ ├── outputs.tf # Outputs
│ ├── provider.tf # Provider config(s)
│ ├── locals.tf # Local/derived values
│ └── environments/ # Environment var files only
│ ├── dev.tfvars
│ ├── test.tfvars
│ └── prod.tfvars
├── .github/workflows/ # CI/CD (if GitHub)
└── README.md # Documentation
Rules:
- Do NOT create separate branches/repos/folders per environment (antipattern).
- Keep environment drift minimal; encode differences in *.tfvars files only.
- Split oversized
main.tf / variables.tf into logically named fragments (e.g., main_services.tf, variables_services.tf).
Keep naming consistent.
Resource Block Organization
Order (top → bottom): optional depends_on, then count/for_each, then attributes, finally lifecycle.
- Use
depends_on ONLY when Terraform cannot infer dependency (e.g., data source needs entitlement).
- Use
count for optional single resource; for_each for multiple instances keyed by a map for stable addresses.
- Group attributes: required first, then optional; blank lines between logical sections.
- Alphabetize within a section for faster scanning.
Variables
- Every variable: explicit
type, non‑empty description.
- Prefer concrete types (
object, map(string), etc.) over any.
- Avoid null defaults for collections; use empty lists/maps instead.
Locals
- Centralize computed or repeated expressions.
- Group related values into object locals for cohesion.
Outputs
- Expose only what downstream modules/automation consume.
- Mark secrets
sensitive = true.
- Always give a clear
description.
Formatting & Linting
- Run
terraform fmt -recursive (required in CI).
- Enforce
tflint (and optionally terraform validate) in pre‑commit / CI.
Documentation
Mandatory:
description + type on all variables & outputs.
- A concise root
README.md: purpose, prerequisites, auth model, usage (init/plan/apply), testing, rollback.
- Generate module docs with
terraform-docs (add to CI if possible).
- Comments only where they clarify non-obvious decisions or constraints.
State Management
- Use a remote backend supporting locking (e.g., Terraform Cloud, AWS S3, GCS, Azure Storage). Avoid SAP BTP Object Store (insufficient capabilities for reliable locking & security).
- NEVER commit
*.tfstate or backups.
- Encrypt state at rest & in transit; restrict access by principle of least privilege.
Validation
- Run
terraform validate (syntax & internal checks) before committing.
- Confirm with user before
terraform plan (requires auth & global account subdomain). Provide auth via env vars or tfvars; NEVER inline secrets in provider blocks.
- Test in non‑prod first; ensure idempotent applies.
Testing
- Use Terraform test framework (
*.tftest.hcl) for module logic & invariants.
- Cover success & failure paths; keep tests stateless/idempotent.
- Prefer mocking external data sources where feasible.
SAP BTP Provider Specifics
Guidelines:
- Resolve service plan IDs using
data "btp_subaccount_service_plan" and reference serviceplan_id from that data source.
Example:
data "btp_subaccount_service_plan" "example" {
subaccount_id = var.subaccount_id
service_name = "your_service_name"
plan_name = "your_plan_name"
}
resource "btp_subaccount_service_instance" "example" {
subaccount_id = var.subaccount_id
serviceplan_id = data.btp_subaccount_service_plan.example.id
name = "my-example-instance"
}
Explicit dependencies (provider cannot infer):
resource "btp_subaccount_entitlement" "example" {
subaccount_id = var.subaccount_id
service_name = "your_service_name"
plan_name = "your_plan_name"
}
data "btp_subaccount_service_plan" "example" {
subaccount_id = var.subaccount_id
service_name = "your_service_name"
plan_name = "your_plan_name"
depends_on = [btp_subaccount_entitlement.example]
}
Subscriptions also depend on entitlements; add depends_on when the provider cannot infer linkage via attributes (match service_name/plan_name ↔ app_name).
Tool Integration
HashiCorp Terraform MCP Server
Use the Terraform MCP Server for interactive schema lookup, resource block drafting, and validation.
- Install & run server (see https://github.com/mcp/hashicorp/terraform-mcp-server).
- Add it as a tool in your Copilot / MCP client configuration.
- Query provider schema (e.g., list resources, data sources) before authoring.
- Generate draft resource blocks, then refine manually for naming & tagging standards.
- Validate plan summaries (never include secrets); confirm diff with reviewer before
apply.
Terraform Registry
Reference the SAP BTP provider docs: https://registry.terraform.io/providers/SAP/btp/latest/docs for authoritative resource & data source fields. Cross‑check MCP responses with registry docs if uncertain.
Anti‑Patterns (Avoid)
Configuration:
- Hard‑coded environment‑specific values (use variables & tfvars).
- Routine use of
terraform import (migration only).
- Deep / opaque conditional logic and dynamic blocks that reduce clarity.
local-exec provisioners except for unavoidable integration gaps.
- Mixing SAP BTP provider with Cloud Foundry provider in the same root unless explicitly justified (split modules).
Security:
- Storing secrets in HCL, state, or VCS.
- Disabling encryption, validation, or scanning for speed.
- Using default passwords/keys or reusing credentials across environments.
Operational:
- Direct production applies without prior non‑prod validation.
- Manual drift changes outside Terraform.
- Ignoring state inconsistencies / corruption symptoms.
- Running production applies from uncontrolled local laptops (use CI/CD or approved runners).
- Reading business data from raw
*.tfstate instead of outputs / data sources.
All changes must flow through Terraform CLI + HCL – never mutate state manually.
1---2name: terraform-sap-btp3description: Terraform on SAP BTP – Best Practices & Conventions4---5# Terraform on SAP BTP – Best Practices & Conventions67## Core Principles89Keep Terraform code minimal, modular, repeatable, secure, and auditable.10Always version control Terraform HCL and never version control generated state.1112## Security1314Mandatory:15- Use the latest stable Terraform CLI and provider versions; upgrade proactively for security patches.16- Do NOT commit secrets, credentials, certificates, Terraform state, or plan output artifacts.17- Mark all secret variables and outputs as `sensitive = true`.18- Prefer ephemeral / write‑only provider auth (Terraform >= 1.11) so secrets never persist in state.19- Minimize sensitive outputs; emit only what downstream automation truly needs.20- Continuously scan with `tfsec`, `trivy`, `checkov` (pick at least one) in CI.21- Periodically review provider credentials, rotate keys, and enable MFA where supported.2223## Modularity2425Structure for clarity and speed:26- Split by logical domain (e.g., entitlements, service instances) – NOT by environment.27- Use modules for reusable multi‑resource patterns only; avoid single‑resource wrapper modules.28- Keep module hierarchy shallow; avoid deep nesting and circular dependencies.29- Expose only essential cross‑module data via `outputs` (mark sensitive when required).3031## Maintainability3233Aim for explicit > implicit.34- Comment WHY, not WHAT; avoid restating obvious resource attributes.35- Parameterize (variables) instead of hard‑coding; provide defaults only when sensible.36- Prefer data sources for external existing infra; never for resources just created in same root – use outputs.37- Avoid data sources in generic reusable modules; require inputs instead.38- Remove unused / slow data sources; they degrade plan time.39- Use `locals` for derived or repeated expressions to centralize logic.4041## Style & Formatting4243### General44- Descriptive, consistent names for resources, variables, outputs.45- snake_case for variables & locals.46- 2 spaces indentation; run `terraform fmt -recursive`.4748### Layout & Files4950Recommended structure:51```text52my-sap-btp-app/53├── infra/ # Root module54│ ├── main.tf # Core resources (split by domain when large)55│ ├── variables.tf # Inputs56│ ├── outputs.tf # Outputs57│ ├── provider.tf # Provider config(s)58│ ├── locals.tf # Local/derived values59│ └── environments/ # Environment var files only60│ ├── dev.tfvars61│ ├── test.tfvars62│ └── prod.tfvars63├── .github/workflows/ # CI/CD (if GitHub)64└── README.md # Documentation65```6667Rules:68- Do NOT create separate branches/repos/folders per environment (antipattern).69- Keep environment drift minimal; encode differences in *.tfvars files only.70- Split oversized `main.tf` / `variables.tf` into logically named fragments (e.g., `main_services.tf`, `variables_services.tf`).71 Keep naming consistent.7273### Resource Block Organization7475Order (top → bottom): optional `depends_on`, then `count`/`for_each`, then attributes, finally `lifecycle`.76- Use `depends_on` ONLY when Terraform cannot infer dependency (e.g., data source needs entitlement).77- Use `count` for optional single resource; `for_each` for multiple instances keyed by a map for stable addresses.78- Group attributes: required first, then optional; blank lines between logical sections.79- Alphabetize within a section for faster scanning.8081### Variables82- Every variable: explicit `type`, non‑empty `description`.83- Prefer concrete types (`object`, `map(string)`, etc.) over `any`.84- Avoid null defaults for collections; use empty lists/maps instead.8586### Locals87- Centralize computed or repeated expressions.88- Group related values into object locals for cohesion.8990### Outputs91- Expose only what downstream modules/automation consume.92- Mark secrets `sensitive = true`.93- Always give a clear `description`.9495### Formatting & Linting96- Run `terraform fmt -recursive` (required in CI).97- Enforce `tflint` (and optionally `terraform validate`) in pre‑commit / CI.9899## Documentation100101Mandatory:102- `description` + `type` on all variables & outputs.103- A concise root `README.md`: purpose, prerequisites, auth model, usage (init/plan/apply), testing, rollback.104- Generate module docs with `terraform-docs` (add to CI if possible).105- Comments only where they clarify non-obvious decisions or constraints.106107## State Management108- Use a remote backend supporting locking (e.g., Terraform Cloud, AWS S3, GCS, Azure Storage). Avoid SAP BTP Object Store (insufficient capabilities for reliable locking & security).109- NEVER commit `*.tfstate` or backups.110- Encrypt state at rest & in transit; restrict access by principle of least privilege.111112## Validation113- Run `terraform validate` (syntax & internal checks) before committing.114- Confirm with user before `terraform plan` (requires auth & global account subdomain). Provide auth via env vars or tfvars; NEVER inline secrets in provider blocks.115- Test in non‑prod first; ensure idempotent applies.116117## Testing118- Use Terraform test framework (`*.tftest.hcl`) for module logic & invariants.119- Cover success & failure paths; keep tests stateless/idempotent.120- Prefer mocking external data sources where feasible.121122## SAP BTP Provider Specifics123124Guidelines:125- Resolve service plan IDs using `data "btp_subaccount_service_plan"` and reference `serviceplan_id` from that data source.126127Example:128```terraform129data "btp_subaccount_service_plan" "example" {130 subaccount_id = var.subaccount_id131 service_name = "your_service_name"132 plan_name = "your_plan_name"133}134135resource "btp_subaccount_service_instance" "example" {136 subaccount_id = var.subaccount_id137 serviceplan_id = data.btp_subaccount_service_plan.example.id138 name = "my-example-instance"139}140```141142Explicit dependencies (provider cannot infer):143```terraform144resource "btp_subaccount_entitlement" "example" {145 subaccount_id = var.subaccount_id146 service_name = "your_service_name"147 plan_name = "your_plan_name"148}149150data "btp_subaccount_service_plan" "example" {151 subaccount_id = var.subaccount_id152 service_name = "your_service_name"153 plan_name = "your_plan_name"154 depends_on = [btp_subaccount_entitlement.example]155}156```157158Subscriptions also depend on entitlements; add `depends_on` when the provider cannot infer linkage via attributes (match `service_name`/`plan_name` ↔ `app_name`).159160## Tool Integration161162### HashiCorp Terraform MCP Server163Use the Terraform MCP Server for interactive schema lookup, resource block drafting, and validation.1641. Install & run server (see https://github.com/mcp/hashicorp/terraform-mcp-server).1652. Add it as a tool in your Copilot / MCP client configuration.1663. Query provider schema (e.g., list resources, data sources) before authoring.1674. Generate draft resource blocks, then refine manually for naming & tagging standards.1685. Validate plan summaries (never include secrets); confirm diff with reviewer before `apply`.169170### Terraform Registry171Reference the SAP BTP provider docs: https://registry.terraform.io/providers/SAP/btp/latest/docs for authoritative resource & data source fields. Cross‑check MCP responses with registry docs if uncertain.172173## Anti‑Patterns (Avoid)174175Configuration:176- Hard‑coded environment‑specific values (use variables & tfvars).177- Routine use of `terraform import` (migration only).178- Deep / opaque conditional logic and dynamic blocks that reduce clarity.179- `local-exec` provisioners except for unavoidable integration gaps.180- Mixing SAP BTP provider with Cloud Foundry provider in the same root unless explicitly justified (split modules).181182Security:183- Storing secrets in HCL, state, or VCS.184- Disabling encryption, validation, or scanning for speed.185- Using default passwords/keys or reusing credentials across environments.186187Operational:188- Direct production applies without prior non‑prod validation.189- Manual drift changes outside Terraform.190- Ignoring state inconsistencies / corruption symptoms.191- Running production applies from uncontrolled local laptops (use CI/CD or approved runners).192- Reading business data from raw `*.tfstate` instead of outputs / data sources.193194All changes must flow through Terraform CLI + HCL – never mutate state manually.