1

I'm trying to work with aws_instance data source. I created a simple configuration which should create an ec2 instance and should return ip as output

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
}

but for some reasons I can't configure data source properly. The result is:

> 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" {

how can I fix it?

1
  • Normally this is handled with resource exported attributes. You can update your output value to aws_instance.example.public_ip and remove your data to fix and optimize this. Commented Oct 16, 2019 at 13:34

2 Answers 2

2

You should use depends_on option into data.aws_instances.test.

like :

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

  depends_on = [
    "aws_instance.example"
  ]
}

It means that build data.aws_instances.test after make resource.aws_instance.example.

Sometimes, We need to use this option. Because of dependencies of aws resources.

See :

Here's a document about depends_on option.

Sign up to request clarification or add additional context in comments.

Comments

1

You don't need a data source here. You can get the public IP address of the instance back from the resource itself, simplifying everything.

This should do the exact same thing:

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

  tags = {
    name = "example"
  }
}

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.