skip to Main Content

I want to seperate data form main code and use them in seperate file similar to local.tf or variables.tf, however even in the docs there is no reference.

use case

I am trying to create access logging for s3 bucket. Target bucket is not managed by s3 so I want to make sure that it exists before using it via data source

resource "aws_s3_bucket" "artifact" {
  bucket   = "jatin-123"
}

data "aws_s3_bucket" "selected" {
  bucket = "bucket.test.com"
}
resource "aws_s3_bucket_logging" "artifacts_server_access_logs" {
  for_each = local.env
  bucket   = data.aws_s3_bucket.selected.id

  target_bucket = local.s3_artifact_access_logs_bucket_name
  target_prefix = "${aws_s3_bucket.artifact[each.key].id}/"
}

2

Answers


  1. Yes, you can have data sources in whatever file you want.
    Terraform basically does not care about the file composition and their names and just lumps all .tf files in the same directory into one big blob.

    Login or Signup to reply.
  2. Yes, of course, you can have. For organization purposes, you SHOULD use different files. When you have a simple project it’s easy to check your code or even troubleshoot within a single file, but when you start to deploy more infrastructure will be a nightmare. So my advice is to start your "small" projects by splitting the through different files.
    Here is my suggestion for you, regarding your example:

    • base.auto.tfvars

      • Here you can put variables that will be used along all the project.
        • E.g: region = us-east-1
          project = web-appliance
    • s3.auto.tfvars

      • Variables that you will use in your s3 bucket
    • s3.tf

      • The code for S3 creation
    • datasource.tf

      • Here you will put all the datasources that you need in your project.
    • provider.tf

      • The configuration for your provider(s). In your example, aws provider
    • versions.tf

      • The versions of your providers
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search