如何根据 AMI 实例信息创建 TLS 证书并将其用于配置?

如何根据 AMI 实例信息创建 TLS 证书并将其用于配置?

我正在尝试在 Terraformed 系统上的 Docker 上创建用于服务器身份验证的 TLS 证书。为了创建 TLS 服务器证书,我执行了以下操作

resource "tls_private_key" "master-1" {
  algorithm = "RSA"
  rsa_bits  = "2048"
}

resource "tls_cert_request" "master-1" {
  key_algorithm   = "RSA"
  private_key_pem = "${tls_private_key.master-1.private_key_pem}"

  subject {
    common_name = "${aws_instance.master-1.public_dns}"
  }

  dns_names = [
    "${aws_instance.master-1.public_dns}",
    "${aws_instance.master-1.private_dns}",
  ]

  ip_addresses = [
    "${aws_instance.master-1.public_ip}",
    "${aws_instance.master-1.private_ip}",
  ]
}

resource "tls_locally_signed_cert" "master-1" {
  ca_key_algorithm   = "RSA"
  cert_request_pem   = "${tls_cert_request.master-1.cert_request_pem}"
  ca_private_key_pem = "${tls_private_key.devops.private_key_pem}"
  ca_cert_pem        = "${tls_self_signed_cert.devops.cert_pem}"

  validity_period_hours = 8760

  allowed_uses = [
    "server_auth",
    "digital_signature",
    "key_encipherment",
  ]
}

在本resource "tls_cert_request" "master-1"节中我添加了对master-1 aws_instance

在实例中,我有以下提供者,它使用来自签名证书的值

  provisioner "remote-exec" {
    inline = [
      "echo ${tls_self_signed_cert.devops.cert_pem} > /tmp/ca.pem",
      "echo ${tls_locally_signed_cert.master-1.cert_pem} > /tmp/cert.pem",
      "echo ${tls_private_key.master-1.private_key_pem} > /tmp/key.pem",
    ]
  }

我知道这在技术上是一个循环,当执行时terraform plam它会出错

Error: Error asking for user input: 1 error(s) occurred:

* Cycle: aws_instance.master-1, tls_cert_request.master-1, tls_locally_signed_cert.master-1

所以我想问一下,除了使用 openssl 并在配置脚本中执行 TLS 生成之外,是否还有其他方法可以避免这种情况?

这是我为 Vagrant 环境所做的工作,我即将将其移植到 Terraform

mkdir -p /var/lib/docker
openssl genrsa -out /var/lib/docker/key.pem 4096 2> /dev/null
openssl req -subj "/CN=$(hostname)" -sha256 -new -key /var/lib/docker/key.pem -out /tmp/server.csr
echo subjectAltName = DNS:$(hostname),IP:$(hostname -I | awk '{print $1}'),IP:127.0.0.1 >> extfile.cnf
echo extendedKeyUsage = serverAuth >> /tmp/extfile.cnf
openssl x509 -req -days 365 -sha256 -in /tmp/server.csr -CA /vagrant/ca/ca.pem -CAkey /vagrant/ca/ca-key.pem -CAcreateserial -out /var/lib/docker/cert.pem -extfile extfile.cnf -passin file:/vagrant/ca/passphrase
rm /tmp/server.csr /tmp/extfile.cnf

答案1

使用来null_resource部署证书,而不是在 AWS_instance 中执行此操作。

resource "null_resource" "master" {
    connection {
        type    = "ssh"
        host    = "${aws_instance.master-1.0.public_ip}"
        user    = "fedora"
        timeout = "15m"
    }

    provisioner "remote-exec" {
        inline = [
        "echo ${tls_self_signed_cert.devops.cert_pem} > /tmp/ca.pem",
        "echo ${tls_locally_signed_cert.master-1.cert_pem} > /tmp/cert.pem",
        "echo ${tls_private_key.master-1.private_key_pem} > /tmp/key.pem",
        ]
    }
}

相关内容