[英]using Terraform to pass a file to newly created ec2 instance without sharing the private key in "connection" section
我的設置是:Terraform --> AWS ec2
使用 Terraform 創建具有 SSH 訪問權限的 ec2 實例。
這
resource "aws_instance" "inst1" {
instance_type = "t2.micro"
ami = data.aws_ami.ubuntu.id
key_name = "aws_key"
subnet_id = ...
user_data = file("./deploy/templates/user-data.sh")
vpc_security_group_ids = [
... ,
]
provisioner "file" {
source = "./deploy/templates/ec2-caller.sh"
destination = "/home/ubuntu/ec2-caller.sh"
}
provisioner "remote-exec" {
inline = [
"chmod +x /home/ubuntu/ec2-caller.sh",
]
}
connection {
type = "ssh"
host = self.public_ip
user = "ubuntu"
private_key = file("./keys/aws_key_enc")
timeout = "4m"
}
}
上面的位有效,我可以看到供應商復制並執行“ec2-caller.sh”。 我不想將我的私鑰以明文形式傳遞給 Terraform 供應商。 無論如何,我們可以在不使用配置器或不將私鑰傳遞給配置器的情況下將文件復制到新創建的 ec2 嗎?
干杯。
Terraform 文檔部分Provisioners are a Last Resort提出了提供和傳遞憑據的需求,作為配置程序成為“最后手段”的理由之一,然后繼續建議將數據傳遞到虛擬機和其他計算的一些其他策略資源。
您似乎已經在使用user_data
來指定要運行的其他一些腳本,因此要遵循該文檔中的建議,需要將這些全部組合到一個cloud-init配置中。 (我假設您的 AMI 已安裝 cloud-init,因為這通常負責將user_data
解釋為要執行的 shell 腳本。)
Cloud-init 支持 多種不同的user_data
格式,其中主要的一種是cloud-init 自己的 YAML 配置文件格式,“Cloud Config” 。 您還可以使用多部分 MIME 消息將多個不同的user_data
有效負載打包到單個user_data
主體中,只要有效負載的組合大小符合 EC2 的user_data
大小上限,即 16kiB。
從你的配置來看,你似乎有兩個步驟需要 cloud-init 來處理,以便用 cloud-init 完全解決這個問題:
./deploy/templates/user-data.sh
腳本。/home/ubuntu/ec2-caller.sh
放在具有適當權限的磁盤上。 假設這兩個步驟相互獨立,您可以向cloud-init
發送一條多部分 MIME 消息,其中包括您最初單獨使用的用戶數據腳本和用於放置ec2-caller.sh
文件的 Cloud Config YAML 配置磁盤。 Terraform 提供商hashicorp/cloudinit
有一個數據源cloudinit_config
,它知道如何為 cloud-init 構造多部分 MIME 消息,您可以像這樣使用它:
data "cloudinit_config" "example" {
part {
content_type = "text/x-shellscript"
content = file("${path.root}/deploy/templates/user-data.sh")
}
part {
content_type = "text/cloud-config"
content = yamlencode({
write_files = [
{
encoding = "b64"
content = filebase64("${path.root}/deploy/templates/ec2-caller.sh")
path = "/home/ubuntu/ec2-caller.sh"
owner = "ubuntu:ubuntu"
permissions = "0755"
},
]
})
}
}
resource "aws_instance" "inst1" {
instance_type = "t2.micro"
ami = data.aws_ami.ubuntu.id
key_name = "aws_key"
subnet_id = ...
user_data = data.cloudinit_config.example.rendered
vpc_security_group_ids = [
... ,
]
}
上面的第二part
塊包括 YAML 基於 cloud-init 示例Writing out arbitrary files ,您可以參考它以了解其他可能的設置。 Terraform 的yamlencode
function無法生成該示例中某些文件中使用的特殊!!binary
標記,但設置encoding: b64
允許將 base64 編碼的文本作為普通字符串傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.