Terraform模块变量未生效:ami_key未覆盖默认值
问题根源:模块定义与调用完全搞反了
你当前的代码逻辑存在核心错误:
- 你把模块调用代码写到了模块目录(
module/dev/compute.tf)里,而Terraform只会执行根目录下的配置文件,模块目录里的代码除非被根配置引用,否则不会生效。 - 根目录的
main.tf直接创建了EC2实例,使用的是根目录variables.tf里的ami_key默认值,完全没用到你在模块目录里设置的参数。
修复步骤
1. 调整模块定义
把根目录main.tf里的EC2资源移到module/dev/compute.tf中,作为模块的资源定义:
# module/dev/compute.tf resource "aws_instance" "aws_vm" { ami = var.ami instance_type = var.instance_type count = var.number_of_instances key_name = var.ami_key tags = { ec2_dev_name = "${var.name_tag}${var.env}${count.index}" } }
在module/dev目录下新建variables.tf,声明模块专属变量:
# module/dev/variables.tf variable "instance_type" { type = string description = "Instance Type" default = "t2.micro" } variable "name_tag" { type = string description = "Name" default = "VM" } variable "env" { type = string description = "Environment of EC2" default = "dev" } variable "number_of_instances" { type = number description = "Instances" default = 1 } variable "ami" { type = string description = "AMI ID" default = "ami-0a3c3a20c09d6f377" } variable "ami_key" { type = string description = "Key Pair" default = "key-default" }
2. 修改根目录main.tf,改为调用模块
根目录main.tf只保留provider配置和模块调用,传递你需要的参数:
# main.tf provider "aws" { access_key = var.aws_access_key_id secret_key = var.aws_secret_access_key region = var.aws_region } module "compute" { source = "./module/dev" instance_type = "t2.micro" name_tag = "VM" env = "dev" number_of_instances = 1 ami = "ami-0a3c3a20c09d6f377" ami_key = "key" # 这里的参数会覆盖模块的默认值 }
3. 精简根目录variables.tf
只保留全局通用变量,移除模块已声明的变量:
# variables.tf variable "aws_region" { type = string description = "US East 1" default = "us-east-1" } variable "aws_access_key_id" {} variable "aws_secret_access_key" {}
验证修复
执行terraform init重新初始化,再运行terraform plan,就能看到key_name已经被覆盖为key了。
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

