Terraform-Ansible-AWS

What is Terraform?

What is Ansible?

Pre-requisites:

Let’s Do It!!

provider "aws" {
region = "us-east-1"
}

resource "aws_security_group" "nginx" {
name = "nginx_access"
vpc_id = var.vpc_id

ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}

ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}

egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}

resource "aws_instance" "nginx" {
ami = "ami-0dba2cb6798deb6d8"
subnet_id = var.subnet_id
instance_type = "t2.micro"
associate_public_ip_address = true
security_groups = [aws_security_group.nginx.id]
key_name = var.key_name

provisioner "remote-exec" {
inline = ["echo 'Wait until SSH is ready'"]

connection {
type = "ssh"
user = var.ssh_user
private_key = file(var.private_key_path)
host = aws_instance.nginx.public_ip
}
}
provisioner "local-exec" {
command = "ansible-playbook -i ${aws_instance.nginx.public_ip}, --private-key ${var.private_key_path} nginx.yaml"
}
}

output "nginx_ip" {
value = aws_instance.nginx.public_ip
}
provisioner "local-exec" {
command = "ansible-playbook -i ${aws_instance.nginx.public_ip}, --private-key ${var.private_key_path} nginx.yaml"
}
variable "vpc_id" {
default = "vpc-0b5f4edc1852"
}

variable "subnet_id" {
default = "subnet-0c4e655e60"
}

variable "ssh_user" {
default = "ubuntu"
}

variable "key_name" {
default = "devops"
}

variable "private_key_path" {
default = "~/terraform-ansible-aws/code/devops.pem"
}
---
- name: Install Nginx Server
hosts: all
remote_user: ubuntu
become: yes
tasks:
- name: Ensure Nginx is at the latest version
apt:
name: nginx
state: latest
- name: Make sure Nginx service is running
systemd:
state: started
name: nginx
$ terraform init
$ terraform plan
$ terraform apply
output "nginx_ip" {
value = aws_instance.nginx.public_ip
}

--

--

--

Astrophile | Technophile | Opensource enthusiast

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Future of Google Fuchsia

100$ To 500$ Vertex Protocol (Terra) Testnet Airdrop || Upcoming Airdrop Terra Network.

Perfect guide to understand Data Scientist in Python

Modern PHP development in WordPress

🔥 Listing Announcement 🔥

How to choose a technology stack for web development — Venar Academy

Assertions and Exceptions

My journey to become an iOS developer week 1

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rahul Waykos

Rahul Waykos

Astrophile | Technophile | Opensource enthusiast

More from Medium

DevOps: How we ended like this?

Jammin’ with AWS IAM, Part 2: Policies

All About AWS VPC!

Recipe OSS: How to crypt/decrypt buckets? (Alibaba Cloud)