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
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