Die*_*ego 6 amazon-ec2 amazon-web-services terraform terraform-provider-aws
我想知道是否可以知道用户数据中的脚本何时完全执行?
data "template_file" "script" {
template = file("${path.module}/installing.sh")
}
data "template_cloudinit_config" "config" {
gzip = false
base64_encode = false
# Main cloud-config configuration file.
part {
filename = "install.sh"
content = "${data.template_file.script.rendered}"
}
}
resource "aws_instance" "web" {
ami = "ami-04e7b4117bb0488e4"
instance_type = "t2.micro"
key_name = "KEY"
vpc_security_group_ids = [aws_default_security_group.default.id]
subnet_id = aws_default_subnet.default_az1.id
associate_public_ip_address = true
iam_instance_profile = "Role_S3"
user_data = data.template_cloudinit_config.config.rendered
tags = {
Name = "Terraform-Ansible"
}
}
Run Code Online (Sandbox Code Playgroud)
在脚本的内容中我有这个。它告诉我 Terraform 成功应用了更改,但脚本仍在运行,有没有办法可以监控它?
#!/usr/bin/env bash
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
echo BEGIN
sudo apt update
sudo apt upgrade -y
sudo apt install -y unzip
echo END
Run Code Online (Sandbox Code Playgroud)
不,您无法从 terraform 确认用户数据状态,因为它会发布启动脚本,该脚本在 EC2 实例启动后执行。但是您需要在初始化脚本上做一些额外的工作,这是一种检查方法。
如果您执行上述操作以在用户数据完成后制作一些标记文件,那么您可以尝试此检查。
resource "null_resource" "user_data_status_check" {
provisioner "local-exec" {
on_failure = "fail"
interpreter = ["/bin/bash", "-c"]
command = <<EOT
echo -e "\x1B[31m wait for few minute for instance warm up, adjust accordingly \x1B[0m"
# wait 30 sec
sleep 30
ssh -i yourkey.pem instance_ip ConnectTimeout=30 -o 'ConnectionAttempts 5' test -f "/home/user/markerfile.txt" && echo found || echo not found
if [ $? -eq 0 ]; then
echo "user data sucessfully executed"
else
echo "Failed to execute user data"
fi
EOT
}
triggers = {
#remove this once you test it out as it should run only once
always_run ="${timestamp()}"
}
depends_on = ["aws_instance.my_instance"]
}
Run Code Online (Sandbox Code Playgroud)
因此,此脚本将通过执行 ssh 来检查新启动的服务器上的标记文件,超时 30 秒,最大尝试次数 5。