Terraform:数据源 aws_instance 不工作

Terraform: data source aws_instance doesn't work

我正在尝试使用 aws_instance 数据源。我创建了一个简单的配置,它应该创建一个 ec2 实例并且应该 return ip 作为输出

variable "default_port" {
  type = string
  default = 8080
}

provider "aws" {
  region = "us-west-2"
  shared_credentials_file = "/Users/kharandziuk/.aws/creds"
  profile                 = "prototyper"
}

resource "aws_instance" "example" {
  ami           = "ami-0994c095691a46fb5"
  instance_type = "t2.small"

  tags = {
    name = "example"
  }
}

data "aws_instances" "test" {
  instance_tags = {
    name = "example"
  }
  instance_state_names = ["pending", "running", "shutting-down", "terminated", "stopping", "stopped"]
}

output "ip" {
  value = data.aws_instances.test.public_ips
}

但由于某些原因我无法正确配置数据源。结果是:

> terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

data.aws_instances.test: Refreshing state...

Error: Your query returned no results. Please change your search criteria and try again.

  on main.tf line 21, in data "aws_instances" "test":
  21: data "aws_instances" "test" {

我该如何解决?

你应该在 data.aws_instances.test 中使用 depends_on 选项。

喜欢:

data "aws_instances" "test" {
  instance_tags = {
    name = "example"
  }
  instance_state_names = ["pending", "running", "shutting-down", "terminated", "stopping", "stopped"]

  depends_on = [
    "aws_instance.example"
  ]
}

表示make resource.aws_instance.example后build data.aws_instances.test.

有时候,我们需要使用这个选项。由于aws资源的依赖。

See :

Here's a document about depends_on option.

这里不需要数据源。您可以从资源本身获取实例的 public IP 地址,简化一切。

这应该做完全相同的事情:

resource "aws_instance" "example" {
  ami           = "ami-0994c095691a46fb5"
  instance_type = "t2.small"

  tags = {
    name = "example"
  }
}

output "ip" {
  value = aws_instance.example.public_ip
}