- Resources are the main thing we want to create with terraform, these are the components that make our infrastructure.
- Terraform intent is to create the resource idempotently, so that running apply more that once will not create multiple resources.
- body of resource contains configuration of attributes of that resource
- each provider (e.g., AWS, Azure, etc.) provides its own set of resources and defines the configuration attributes
- when a resource is created by Terraform, it’s tracked in Terraform state
- resources can refer to attributes of other resources, creating implicit dependencies
dependencies trigger sequential creation
HCL Resource examples
1 resource "aws_instance" "web" {
2 ami = "ami-0005e0cfe09cc9050"
3 instance_type = "t3.micro"
4 tags = {
5 Name = "HelloWorld"
6 }
7}
1 resource "aws_s3_bucket" "example" {
2 bucket = "my-tf-test-bucket"
3 tags = {
4 Name = "My bucket"
5 Environment = "Dev"
6 }
7}
1resource "docker_container" "foo" {
2 image = docker_image.ubuntu.latest
3 name = "foo"
4 command = ["/bin/sh", "-c", "--" , "while true; do sleep 30; done;"]
5}
Resources that referenc other resources
- Here's an example of a security-group-rule that refers to the security-group it belongs to:
1resource "aws_security_group" "web_server" {
2 name = "webserver-sg"
3 vpc_id = "${data.aws_vpc.default.id}"
4
5}
6
7resource "aws_security_group_rule" "web_server_allow_http_inbound" {
8 type = "ingress"
9 from_port = "100"
10 to_port = "2000"
11 protocol = "tcp"
12 security_group_id = "${aws_security_group.web_server.id}"
13 source_security_group_id = "${aws_security_group.alb.id}"
14}
- In this case, terraform must make sure that the security group is create before the rule is created.
This is done automatically.