Skip to content

Data Source: awsInstances

Use this data source to get IDs or IPs of Amazon EC2 instances to be referenced elsewhere, e.g., to allow easier migration from another management solution or to make it easier for an operator to connect through bastion host(s).

-> Note: It's a best practice to expose instance details via outputs and remote state and use terraformRemoteState data source instead if you manage referenced instances via Terraform.

\~> Note: It's strongly discouraged to use this data source for querying ephemeral instances (e.g., managed via autoscaling group), as the output may change at any time and you'd need to re-run apply every time an instance comes up or dies.

Example Usage

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsInstancesTest = new aws.dataAwsInstances.DataAwsInstances(
  this,
  "test",
  {
    filter: [
      {
        name: "instance.group-id",
        values: ["sg-12345678"],
      },
    ],
    instanceStateNames: ["running", "stopped"],
    instanceTags: {
      Role: "HardWorker",
    },
  }
);
const awsEipTest = new aws.eip.Eip(this, "test_1", {
  instance: `\${${dataAwsInstancesTest.ids.fqn}[count.index]}`,
});
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsEipTest.overrideLogicalId("test");
/*In most cases loops should be handled in the programming language context and 
not inside of the Terraform context. If you are looping over something external, e.g. a variable or a file input
you should consider using a for loop. If you are looping over something only known to Terraform, e.g. a result of a data source
you need to keep this like it is.*/
awsEipTest.addOverride("count", `\${length(${dataAwsInstancesTest.ids})}`);

Argument Reference

  • instanceTags - (Optional) Map of tags, each pair of which must exactly match a pair on desired instances.

  • instanceStateNames - (Optional) List of instance states that should be applicable to the desired instances. The permitted values are: pending,Running,ShuttingDown,Stopped,Stopping,Terminated. The default value is running.

  • filter - (Optional) One or more name/value pairs to use as filters. There are several valid keys, for a full reference, check out describe-instances in the AWS CLI reference.

Attributes Reference

  • id - AWS Region.
  • ids - IDs of instances found through the filter
  • privateIps - Private IP addresses of instances found through the filter
  • publicIps - Public IP addresses of instances found through the filter
  • ipv6Addresses - IPv6 addresses of instances found through the filter

Timeouts

Configuration options:

  • read - (Default 20M)