Terraform:如何将根模块变量传递至子模块?
Hey there! Let's break down your Terraform setup, cover what's working, and walk through key improvements to make this implementation solid.
What’s Working So Far
Your core approach to passing the account_id variable from the root module to the iam submodule is syntactically valid. By defining account_id = "${var.account_id}" in your root module's module "iam" block, you're correctly passing the root variable value to the submodule—assuming the submodule is set up to receive it (more on that below).
Key Improvements & Fixes
1. Add Variable Declaration in the Submodule
Right now, your iam submodule has no way to recognize the account_id variable being passed to it. You need to create a variables.tf file in ./modules/iam/ to explicitly declare this variable:
# ./modules/iam/variables.tf variable "account_id" { description = "AWS account ID used for constructing IAM resource ARNs" type = string # Optional: Add a validation rule to ensure it's a valid 12-digit account ID validation { condition = length(var.account_id) == 12 && regex("^[0-9]+$", var.account_id) error_message = "The account_id must be a 12-digit numeric string." } }
2. Actually Use the Passed Variable in the Submodule
Your current iam.tf snippet doesn't use the account_id variable at all. If your policy ARN depends on the account ID (which most IAM policies do), update it to reference the submodule's variable:
# ./modules/iam/iam.tf resource "aws_iam_policy_attachment" "myName" { name = "myName" # Use the passed account_id variable to build the policy ARN policy_arn = "arn:aws:iam::${var.account_id}:policy/your-target-policy" # Don't forget to specify roles/users/groups to attach the policy to! roles = ["your-iam-role-name"] }
3. Modernize Your AWS Provider Configuration
- Update the Provider Version: The
~> 1.11AWS provider version is extremely outdated (released in 2018). Upgrade to a recent stable version (e.g.,~> 5.0) to get security patches, new features, and better compatibility with modern Terraform versions. - Simplify Variable Syntax: Terraform 0.12+ supports direct variable references without
${}wrapping. - Avoid Hardcoding Credentials: Storing
access_keyandsecret_keyin variables is insecure. Instead, use environment variables (AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY) or the AWS credentials file.
Here's the cleaned-up provider block:
# Root module main.tf provider "aws" { version = "~> 5.0" region = var.aws_region }
4. Reorder Module Block Attributes
While not a functional issue, Terraform convention recommends placing the source attribute first in module blocks for readability:
# Root module main.tf module "iam" { source = "./modules/iam" account_id = var.account_id # No need for `${}` wrapping in Terraform 0.12+ }
内容的提问来源于stack exchange,提问作者Broshi

