Skip to content

Instantly share code, notes, and snippets.

@Alexhha
Created July 13, 2019 17:29
Show Gist options
  • Save Alexhha/63b743fcfd9f6c56073a34b38eeef95e to your computer and use it in GitHub Desktop.
Save Alexhha/63b743fcfd9f6c56073a34b38eeef95e to your computer and use it in GitHub Desktop.
terraform-aws-ha-ansible-inventory
provider "aws" {
version = "~> 2.0"
profile = "personal"
region = "${var.region}"
}
data "aws_availability_zones" "healthy_zones" {
state = "available"
}
data "template_file" "ansible_inventory" {
template = "${file("templates/hosts.ini.tpl")}"
vars {
ha_enabled = "${var.ha_enabled}"
master_addr = "${aws_instance.master.public_ip}:${aws_instance.master.private_ip}"
slave_addr = "${join(",", formatlist("%s:%s", aws_instance.slave.*.public_ip, aws_instance.slave.*.private_ip))}"
db_addr = "${aws_instance.database.public_ip}:${aws_instance.database.private_ip}"
}
}
resource "local_file" "save_ansible_inventory" {
content = "${data.template_file.ansible_inventory.rendered}"
filename = "hosts.ini"
}
resource "aws_instance" "master" {
ami = "ami-0085d4f8878cddc81"
key_name = "ansible-jfrog.key"
instance_type = "t2.nano"
availability_zone = "${data.aws_availability_zones.healthy_zones.names[0]}"
tags {
Name = "ansible-inventory-tpl-master"
}
}
resource "aws_instance" "slave" {
ami = "ami-0085d4f8878cddc81"
count = "${var.ha_enabled == "true" ? var.ha_node_count : 0}"
key_name = "ansible-jfrog.key"
instance_type = "t2.nano"
availability_zone = "${data.aws_availability_zones.healthy_zones.names[1]}"
tags {
Name = "ansible-inventory-tpl-slave${count.index+1}"
}
}
resource "aws_instance" "database" {
ami = "ami-0085d4f8878cddc81"
key_name = "ansible-jfrog.key"
instance_type = "t2.nano"
availability_zone = "${data.aws_availability_zones.healthy_zones.names[1]}"
tags {
Name = "ansible-inventory-tpl-db"
}
}
[${ha_enabled == "true" ? "ha" : "sa"}-master]
webserver ansible_host=${split(":", master_addr)[0]} private_ip=${split(":", master_addr)[1]}
[${ha_enabled == "true" ? "ha" : "sa"}-database]
db-server ansible_host=${split(":", db_addr)[0]} private_ip=${split(":", db_addr)[1]}
%{ if ha_enabled == "true" ~}
[ha-slave]
%{ for curr_slave_addr in "${split(",", slave_addr)}" ~}
slave${index(split(",", slave_addr), curr_slave_addr)+1} ansible_host=${split(":", curr_slave_addr)[0]} private_ip=${split(":", curr_slave_addr)[1]}
%{ endfor ~}
%{ endif ~}
variable "ha_enabled" {
type = "string"
default = "false"
}
variable "ha_node_count" {
type = "string"
default = "1"
}
variable "region" {
type = "string"
default = "eu-central-1"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment