Class: Synthra::Export::Terraform

Inherits:
Object
  • Object
show all
Defined in:
lib/synthra/export/terraform.rb

Overview

Terraform/IaC Export

Generate Terraform configurations for infrastructure that matches your data schemas. Supports DynamoDB, PostgreSQL RDS, and other AWS services.

Examples:

Export to Terraform

exporter = Synthra::Export::Terraform.new(registry)
tf = exporter.export

CLI

$ synthra export --all -f terraform -o main.tf

Constant Summary collapse

DYNAMODB_TYPE_MAP =

Type mapping for DynamoDB

{
  "text" => "S",
  "name" => "S",
  "email" => "S",
  "uuid" => "S",
  "number" => "N",
  "integer" => "N",
  "age" => "N",
  "airport_elevation" => "N",
  "discount" => "N",
  "formula" => "N",
  "row_number" => "N",
  "sequence" => "N",
  "id_sequence" => "N",
  "float" => "N",
  "money" => "N",
  "latitude" => "N",
  "longitude" => "N",
  "airport_latitude" => "N",
  "airport_longitude" => "N",
  "product_price" => "N",
  "tax_rate" => "N",
  "transaction_amount" => "N",
  "boolean" => "S",  # DynamoDB stores as string
  "timestamp" => "S",
  "date" => "S",
  "binary" => "B"
}.freeze
POSTGRES_TYPE_MAP =

Type mapping for PostgreSQL

{
  "text" => "VARCHAR(255)",
  "name" => "VARCHAR(255)",
  "email" => "VARCHAR(255)",
  "paragraph" => "TEXT",
  "uuid" => "UUID",
  "number" => "INTEGER",
  "integer" => "INTEGER",
  "age" => "INTEGER",
  "airport_elevation" => "INTEGER",
  "discount" => "INTEGER",
  "formula" => "INTEGER",
  "row_number" => "INTEGER",
  "sequence" => "INTEGER",
  "id_sequence" => "SERIAL",
  "float" => "DOUBLE PRECISION",
  "money" => "DECIMAL(10,2)",
  "latitude" => "DECIMAL(10,8)",
  "longitude" => "DECIMAL(11,8)",
  "airport_latitude" => "DECIMAL(10,8)",
  "airport_longitude" => "DECIMAL(11,8)",
  "product_price" => "DECIMAL(15,2)",
  "tax_rate" => "DECIMAL(10,4)",
  "transaction_amount" => "DECIMAL(15,2)",
  "boolean" => "BOOLEAN",
  "timestamp" => "TIMESTAMP WITH TIME ZONE",
  "datetime" => "TIMESTAMP WITH TIME ZONE",
  "date" => "DATE",
  "date_between" => "DATE",
  "past_date" => "DATE",
  "future_date" => "DATE",
  "mobile_device_release_date" => "DATE",
  "now" => "DATE",
  "object" => "JSONB",
  "map_by_field" => "JSONB",
  "array" => "TEXT[]"
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(registry, **options) ⇒ Terraform

Create new exporter

Parameters:

  • registry (Registry)

    schema registry

  • options (Hash)

    export options

Options Hash (**options):

  • :provider (Symbol)

    :aws, :gcp, :azure

  • :database (Symbol)

    :dynamodb, :rds_postgres, :rds_mysql

  • :prefix (String)

    resource name prefix

  • :tags (Hash)

    default tags



121
122
123
124
125
126
127
128
129
130
# File 'lib/synthra/export/terraform.rb', line 121

def initialize(registry, **options)
  @registry = registry
  @options = {
    provider: :aws,
    database: :dynamodb,
    prefix: "fake_data",
    region: "us-east-1",
    tags: { "ManagedBy" => "Synthra" }
  }.merge(options)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



88
89
90
# File 'lib/synthra/export/terraform.rb', line 88

def options
  @options
end

#registryObject (readonly)

Returns the value of attribute registry.



88
89
90
# File 'lib/synthra/export/terraform.rb', line 88

def registry
  @registry
end

Instance Method Details

#exportString

Export to Terraform HCL

Returns:

  • (String)

    Terraform configuration



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/synthra/export/terraform.rb', line 136

def export
  sections = []

  # Provider configuration
  sections << provider_block

  # Variables
  sections << variables_block

  # Resources for each schema
  @registry.names.sort.each do |name|
    schema = @registry.schema(name)
    sections << generate_resource(schema)
  end

  # Outputs
  sections << outputs_block

  sections.join("\n\n")
end

#export_as(format) ⇒ String

Export to specific format

Parameters:

  • format (Symbol)

    :hcl or :json

Returns:

  • (String)


162
163
164
165
166
167
168
169
# File 'lib/synthra/export/terraform.rb', line 162

def export_as(format)
  case format
  when :json
    export_json
  else
    export
  end
end

#export_jsonObject (private)



460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/synthra/export/terraform.rb', line 460

def export_json
  # Export as Terraform JSON format
  config = {
    terraform: {
      required_version: ">= 1.0",
      required_providers: {
        aws: {
          source: "hashicorp/aws",
          version: "~> 5.0"
        }
      }
    },
    provider: {
      aws: {
        region: @options[:region]
      }
    },
    resource: {},
    output: {}
  }

  @registry.names.each do |name|
    schema = @registry.schema(name)
    snake_name = underscore(name)

    # Add DynamoDB table
    config[:resource][:aws_dynamodb_table] ||= {}
    config[:resource][:aws_dynamodb_table][snake_name] = {
      name: "#{@options[:prefix]}_#{snake_name}",
      billing_mode: "PAY_PER_REQUEST",
      hash_key: find_key_field(schema),
      attribute: schema.fields.select { |f| f.name == find_key_field(schema) }.map do |f|
        { name: f.name, type: DYNAMODB_TYPE_MAP[f.type_name] || "S" }
      end
    }
  end

  JSON.pretty_generate(config)
end

#find_key_field(schema) ⇒ Object (private)



446
447
448
449
450
451
# File 'lib/synthra/export/terraform.rb', line 446

def find_key_field(schema)
  %w[id uuid _id].each do |key|
    return key if schema.fields.any? { |f| f.name == key }
  end
  schema.fields.first&.name || "id"
end

#find_sort_key(schema) ⇒ Object (private)



453
454
455
456
457
458
# File 'lib/synthra/export/terraform.rb', line 453

def find_sort_key(schema)
  %w[created_at timestamp sort_key].each do |key|
    return key if schema.fields.any? { |f| f.name == key }
  end
  nil
end

#generate_dynamodb(schema) ⇒ Object (private)



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/synthra/export/terraform.rb', line 258

def generate_dynamodb(schema)
  table_name = "#{@options[:prefix]}_#{underscore(schema.name)}"
  key_field = find_key_field(schema)
  sort_key = find_sort_key(schema)

  # Find secondary indexes (fields with 'unique' or commonly indexed)
  gsi_fields = schema.fields.select do |f|
    %w[email username slug].include?(f.name) ||
      f.name.end_with?("_id")
  end

  gsi_blocks = gsi_fields.map do |field|
    <<~GSI
        global_secondary_index {
          name            = "#{field.name}-index"
          hash_key        = "#{field.name}"
          projection_type = "ALL"
        }
    GSI
  end.join("\n")

  attributes = [key_field]
  attributes << sort_key if sort_key
  attributes += gsi_fields.map(&:name)
  attributes = attributes.uniq

  attribute_blocks = attributes.map do |name|
    field = schema.fields.find { |f| f.name == name }
    type = field ? DYNAMODB_TYPE_MAP[field.type_name] || "S" : "S"
    <<~ATTR
        attribute {
          name = "#{name}"
          type = "#{type}"
        }
    ATTR
  end.join("\n")

  sort_key_line = sort_key ? "\n  range_key      = \"#{sort_key}\"" : ""

  <<~HCL
    # DynamoDB table for #{schema.name}
    resource "aws_dynamodb_table" "#{underscore(schema.name)}" {
      name           = "#{table_name}"
      billing_mode   = "PAY_PER_REQUEST"
      hash_key       = "#{key_field}"#{sort_key_line}

    #{attribute_blocks}
    #{gsi_blocks}
      tags = {
        Name   = "#{table_name}"
        Schema = "#{schema.name}"
      }
    }
  HCL
end

#generate_rds_postgres(schema) ⇒ Object (private)



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/synthra/export/terraform.rb', line 314

def generate_rds_postgres(schema)
  table_name = pluralize(underscore(schema.name))

  columns = schema.fields.map do |field|
    pg_type = POSTGRES_TYPE_MAP[field.type_name] || "VARCHAR(255)"
    null = field.optional? || field.nullable? ? "" : " NOT NULL"
    default = field.name == "id" ? " DEFAULT gen_random_uuid()" : ""

    if field.name == "id"
      "  id UUID PRIMARY KEY#{default}"
    else
      "  #{field.name} #{pg_type}#{null}"
    end
  end

  # Add timestamps if not present
  unless schema.fields.any? { |f| f.name == "created_at" }
    columns << "  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()"
  end
  unless schema.fields.any? { |f| f.name == "updated_at" }
    columns << "  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()"
  end

  sql = <<~SQL
    CREATE TABLE IF NOT EXISTS #{table_name} (
    #{columns.join(",\n")}
    );
  SQL

  # Create index statements
  indexes = schema.fields.select { |f| %w[email username slug].include?(f.name) }
  index_sql = indexes.map do |field|
    "CREATE INDEX IF NOT EXISTS idx_#{table_name}_#{field.name} ON #{table_name}(#{field.name});"
  end.join("\n")

  <<~HCL
    # PostgreSQL schema for #{schema.name}
    # Run this SQL to create the table:
    #
    # #{sql.gsub("\n", "\n# ")}
    # #{index_sql.gsub("\n", "\n# ")}

    resource "aws_db_instance" "#{underscore(schema.name)}_db" {
      identifier = "${var.environment}-#{underscore(schema.name)}-db"

      engine         = "postgres"
      engine_version = "15"
      instance_class = "db.t3.micro"

      allocated_storage     = 20
      max_allocated_storage = 100
      storage_type          = "gp3"

      db_name  = "#{underscore(schema.name)}_db"
      username = "admin"
      password = var.db_password

      skip_final_snapshot = var.environment != "production"

      tags = {
        Name   = "${var.environment}-#{underscore(schema.name)}-db"
        Schema = "#{schema.name}"
      }
    }
  HCL
end

#generate_resource(schema) ⇒ Object (private)



245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/synthra/export/terraform.rb', line 245

def generate_resource(schema)
  case @options[:database]
  when :dynamodb
    generate_dynamodb(schema)
  when :rds_postgres
    generate_rds_postgres(schema)
  when :s3
    generate_s3(schema)
  else
    generate_dynamodb(schema)
  end
end

#generate_s3(schema) ⇒ Object (private)



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/synthra/export/terraform.rb', line 381

def generate_s3(schema)
  bucket_name = "#{@options[:prefix]}-#{underscore(schema.name)}-data"

  <<~HCL
    # S3 bucket for #{schema.name} data
    resource "aws_s3_bucket" "#{underscore(schema.name)}" {
      bucket = "#{bucket_name}-${var.environment}"

      tags = {
        Name   = "#{bucket_name}"
        Schema = "#{schema.name}"
      }
    }

    resource "aws_s3_bucket_versioning" "#{underscore(schema.name)}" {
      bucket = aws_s3_bucket.#{underscore(schema.name)}.id
      versioning_configuration {
        status = "Enabled"
      }
    }

    resource "aws_s3_bucket_server_side_encryption_configuration" "#{underscore(schema.name)}" {
      bucket = aws_s3_bucket.#{underscore(schema.name)}.id

      rule {
        apply_server_side_encryption_by_default {
          sse_algorithm = "AES256"
        }
      }
    }
  HCL
end

#outputs_blockObject (private)



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'lib/synthra/export/terraform.rb', line 414

def outputs_block
  outputs = @registry.names.map do |name|
    snake_name = underscore(name)

    case @options[:database]
    when :dynamodb
      <<~OUTPUT
        output "#{snake_name}_table_name" {
          description = "DynamoDB table name for #{name}"
          value       = aws_dynamodb_table.#{snake_name}.name
        }

        output "#{snake_name}_table_arn" {
          description = "DynamoDB table ARN for #{name}"
          value       = aws_dynamodb_table.#{snake_name}.arn
        }
      OUTPUT
    when :rds_postgres
      <<~OUTPUT
        output "#{snake_name}_db_endpoint" {
          description = "RDS endpoint for #{name}"
          value       = aws_db_instance.#{snake_name}_db.endpoint
        }
      OUTPUT
    else
      ""
    end
  end

  outputs.join("\n")
end

#pluralize(str) ⇒ Object (private)

Simple pluralization



100
101
102
103
104
105
106
107
108
# File 'lib/synthra/export/terraform.rb', line 100

def pluralize(str)
  if str.end_with?('s', 'x', 'z', 'ch', 'sh')
    "#{str}es"
  elsif str.end_with?('y') && !%w[a e i o u].include?(str[-2])
    "#{str[0..-2]}ies"
  else
    "#{str}s"
  end
end

#provider_blockObject (private)



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/synthra/export/terraform.rb', line 173

def provider_block
  case @options[:provider]
  when :aws
    <<~HCL
      # Terraform configuration
      terraform {
        required_version = ">= 1.0"

        required_providers {
          aws = {
            source  = "hashicorp/aws"
            version = "~> 5.0"
          }
        }
      }

      provider "aws" {
        region = var.aws_region

        default_tags {
          tags = var.default_tags
        }
      }
    HCL
  when :gcp
    <<~HCL
      terraform {
        required_version = ">= 1.0"

        required_providers {
          google = {
            source  = "hashicorp/google"
            version = "~> 5.0"
          }
        }
      }

      provider "google" {
        project = var.gcp_project
        region  = var.gcp_region
      }
    HCL
  else
    ""
  end
end

#underscore(str) ⇒ Object (private)

Convert CamelCase to snake_case



93
94
95
96
97
# File 'lib/synthra/export/terraform.rb', line 93

def underscore(str)
  str.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
     .gsub(/([a-z\d])([A-Z])/, '\1_\2')
     .downcase
end

#variables_blockObject (private)



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/synthra/export/terraform.rb', line 220

def variables_block
  <<~HCL
    # Variables
    variable "aws_region" {
      description = "AWS region"
      type        = string
      default     = "#{@options[:region]}"
    }

    variable "environment" {
      description = "Environment name"
      type        = string
      default     = "development"
    }

    variable "default_tags" {
      description = "Default tags for all resources"
      type        = map(string)
      default = {
        #{@options[:tags].map { |k, v| "#{k} = \"#{v}\"" }.join("\n    ")}
      }
    }
  HCL
end