This worked for me on aws ec2:
main.tf:
resource "aws_instance" "instance" {
for_each = toset(["ingress-01", "node-01", "node-02", "master-01" ])
ami = "ami-0c239ecd40dcc174c"
instance_type = "t2.micro"
tags = {
Name = "${each.key}"
}
}
resource "local_file" "inventory" {
content = templatefile("inventory.tmpl", { content = tomap({
for instance in aws_instance.instance:
instance.tags.Name => instance.public_dns
})
})
filename = format("%s/%s", abspath(path.root), "inventory.yaml")
}
template (inventory.tmpl):
all:
children:
ingress:
hosts:
%{ for content_key, content_value in content }
%{~ if length(regexall("ingress", content_key)) > 0 ~}
${content_key}:
ansible_host: ${content_value}
%{ endif ~}
%{~ endfor ~}
master:
hosts:
%{ for content_key, content_value in content }
%{~ if length(regexall("master", content_key)) > 0 ~}
${content_key}:
ansible_host: ${content_value}
%{ endif ~}
%{~ endfor ~}
nodes:
hosts:
%{ for content_key, content_value in content }
%{~ if length(regexall("node", content_key)) > 0 ~}
${content_key}:
ansible_host: ${content_value}
%{ endif ~}
%{~ endfor ~}
cat inventory.yaml
all:
children:
ingress:
hosts:
ingress-01:
ansible_host: ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com
master:
hosts:
master-01:
ansible_host: ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com
nodes:
hosts:
node-01:
ansible_host: ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com
node-02:
ansible_host: ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com