Home > Enterprise >  Terraform : difference between referencing using local and resource
Terraform : difference between referencing using local and resource

Time:10-19

I have the following piece of code which creates bucket and enables versioning.

Here I am referencing bucket using locals

resource "aws_s3_bucket_versioning" "sample" {
  bucket = local.bucket_name
  versioning_configuration {
    status = "Enabled"
  }
}

In this code I am referencing using

resource "aws_s3_bucket_versioning" "sample" {
  bucket = aws_s3_bucket.sample.bucket
  versioning_configuration {
    status = "Enabled"
  }
}

I think both does the same work, but my mentor said writing with resource is better code as it decreases the chances of errors because using locals terraform wont understand the dependencies snd might provision versioning before provisioning bucket.

My point is I think terraform is smart enough to resolve dependencies, is it still true when we reference using locals.

Tere is an article about this ( in japanese ) https://dev.classmethod.jp/articles/dependency-in-terraform/

CodePudding user response:

Your mentor is correct. aws_s3_bucket.sample.bucket is better then local.bucket_name. This is because it makes code easier to maintain and modify. For example, if you have code as follows:

resource "aws_s3_bucket" "sample" {
  bucket = local.bucket_name
}

resource "aws_s3_bucket_versioning" "sample" {
  bucket = local.bucket_name
}

Then any changes in aws_s3_bucket, to let say

resource "aws_s3_bucket" "sample" {
  bucket = var.bucket_name
}

will require you to manual change aws_s3_bucket_versioning as well. Its easy if you have small code, but if not, then this can be quite troublesome.

In contrast, if you have

resource "aws_s3_bucket" "sample" {
  bucket = local.bucket_name
}

resource "aws_s3_bucket_versioning" "sample" {
  bucket = aws_s3_bucket.sample.bucket
}

then changing aws_s3_bucket

resource "aws_s3_bucket" "sample" {
  bucket = var.bucket_name
}

will automatically translate to the rest of code. You do not have to manually change aws_s3_bucket_versioning and fix bucket name.

  • Related