Skip to content

Instantly share code, notes, and snippets.

@ohrafaelmartins
Last active March 22, 2021 00:44
Show Gist options
  • Save ohrafaelmartins/e87237cd6e8a842702151622248a351a to your computer and use it in GitHub Desktop.
Save ohrafaelmartins/e87237cd6e8a842702151622248a351a to your computer and use it in GitHub Desktop.
# Terraform: How to create five instances on Amazon Web Services
# and define the name tag individually using a list type variable.
# It is just a simple example of how to create a given instance
# number and set the names according to the size of the list.
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
owners = ["099720109477"] # Ubuntu
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
count = length(var.instance_names) # number of instances desired to create within the EC2 service on Amazon Web Services
associate_public_ip_address = true # Associate with a passkey (pem file)
key_name = "key_pem_name" # Name of the key previously created within the Amazon Web Services IAM service
tags = {
Name = var.instance_names[count.index] # Using each item in the list to name the instances created
}
}
# Configuration of the default region where to create the instances
provider "aws" {
region = "sa-east-1"
}
terraform {
# Configuration to use state within a bucket
backend "s3" {
bucket = "bucketanme"
key = "terraform-test.tfstate"
region = "sa-east-1"
}
# Sets the minimum version of the aws plugin
required_providers {
aws = {
version = "~> 2.0"
source = "hashicorp/aws"
}
}
}
# Returns the public DNS of each instance created on Amazon Web Services
output "dns_name" {
value = aws_instance.web.*.public_dns
}
# Create a list that will be used to name each instance
variable "instance_names" {
type = list(any)
default = ["Jenkins", "Grafana", "Prometheus", "Zabbix", "netdata"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment