Skip to content

Instantly share code, notes, and snippets.

@saissemet
Last active January 22, 2024 04:17
Show Gist options
  • Save saissemet/7dead669cba388240cf67745cd535d40 to your computer and use it in GitHub Desktop.
Save saissemet/7dead669cba388240cf67745cd535d40 to your computer and use it in GitHub Desktop.
Creating multiple EC2 instances using Terraform
## Step 1 ##
In your current user directory, create a folder named ".aws".
Also create a file named "credentials" with your AWS credentials.
## Step 2 ##
Download Terraform (https://releases.hashicorp.com/terraform/0.14.7/terraform_0.14.7_windows_amd64.zip)
Create a folder with a name of your taste and place the "terraform.exe" file.
## Step 3 ##
In that same folder you just created, create the files: "provider.tf", "variables.tf", "main.tf" and "config.sh".
These files are available on this gist.
## Step 4 ##
At this point you should be able to start using terraform.
To do that, open your command line and make sure you're placed in the directory you created in the step 2.
After that, insert the following commands, one by one:
terraform init
terraform plan
terraform apply
#!/bin/bash -x
mkdir /ansible
touch /ansible/welcome-file
echo "Hello" > /ansible/welcome-file
resource "aws_instance" "instance1" {
count = var.instance_count
ami = "ami-0885b1f6bd170450c"
instance_type = "t2.micro"
key_name = var.key_name
security_groups = [
var.sec_group_name,
]
vpc_security_group_ids = [
aws_security_group.instance.id,
]
root_block_device {
volume_size = var.volume_size
}
user_data = filebase64(var.user_data)
}
resource "aws_security_group" "instance" {
description = var.sec_group_description
egress = [
{
cidr_blocks = [
"0.0.0.0/0",
]
description = ""
from_port = 0
ipv6_cidr_blocks = []
prefix_list_ids = []
protocol = "-1"
security_groups = []
self = false
to_port = 0
},
]
ingress = [
for _port in var.port_list:
{
cidr_blocks = [
for _ip in var.ip_list:
_ip
]
description = ""
from_port = _port
ipv6_cidr_blocks = []
prefix_list_ids = []
protocol = "tcp"
security_groups = []
self = false
to_port = _port
}
]
name = var.sec_group_name
}
terraform {
required_version = ">= 0.13"
required_providers {
aws = {
source = "hashicorp/aws"
version = "3.22.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
variable "key_name" {
default = "Ansible"
}
variable "sec_group_name" {
default = "Ansible Security Group"
}
variable "sec_group_description" {
default = "Ansible Security Group - allow All Trafic to My IP"
}
variable "user_data" {
default = "./config.sh"
}
variable "volume_size" {
default = 8
}
variable "ip_list" {
description = "Allowed IPs"
type = list(string)
default = [
"0.0.0.0/0",
]
}
variable "instance_count" {
default = "2"
}
variable "port_list" {
description = "Allowed ports"
type = list(number)
default = [
22,
80,
8080,
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment