繁体   English   中英

如何将 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"
    ]
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM