首页 > 解决方案 > 如何使用 terraform 在 AWS 中为自定义 AMI 创建创建临时实例?

问题描述

我正在尝试使用 terraform 为我的 AWS 部署创建自定义 AMI。它工作得很好,也可以运行 bash 脚本。问题是不可能临时创建实例,然后使用 terraform 和所有相关资源终止 ec2 实例。首先,我构建一个“aws_instance”,而不是在我的 /tmp 文件夹中提供一个 bash 脚本,然后通过 terraform 脚本中的 ssh 连接来完成。如下所示:

首先 aws_instance 是基于标准 AWS Amazon 系统映像 (AMI) 创建的。这用于稍后从中创建图像。

resource "aws_instance" "custom_ami_image" {
  tags = { Name = "custom_ami_image" }

  ami             = var.ami_id                               //base custom ami id 
  subnet_id       = var.subnet_id
  vpc_security_group_ids  = [var.security_group_id]
  iam_instance_profile    = "ec2-instance-profile"
  instance_type           = "t2.micro"

  ebs_block_device {
                     //...further configurations
                   }

现在提供了一个 bash 脚本。来源是 bash 脚本在您正在执行 terraform 的本地 linux 机器上的位置。目标位于新的 AWS 实例上。在文件中,我安装了更多的东西,比如 python3、oracle 驱动程序等等......

  provisioner "file" {
    source      = "../bash_file"
    destination = "/tmp/bash_file"
  }

然后我将更改 bash 脚本的权限并使用 ssh 用户执行它:

  provisioner "remote-exec" {
    inline = [
      "chmod +x /tmp/bash_file",
      "sudo /tmp/bash_file",
    ]
  }

不,您可以使用之前创建的密钥登录 ssh 用户。

  connection {
    type        = "ssh"
    user        = "ssh-user"
    password    = ""
    private_key = file("${var.key_name}.pem")
    host        = self.private_ip
  }
}

使用aws_ami_from_instance可以使用当前创建的 EC2 实例对 ami 进行建模。现在可以调用以进行进一步部署,也可以将其共享到更多 aws 帐户。

resource "aws_ami_from_instance" "custom_ami_image {
  name               = "acustom_ami_image"
  source_instance_id = aws_instance.custom_ami_image.id
}

它工作正常,但困扰我的是生成的 ec2 实例!它正在运行并且不可能用 terraform 终止它?有谁知道我该如何处理?当然,运行成本是可控的,但我不喜欢创建数据垃圾......

标签: amazon-web-servicesamazon-ec2terraformamazon-ami

解决方案


我认为创建 AMI 图像的最佳方法是使用 Packer,也来自 Hashicorp,如 Terraform。

什么是打包机?

使用 Packer 配置基础架构 Packer 是 HashiCorp 的开源工具,用于从源配置创建机器映像。您可以为您的特定用例配置带有操作系统和软件的 Packer 映像。

Packer 使用临时密钥对、security_group 和 IAM 角色创建一个临时实例。在供应商“shell”中可以自定义内联命令。之后,您可以将此 ami 与您的 terraform 代码一起使用。

示例脚本可能如下所示:

packer {
  required_plugins {
    amazon = {
      version = ">= 0.0.2"
      source  = "github.com/hashicorp/amazon"
    }
  }
}

source "amazon-ebs" "linux" {
  # AMI Settings
  ami_name                      = "ami-oracle-python3"
  instance_type                 = "t2.micro"
  source_ami                    = "ami-xxxxxxxx"
  ssh_username                  = "ec2-user"
  associate_public_ip_address   = false
  ami_virtualization_type       = "hvm"
  subnet_id                     = "subnet-xxxxxx" 
  
  launch_block_device_mappings {
    device_name = "/dev/xvda"
    volume_size = 8
    volume_type = "gp2"
    delete_on_termination = true
    encrypted = false
  }

  # Profile Settings
  profile                       = "xxxxxx"
  region                        = "eu-central-1"
}

build {
  sources = [
    "source.amazon-ebs.linux"
  ]
  provisioner "shell" {
    inline = [
        "export no_proxy=localhost"
    ]
  }
}

您可以在此处找到有关打包程序的文档。


推荐阅读