在Terraform配置中引用现有EC2节点的公共IP地址

时间:2018-06-22 00:08:17

标签: amazon-ec2 terraform terraform-provider-aws

我有一些terraform提供商,具体取决于现有EC2节点的公共IP地址。我在similar StackOverflow question中看到,您可以通过设置匹配的资源条目来导入现有节点,然后运行terraform import进行导入:

terraform import aws_instance.test i-12345678

但是,当我运行它(当然具有正确的实例ID)时,会出现此错误:

Error importing: Provider "kov" depends on non-var "aws_instance.test.0/aws_instance.test.N". Providers for import can currently
only depend on variables or must be hardcoded. You can stop import
from loading configurations by specifying `-config=""`.

上述命令的配置为:

provider "aws" {
    # ...
}
resource "aws_instance" "test" {
    ami = "ami-blablahblah"
    instance_type = "t2.large"
    # ...
}
provider "kov" {
    host = "${aws_instance.test.public_ip}"
    port = 8080
    # ...
}

其他提供程序使用该主机和端口来配置与其连接的其他服务器。有什么想法可以使它起作用吗?

2 个答案:

答案 0 :(得分:0)

如果您只想以某种方式引用资源,则不必导入资源。

看看routes.py数据源:https://www.terraform.io/docs/providers/aws/d/instance.html

aws_instance

然后,您应该能够从数据源访问data "aws_instance" "test" { instance_id = "i-12345678" }

答案 1 :(得分:0)

只想根据@manojlds的有用答案进行跟进。工作配置如下:

provider "aws" {
    # ...
}
data "aws_instance" "test" {
    instance_type = "t2.large"
}
provider "kov" {
    host = "${data.aws_instance.test.public_ip}"
    # ...
}

更好的是,我可以根据其他属性过滤数据源,因此我不必一定要事先知道instance-id。