在“ provisioner”块上的AWS EC2实例上运行Hashicorp Vault服务器

时间:2018-08-08 06:33:26

标签: amazon-web-services amazon-ec2 terraform hashicorp-vault

我正在创建一个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服务器命令的末尾添加&,以便不阻止外壳程序,但是在执行此操作时,将创建实例,但实际上并未启动Vault服务器。

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

编辑

我也尝试过使用nohup

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

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

2 个答案:

答案 0 :(得分:2)

最后,正如@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 

答案 1 :(得分:1)

这实际上不是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 &"
    ]
...