Terraform:数据源aws_instance不起作用

时间:2019-10-16 08:23:36

标签: amazon-web-services terraform terraform-provider-aws

我正在尝试使用aws_instance数据源。我创建了一个简单的配置,该配置应创建一个ec2实例,并应将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" {

我该如何解决?

2 个答案:

答案 0 :(得分:1)

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

喜欢:

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

  depends_on = [
    "aws_instance.example"
  ]
}

这意味着在生成data.aws_instances.test之后构建resource.aws_instance.example

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

  

请参阅:

     

这里有a document个关于depends_on的选项。

答案 1 :(得分:0)

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

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

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

  tags = {
    name = "example"
  }
}

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