![](/img/trans.png)
[英]What to bake into an AWS AMI and what to provision using cloud-init?
[英]How to provision AWS instances with cluster's IPs using Terraform and cloud-init?
我正在嘗試使用cloud-init
及其 Terraform 提供程序配置服務器和我的應用程序。 在初始化腳本中,我使用write-files
生成一個配置文件,該文件需要包含 Terraform 生成的所有aws_instances
IP ; 我嘗試(天真地)使用模板來解決,如下所示:
data "cloudinit_config" "test" {
gzip = false
base64_encode = false
part {
content_type = "text/cloud-config"
content = templatefile("templates/cloudinit.yaml", {
ip = aws_instance.test[*].private_ip # <-- Trying to get the private_ip here
})
}
}
resource "aws_instance" "test" {
count = var.num_nodes
ami = "ami-00523c5e5a67c3b52"
instance_type = var.node_type
user_data = data.cloudinit_config.test.rendered
subnet_id = aws_subnet.public.id
associate_public_ip_address = true
vpc_security_group_ids = [aws_security_group.web.id]
tags = {
Name = "Test${count.index}"
}
ebs_block_device {
device_name = "/dev/sda1"
volume_size = var.hdd_size
volume_type = "gp2"
}
}
當然,當我做terraform plan
會告訴我:
Error: Cycle: aws_instance.test, data.cloudinit_config.test
因為機器的 private_ip(在運行時分配)和我必須在運行機器之前注入我的 cloud-init 之間存在循環依賴關系。
有沒有辦法將所有 EC2 實例的 IP 注入到cloud-init
腳本中?
編輯:添加一段cloud-init
腳本
write_files:
- content: |
timeout=200
nodes=${jsonencode($ip)}
path: /etc/zerk/main.config
如果您可以使用 DNS 名稱而不是 IP, 請查看https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance#private_dns
否則,您可以使用丑陋但簡單的https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance#private_ip
variable "private_ips" {
type = list
description = "Additional private IPs associated with EC2 instances"
}
# Notes, number of IPs should match number of nodes
# IPs should be within CIDR range of the VPC
private_ips = ["172.10.32.1", "172.10.32.2", "172.10.32.3"]
data "cloudinit_config" "test" {
gzip = false
base64_encode = false
part {
content_type = "text/cloud-config"
content = templatefile("templates/cloudinit.yaml", {
ip = var.private_ips
})
}
}
resource "aws_instance" "test" {
count = var.num_nodes
user_data = data.cloudinit_config.test.rendered
...
private_ip = element(var.private_ips, count.index)
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.