DEV Community

Programmers Quickie

🔥Terraform | init, tags, name, EC2, Security groups, Dynamic Blocks

📚 Book - https://amzn.to/39ty0Tq - "Terraform: Up & Running: Writing Infrastructure as Code"

  • Terraform init will download all the dependencies needed by the terraform project like when you have a clean maven project, and running almost any mvn command will pull down the dependencies.
  • tags in terraform helps you set the additional tag properties of the resources, if you want to set the name of the resource that would appear in aws then you need to set the tag with specific key and this key is Name actual names of resources, so if you would like to create a vpc resource in aws with name "myvpc" you need to actually set its tags which is different from aws tags you would set the tags { Name = "MyVpc" } and this would set the name of the resource in aws and not the tags in aws.
  • Create EC2The terraform name aws_instance
    The 2 mandatory arguments are ami and instance_type
    Example
resource "aws_instance "MyEc2Instance" {
ami = "ami_287428346" // some aws ami
instance_type = "t2.micro"
}
  • Note to reference an id of a terraform instance need to specify <aws key>.<name>.id so aws_vpc.myvpc.id
  • When we set an "aws_eip" which is elastic ip we have to tell it for which ec2 instance we assign it to, so the resource contains the "instance" property that we have to set.
  • Aws account can give us up to 5 elastic ips.
  • Security group - statefull firewall - stateful means if we allowed some traffic going in it would automatically allow traffic to go out, in stateless we have to set explicitly the input to the firewall and the output.
resource "aws_security_group" "MySecurityGroup" {
name = "Allow HTTPS"
ingress {
from_port = 443
to_port = 443 # This is a range of ports from to to is not output.
protocol = "TCP"
cird_blocks = ["0.0.0.0/0"] # All traffic.
}
egress {

}
}

Then we can reference this MySecurityGroup from various resources such as ec2 instances.

  • Dynamic Blocks - iterator, for_each var.mylistvar , content = port.value This allows us to use for_each.prefix the block you want to use the list for each in dynamic example
variable "ingressrules" { # Here you set the list variable holding the data to be dynamically included.
type = list(number)
default = [80, 443]
}

dynamic "ingress" { # Now iterate and use the above list defined above.
iterator = port
for_each = var.ingressrules
content {
from_port = port.value
}
}

Terraform dynamic blocks and security groups definition in Terraform and AWS elastic IP definition in Terraform and EC2 We continue also to investigate what does terraform init means.


Episode source