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

问题描述 投票:0回答:1

我想将由terraform创建的EC2实例ID传递到要放置在EC2实例内部的文件sagemaker.config

ec2_files / sagemaker.config

我想以以下格式在配置文件中添加实例ID

email:[email protected]
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"
  }
}
amazon-web-services amazon-ec2 terraform terraform-provider-aws
1个回答
0
投票

[进行了一些研究之后,我找到了一种使用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"
    ]
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.