skip to Main Content

I Am trying to create S3 bucket module, currently i am stuck with one scenario. For example user don’t bucket to be encrypted then kms key shouldn’t be created. It is working till here, how ever there is a variable kms_policy. Now even if i set encrypt_s3_bucket false during validation it is asking me to pass variable.

resource "aws_kms_key" "mykey" {
  count = var.encrypt_s3_bucket ? 1:0
  description             = "This key is used to encrypt bucket objects"
  deletion_window_in_days = 10
  enable_key_rotation = false
  multi_region = false
  policy = var.encrypt_s3_bucket ? var.kms_policy : null
}

variables.tf

variable "kms_policy" {
  type = string
}

2

Answers


  1. Its not possible to skip variable creation. Instead make a default value, and this way it will not ask you for the variable all the time.

    variable "kms_policy" {
      default = null
      type = string
    }
    
    Login or Signup to reply.
  2. It seems that you have an implied dependency between two of your input variables: if encrypt_s3_bucket is true then kms_policy must be set, but if encrypt_s3_bucket is false then it need not be set.

    In a situation like that, I would suggest combining both of these into a single variable so that it’s clearer that they are strongly connected. For example:

    variable "s3_bucket_encryption" {
      type = object({
        kms_policy = string
      })
      default = null
    }
    

    This declares a single variable called s3_bucket_encryption whose type constraint is for an object type with a kms_policy attribute. The user of this module can then choose either to leave that variable unset (null), or to set it to an object with a policy specified:

      s3_bucket_encryption = {
        kms_policy = "..."
      }
    

    Notice that there’s now no way to enable S3 bucket encryption without providing a policy, and also no way to provide a policy without enabling encryption.

    Then to use this within your module:

    resource "aws_kms_key" "mykey" {
      count = var.s3_bucket_encryption != null ? 1 : 0
    
      description             = "This key is used to encrypt bucket objects"
      deletion_window_in_days = 10
      enable_key_rotation     = false
      multi_region            = false
      policy                  = var.s3_bucket_encryption.kms_policy
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search