【问题标题】:Terraform: data source aws_instance doesn't workTerraform:数据源 aws_instance 不起作用
【发布时间】:2019-10-16 19:05:11
【问题描述】:

我正在尝试使用 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" {

我该如何解决?

【问题讨论】:

  • 通常使用资源导出属性来处理。您可以将您的 output 值更新为 aws_instance.example.public_ip 并删除您的数据以修复和优化此问题。

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


【解决方案1】:

您应该在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之后构建data.aws_instances.test

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

见:

这是关于depends_on 选项的a document

【讨论】:

    【解决方案2】:

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

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

    resource "aws_instance" "example" {
      ami           = "ami-0994c095691a46fb5"
      instance_type = "t2.small"
    
      tags = {
        name = "example"
      }
    }
    
    output "ip" {
      value = aws_instance.example.public_ip
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-10
      • 2021-07-16
      • 2020-02-21
      • 2019-06-28
      • 2021-02-13
      • 2018-07-09
      • 2021-12-10
      • 2018-10-10
      相关资源
      最近更新 更多