DevOps Classroom Series – 01/Jun/2020

Scenario: Create an Ec2 machine in AWS with existing security group and ensure you have tags

  • To create this we will be using Local Values and Datasources
  • Local Values help in creating the expression once and reuse it multiple times
  • DataSource help in fetching the values from provider. For finding datasources google with expression terraform datasource <provider> <resource> eg terraform datasource aws securitygroup Preview
  • The terraform script
provider "aws" {
    
}

## Create variable value for reuse with in template
locals {
  common_tags   = {
      Name      = "learning"
      Owner     = "DevOps"
  }
}


data "aws_security_group" "mysecuritygroup" {
    name    = "Openall"
}


resource "aws_instance" "firstec2" {
    ami                             = "ami-003634241a8fcdec0"
    instance_type                   = "t2.micro"
    key_name                        = "terraform"
    vpc_security_group_ids          = [ data.aws_security_group.mysecuritygroup.id ]
    associate_public_ip_address     = true
    tags                            = local.common_tags

}

Scenario: Create a VPC with variable number of subnets

  • Look into Terraform functions [from here]
  • We have a terraform template which looks like this
variable "vpccidr" {
  description   = "cidr of the vpc"
  default       = "192.168.0.0/16"
}

variable "subnetcidrs" {
  description   = "subnet cidrs"
  type          = list(string) 
  default       = ["192.168.0.0/24", "192.168.1.0/24", "192.168.2.0/24"]
}

variable "nameofvpc" {
  description = "name for vpc"
  default = "myvpc"
}

provider "aws" {
    
}

resource "aws_vpc" "created" {
    cidr_block  = var.vpccidr
    tags        = {
        Name    = var.nameofvpc
    }
}

resource "aws_subnet" "subnets" {
    count       = length(var.subnetcidrs)
    vpc_id      = aws_vpc.created.id
    cidr_block  = var.subnetcidrs[count.index]
  
}

output "vpcid" {
  value = aws_vpc.created.id
}

Scenario: Rather than copying the above terraform script again try to reuse the tempalte to create an ec2 instance inside your vpc

  • How to make template reusable?
  • Answer is Terraform modules and we will be using modules and registry

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Please turn AdBlock off
Floating Social Media Icons by Acurax Wordpress Designers

Discover more from Direct DevOps from Quality Thought

Subscribe now to keep reading and get access to the full archive.

Continue reading

Visit Us On FacebookVisit Us On LinkedinVisit Us On Youtube