Write a terraform code to configure a web-server in n.virginia region having one VPC(name should be 'lwterra') on AWS
Rashni Ghosh
AWS || Jenkins(CI/CD) || Docker || Terraform || Git & GitHub || Python(Boto3) || DevOps || Control-M || Rancher
We need an infrastructure to create resources. Here we will go with AWS cloud. So firstly To achieve this we need to create a?provider.tf?file where we will declare the provider details.
provider "aws" {
? profile = "defaultP" #profile_name
? region = "us-east-1"
}
We will create a new VPC named 'lwterra' and also create a subnet and IGW(instances need a public_ip)
resource "aws_vpc" "testvpc" {
? cidr_block = "10.0.0.0/16"
? tags = {
? ? Name = "lwterra"
? }
}
resource "aws_subnet" "sub1" {
? vpc_id? ? ?= aws_vpc.testvpc.id
? cidr_block = "10.0.1.0/24"
? depends_on = [aws_internet_gateway.igwtest]
? map_public_ip_on_launch = true
? tags = {
? ? Name = "Ec2Sub"
? }
}
resource "aws_internet_gateway" "igwtest" {
? vpc_id = aws_vpc.testvpc.id
? tags = {
? ? Name = "IGW for testvpc"
? }
}
Now we need to create a server and configure it as web-server.
领英推荐
resource "aws_instance" "web" {
? depends_on = [ aws_security_group.ec2_ssh_security_group ]
? ami? ? ? ? ? ?= "ami-0c2b8ca1dad447f8a"
? instance_type = "t2.micro"
? subnet_id? ?= aws_subnet.sub1.id
? key_name? ? ? = "TFKP"
? vpc_security_group_ids = [aws_security_group.ec2_ssh_security_group.id]
? tags = {
? ? Name = "LwInstanceTerra"
? }
? connection {
? ? type = "ssh"
? ? user = "ec2-user"
? ? private_key = file("C:/Users/RASHNI/Downloads/TFKP.pem")??
? ? host =? aws_instance.web.public_ip
? }
? provisioner "file" {
? ? source = "index.html"
? ? destination = "/var/www/html/index.html"
? }
? provisioner "remote-exec" {
? ? inline = [
? ? ? "sudo yum install httpd",
? ? ? "sudo systemctl start httpd"
? ? ]
? }
}
Now to access the web-server we need to open the port 80(for HTTP) and 22(for SSH). Hence we need a custom security group.
resource "aws_security_group" "ec2_ssh_security_group" {
? name? ? ? ? = "lwterra-sg"
? description = "Security Group for ssh access"
? vpc_id? ? ? = aws_vpc.testvpc.id
? ingress {
? ? from_port? ?= 80
? ? protocol? ? = "TCP"
? ? to_port? ? ?= 80
? ? cidr_blocks = ["0.0.0.0/0"]
? }
? ingress {
? ? from_port? ?= 22
? ? protocol? ? = "TCP"
? ? to_port? ? ?= 22
? ? cidr_blocks = ["0.0.0.0/0"]
? }
? egress {
? ? from_port? ?= 0
? ? protocol? ? = "-1"
? ? to_port? ? ?= 0
? ? cidr_blocks = ["0.0.0.0/0"]
? }
}
Note : To use this script - 1)please create a new keypair(name it as TFKP) and need to keep the '.pem' file to local system and change the file path. 2) also create a index.html file mentioning your skill set.
Now try with the public_ip and show your skill set.. :)
DevOps Engineer at Flentas | 2xAWSCertified | CKA Certified | Docker | Jenkin | Terraform
3 年Amazing ??