Terraform 模块 - 错误 无变化。您的基础架构与配置相匹配

Terraform module - error No changes. Your infrastructure matches the configuration

我正在尝试使用 terraform 模块进行试验并创建了一个非常简单的模块。结构如下

├───dev
│       dev.tfvars
│       main.tf
│       output.tf
│       variables.tf
│
└───modules
    └───instances
            main.tf
            output.tf
            variables.tf
            versions.tf

terraform init
PS C:\Users421\github\IAC-TF\dev> terraform init
Initializing modules...
- ec2_create in ..\modules\instances

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 4.17.1"...
- Installing hashicorp/aws v4.17.1...
- Installed hashicorp/aws v4.17.1 (signed by HashiCorp)

terraform plan
PS C:\Users421\github\IAC-TF\dev> terraform plan

No changes. Your infrastructure matches the configuration.

我正在从我的 DEV 执行这些命令(我计划在不同的目录中构建产品)。

dev.tfvars
instance_type    = "t2.micro"
instance_keypair = "user001"
no_of_instances  = 1
ami_id           = "ami-0c6120f461d6b39e9"


main.tf
provider "aws" {
  region = "ap-southeast-2"
}
module "ec2_create" {
  source        = "../modules/instances"
  ami           = var.ami_id
  instance_type = var.instance_type
  count         = var.no_of_instances

}

variables.tf
variable "no_of_instances" {
  description = "Number of Instances"
  type        = number
  default     = 0
}

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

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

我的示例模块如下。

main.tf
resource "aws_instance" "web" {
  ami = var.ami
  instance_type = var.instance_type
  count = var.no_of_instances
}

variables.tf
variable "ami" {
  description = "ID of AMI to use for the instance"
  type        = string
  default     = ""
}

variable "instance_type" {
  description = "instance_type of AMI to use for the instance"
  type        = string
  default     = ""
}

variable "no_of_instances" {
  description = "Number of Instances"
  type        = number
  default     = 1
}

versions.tf
terraform {
  required_version = "~> 1.1.7" # which means any version equal & above 4.17.1 like 4.17.2
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.17.1"
    }
  }

看起来没有创建任何内容,我尝试使用相同的资源 aws_instance 使用一个没有模块的文件并创建了它。看起来我在调用模块时遗漏了一些东西。感谢您对此的帮助。我是 terraform 的新手。

发生这种情况很可能是因为您的 no_of_instances 默认为 0。因此没有要创建的资源。

要使用您的dev.tfvars,您必须明确传递此文件:

terraform plan -var-file=dev.tfvars