为 EC2 实例创建签名证书时如何防止循环依赖?

Posted

技术标签:

【中文标题】为 EC2 实例创建签名证书时如何防止循环依赖?【英文标题】:How to prevent cyclic dependencyd when creating signed cert for EC2 instance? 【发布时间】:2016-04-22 09:57:12 【问题描述】:

我正在使用 terraform 创建一个 EC2 实例,该实例将用作 docker 主机。这意味着我需要创建加密密钥以通过 Internet 安全地连接到它。创建密钥时,您需要指定要连接的 IP 地址和主机名。在 terraform 中,这些值可以动态分配,但这很容易导致循环依赖情况。举个例子:

resource "tls_private_key" "example" 
  algorithm = "ECDSA"


resource "tls_self_signed_cert" "docker_host_key" 
  key_algorithm = "$tls_private_key.example.algorithm"
  private_key_pem = "$tls_private_key.example.private_key_pem"
  validity_period_hours = 12
  early_renewal_hours = 3
  allowed_uses = ["server_auth"]
  dns_names = [ "$aws_instance.example.public_dns" ]
  ip_addresses = [ "$aws_instance.example.public_ip" ]
  subject 
    common_name = "example.com"
    organization = "example"
  


resource "aws_instance" "example" 
  count = 1
  ami = "ami-d05e75b8"
  instance_type = "t2.micro"
  subnet_id = "subnet-24h4fos9"
  associate_public_ip_address = true
  provisioner "remote-exec" 
    inline = [
      "echo \"$tls_self_signed_cert.docker_host_key.private_key_pem\" > private_key_pem",
      "echo \"$tls_self_signed_cert.docker_host_key.cert_pem\" > cert_pem",
      "echo \"$tls_private_key.docker_host_key.private_key_pem\" > private_key_pem2",
    ]
  

remote-exec 配置器中,我们需要写入来自tls_self_signed_cert 资源的值,而后者又需要来自aws_instance 资源的值。

我该如何克服这种情况?

【问题讨论】:

【参考方案1】:

您可以使用 aws_eip 资源创建弹性 IP 并将其附加到具有 aws_eip_association 的实例。

resource "aws_eip" "eip" 
  ...


resource "aws_eip_association" "eip" 
  allocation_id = "$aws_eip.eip.id"
  instance_id = "$aws_instance.example.id"


resource "tls_self_signed_cert" "docker_host_key" 
  # set something here from Route53 instead: dns_names = [ "$aws_instance.example.public_dns" ]
  ip_addresses = [ "$aws_eip.eip.public_ip" ]
  ...

【讨论】:

以上是关于为 EC2 实例创建签名证书时如何防止循环依赖?的主要内容,如果未能解决你的问题,请参考以下文章