我想将 terraform 创建的 EC2 实例 ID 传递给我要放置在 EC2 实例中的文件sagemaker.config
。
ec2_files/sagemaker.config
我想要配置文件中的实例 ID 采用以下格式
email:abc@xyc.com
instanceid:i-0a4ca8714103432dxxx
ec2.tf
resource "aws_instance" "sagemaker_automation" {
instance_type = var.instance_type
ami = var.image_id
iam_instance_profile = aws_iam_instance_profile.ec2_profile.name
tags = {
Name = "Sagemaker Automation"
}
}
在做了一些研究之后,我找到了一种使用provisioner "file"
和provisioner "local-exec"
将 EC2 实例 ID 传递给文件并将其放置在 EC2 实例中的方法。
resource "tls_private_key" "example" {
algorithm = "RSA"
rsa_bits = 4096
}
resource "aws_key_pair" "generated_key" {
key_name = "cloudtls"
public_key = tls_private_key.example.public_key_openssh
}
resource "aws_instance" "automation" {
instance_type = var.instance_type
ami = var.image_id
iam_instance_profile = aws_iam_instance_profile.ec2_profile.name
key_name = aws_key_pair.generated_key.key_name
vpc_security_group_ids = var.security_group_ids
subnet_id = var.subnet_id
tags = {
Name = "Automation"
}
provisioner "local-exec" {
# the below command replaces the existing instance id in the file, if any
# and replaces it with the new instance id
command = "sed -i '/instanceid/d' ec2_files/sagemaker.config;echo 'instanceid:${aws_instance.automation.id}' >> ec2_files/sagemaker.config"
}
# this copies the files in the ec2_files/ directory to /home/ec2-user on the instance
provisioner "file" {
source = "ec2_files/"
destination = "/home/ec2-user"
}
# this is required to establish a connection and to copy files to the EC2 instance id from local disk
connection {
type = "ssh"
user = "ec2-user"
private_key = tls_private_key.example.private_key_pem
host = aws_instance.automation.private_ip
}
provisioner "remote-exec" {
inline = [
"ls -lrt",
"(crontab -l 2>/dev/null; echo '@reboot sleep 30 && /home/ec2-user/runpython.sh >> sagemakerautomation.log') | crontab -",
"chmod +x runpython.sh",
"cat sagemaker.config"
]
}
}