如何使用terraform在AWS中创建自定义AMI的临时实例?



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

首先,aws_instance是基于标准AWS Amazon Machine Image (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-user:

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实例!它在运行,不可能用地形来终止它?有人知道我该怎么处理吗?当然,运行成本是可控的,但是我不喜欢创建数据垃圾....

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

Packer是什么?

配置基础设施与Packer Packer是HashiCorp的开源工具,用于从源代码创建机器映像配置。您可以使用操作命令配置Packer映像系统和软件为您的特定用例。

Packer创建一个临时实例,其中包含临时的keypair, security_group和IAM角色。在提供者的"shell"中是否可以使用自定义内联命令。之后,您可以在您的地形代码中使用此ami。

示例脚本如下所示:

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"
]
}
}

你可以在这里找到关于packer的文档。

最新更新