运行 "provisioner" 块上的 AWS EC2 实例上的 Hashicorp Vault 服务器

Running Hashicorp Vault server on AWS EC2 instance on "provisioner" block

我正在创建一个 AWS 实例,我正在尝试 运行 创建一个 Vault 服务器。我的问题是创建过程永远不会完成,因为服务器未 运行 在后台运行。这是我的配置:

resource "aws_instance" "web" {
  ami           = "ami-466768ac"
  instance_type = "t2.micro"
  key_name = "my_key"

  tags {
    Name = "Vault"
  }

  provisioner "remote-exec" {

    connection {
      type        = "ssh"
      agent       = false
      user        = "ec2-user"
      private_key = "${file("/path/to/my_key")}"
    }

    inline = [
      "curl -O https://releases.hashicorp.com/vault/0.10.4/vault_0.10.4_linux_amd64.zip",
      "unzip vault_0.10.4_linux_amd64.zip",
      "./vault server -dev -dev-listen-address=0.0.0.0:8200"
    ]
  }

}

基本上,我通过 curl 下载 Vault 并 运行 开发服务器。服务器实际上是 运行(我在终端日志中看到它),但实例创建(通过 Terraform)从未完成:

aws_instance.web: Still creating... (40s elapsed)
aws_instance.web: Still creating... (50s elapsed)
aws_instance.web: Still creating... (1m0s elapsed)
aws_instance.web: Still creating... (1m10s elapsed)
aws_instance.web: Still creating... (1m20s elapsed)
aws_instance.web: Still creating... (1m30s elapsed)
...

我试图在启动 Vault 服务器命令的末尾添加 &,以免阻塞 shell 但是,当我这样做时,实例已创建但 Vault服务器实际上没有启动。

如何在创建实例时以后台模式启动服务器?

编辑

我也试过 nohup:

nohup ./vault server -dev -dev-listen-address=0.0.0.0:8200

但是当 terraform 完成时服务器没有启动...

这真的不是特定于 Terraform 的东西,如果您要通过 SSH 进入一个实例并 运行 您的命令,您会看到它在进程处于前台时被阻塞,如果您通过将 & 添加到命令的末尾,您会在退出 SSH 会话后立即看到它退出。

此处的解决方案是使用 nohup,这样 Vault 服务器进程将忽略您的会话存在时触发的 HUP(或挂断)信号。

因此您应该将命令更改为:

...
    inline = [
      "curl -O https://releases.hashicorp.com/vault/0.10.4/vault_0.10.4_linux_amd64.zip",
      "unzip vault_0.10.4_linux_amd64.zip",
      "nohup ./vault server -dev -dev-listen-address=0.0.0.0:8200 &"
    ]
...

最后,正如@StephenKing 在评论中告诉我的那样,我创建了一个 systemd 服务。这是我的配置:

resource "aws_instance" "web" {
  ami           = "ami-466768ac"
  instance_type = "t2.micro"
  key_name = "my_key"

  tags {
    Name = "Vault"
  }

  //upload vault.service file (systemd unit)
  provisioner "file" {
    connection {
      type        = "ssh"
      agent       = false
      user        = "ec2-user"
      private_key = "${file("/path/to/my/key")}"
    }
    source = "./vault.service"
    destination = "/home/ec2-user/vault.service"
  }

  //download vault and start service
  provisioner "remote-exec" {
    connection {
      type        = "ssh"
      agent       = false
      user        = "ec2-user"
      private_key = "${file("/path/to/my/key")}"
    }
    inline = [
      "curl -O https://releases.hashicorp.com/vault/0.10.4/vault_0.10.4_linux_amd64.zip",
      "unzip vault_0.10.4_linux_amd64.zip",
      "sudo mv /home/ec2-user/vault.service /etc/systemd/system/",
      "sudo systemctl start vault.service"
    ]
  }

}

vault.service

[Unit]
Description=Vault dev server

[Service]
ExecStart=/home/ec2-user/vault server -dev -dev-listen-address=0.0.0.0:8200