15

我希望我的 Terraform 配置通过调用命令来配置服务器并在最后启动服务并继续运行它。我尝试使用 nohup 和 screen 使用 remote-exec:

nohup:

provisioner "remote-exec" {
 inline = "nohup sudo command &"
}

屏幕:

provisioner "remote-exec" {
 inline = "screen -d -m sudo command"
}

我通过手动登录来检查命令是否正在运行。但它们不会保持进程运行。如果我手动尝试这些命令并使用 ssh 调用它们,这些命令确实有效。

如何使用 Terraform 配置来启动命令并在返回控制流的同时保持其运行?

4

2 回答 2

33

尝试在 nohup 之后添加睡眠。为我工作。我怀疑你最后一个远程执行的后台让 Terraform 在子进程有机会启动之前关闭连接,尽管 nohup。

provisioner "remote-exec" {
    inline = [
        "nohup sudo command &",
        "sleep 1"
    ]
}
于 2016-04-20T02:52:51.753 回答
2

A more robust solution to this is to start a service that runs your process instead.

This means that the init system can take control of the process and restart it if necessary. It also gains the other benefits of a modern init system such as handling dependency ordering (making sure that other services are running before that one starts) and things like logs.

If you set your service to start on boot then you can avoid having to connect to the server over SSH as well and can mean that the server will tolerate reboots without needing to be reprovisioned.

With Systemd this would mean creating a unit file that could be as simple as the following:

[Unit]
Description=foo

[Service]
ExecStart=command
Restart=always

[Install]
WantedBy=multi-user.target

Running the following commands would then make sure that command is ran at boot automatically and that any failures of the process would lead to it being automatically restarted:

systemctl enable foo.service
systemctl start foo.service

This becomes even more important when using mechanisms such as AWS' autoscaling groups to provision your instances. When creating autoscaling groups via the aws_autoscaling_group resource you are unable to easily connect to the instances created at that time and have no control of connecting to instances as the group scales out or replaces instances. At this point it's important that the instance is able to configure itself entirely either from the base image alone (which could be created using a tool such as Packer) or through user data scripts that are automatically ran on first boot.

于 2020-06-15T12:23:21.623 回答