如何将 aws_instance 资源创建的 EC2 实例 ID 传递到文件中,并使用 Terraform 将其放入 EC2 实例中?

How to pass the EC2 instance ID created by an aws_instance resource into a file and place it inside an EC2 instance using Terraform?

我想将 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"
    ]
  }
}