Home > Back-end >  Create Terraform resource if variable is not null
Create Terraform resource if variable is not null

Time:11-18

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_object_lock_configuration

So basically I want to make a resource creation optional only if the variable object_lock_enabled is declared. It's an optional variable and if it exists, the bucket recreation is forced and I don't want that with other environments, only for the production.

prod.tfvars

object_lock_enabled = true

main.tf

    module "voucher_s3_bucket" {
      source  = "terraform-aws-modules/s3-bucket/aws"
      version = "3.4.0"
    
      bucket                                = local.voucher_bucket_name
      object_lock_enabled                   = var.object_lock_enabled
   }
.
.
.
    resource "aws_s3_bucket_object_lock_configuration" "example" {
      bucket = 'mybucket'
    
      rule {
        default_retention {
          mode = "COMPLIANCE"
          days = 5
        }
      }
    }

variables.tf

variable "object_lock_enabled" {
  description = "Enable object lock on bucket"
  type        = bool
  default     = null
}

but TF_VAR_env=platform terragrunt plan returns Error during operation: argument must not be null I tried adding this line to the configuration resource bloc

count = var.object_lock_enabled == null ? 0 : 1

But I still get the same error.

CodePudding user response:

You can just use false instead of null as a default value:

variable "object_lock_enabled" {
  description = "Enable object lock on bucket"
  type        = bool
  default     = false # <----
}

and keep:

object_lock_enabled = var.object_lock_enabled
  • Related