Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support terraform config generation from secret template #235

Conversation

zzaakiirr
Copy link
Contributor

@zzaakiirr zzaakiirr commented Oct 10, 2024

What does this PR do?

This PR adds support for converting templates with type: secret to terraform config format

Terraform docs

https://registry.terraform.io/providers/controlplane-com/cpln/latest/docs/resources/secret

Examples

  1. For aws secret:
kind: secret
name: aws
description: aws
tags:
  tag1: AKIAIOSFODNN7EXAMPLE
  tag2: arn:awskey
type: aws
data:
  accessKey: AKIAIOSFODNN7EXAMPLE
  externalId: '123'
  roleArn: arn:awskey
  secretKey: '123'

Transforms to:

resource "cpln_secret" "aws" {
  name = "aws"
  description = "aws"
  tags = {
    tag1 = "AKIAIOSFODNN7EXAMPLE"
    tag2 = "arn:awskey"
  }
  aws {
    secret_key = "123"
    access_key = "AKIAIOSFODNN7EXAMPLE"
    role_arn = "arn:awskey"
    external_id = "123"
  }
}
  1. For azure-connector secret:
kind: secret
name: azure-connector
description: azure_connector
tags:
  tag1: tag-val
type: azure-connector
data:
  code: '123'
  url: https://sdfsfs.com

Transforms to:

resource "cpln_secret" "azure-connector" {
  name = "azure-connector"
  description = "azure_connector"
  tags = {
    tag1 = "tag-val"
  }
  azure_connector {
    url = "https://sdfsfs.com"
    code = "123"
  }
}
  1. For azure-sdk-secret secret:
kind: secret
name: azure-sdk-secret
description: azure-sdk-secret
type: azure-sdk
data: >-
  {"subscriptionId":"subscriptionId","tenantId":"tenantId","clientId":"clientId","clientSecret":"CONFIDENTIAL"}

Transforms to:

resource "cpln_secret" "azure-sdk-secret" {
  name = "azure-sdk-secret"
  description = "azure-sdk-secret"
  azure_sdk = "{"subscriptionId":"subscriptionId","tenantId":"tenantId","clientId":"clientID","clientSecret":"CONFIDENTIAL"}"
}
  1. For dictionary secret:
kind: secret
name: dictionary
description: dictionary
tags: {}
type: dictionary
data:
  sdfdsf: '2222'

Transforms to:

resource "cpln_secret" "dictionary" {
  name = "dictionary"
  description = "dictionary"
  tags = {

  }
  dictionary = {
    sdfdsf = "2222"
  }
}

Supported all types of secrets which can be created in CPLN:
image

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for a new template kind, "secret," enhancing template processing capabilities.
    • Introduced a new Secret class to manage secret configurations in Terraform.
    • Enhanced string handling to support multi-line strings in the DSL.
  • Bug Fixes

    • Improved error handling in key transformation methods for robustness.
  • Tests

    • Added comprehensive tests for the new Secret class and updated tests for the Generator class to cover new functionality.
    • Introduced tests for the underscore_keys method in the Hash class.

@zzaakiirr
Copy link
Contributor Author

@coderabbitai full review

Copy link

coderabbitai bot commented Oct 10, 2024

✅ Actions performed

Full review triggered.

Copy link

coderabbitai bot commented Oct 10, 2024

Walkthrough

The changes in this pull request include modifications to several classes and methods within the Terraform configuration modules. Key updates involve the introduction of a new template kind "secret," enhancements to string handling, and the addition of error-handling methods in the Hash class. New tests have been created for the TerraformConfig::Generator and TerraformConfig::Secret classes. These changes collectively enhance the functionality and robustness of the Terraform configuration management.

Changes

File Path Change Summary
lib/command/terraform/generate.rb Updated generate_app_config to include secret in template processing. Test suite updated to include secrets.tf.
lib/core/terraform_config/dsl.rb Modified tf_value method to handle multi-line strings with heredoc syntax.
lib/core/terraform_config/generator.rb Added support for "secret" template kind; updated filename and tf_config methods, and introduced secret_config method.
lib/core/terraform_config/gvc.rb Changed initialize method to streamline processing of load_balancer attribute.
lib/core/terraform_config/secret.rb Introduced Secret class for managing secret configurations, with methods for initialization and Terraform resource generation.
lib/patches/hash.rb Added symbolize_keys and underscore_keys methods to Hash class with error handling.
lib/patches/string.rb Enhanced underscore method to handle additional string transformations.
spec/core/terraform_config/generator_spec.rb Added tests for unsupported template kinds and for "secret" template kind in generator_spec.rb.
spec/core/terraform_config/secret_spec.rb New test suite for TerraformConfig::Secret class, validating the to_tf method for various secret types.
spec/pathces/hash_spec.rb New test suite for Hash class testing #underscore_keys method with string and symbol keys.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Generator
    participant Secret
    participant Terraform

    User->>Generator: Request to generate configuration
    Generator->>Generator: Check template kind
    alt Kind is "secret"
        Generator->>Secret: Create new Secret instance
        Secret->>Terraform: Generate Terraform resource block
        Terraform-->>Generator: Return generated block
    else Kind is "gvc" or "identity"
        Generator->>Terraform: Process existing templates
    end
    Generator-->>User: Return configuration
Loading

🐇 "In the garden of code, changes bloom bright,
New secrets to guard, in the soft moonlight.
With templates now varied, and strings that can sing,
We hop through the logic, oh what joy it brings!
So let’s celebrate this, with a dance and a cheer,
For every new feature, we hold dear!" 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e1d0440 and a58bcf9.

📒 Files selected for processing (2)
  • lib/core/terraform_config/secret.rb (1 hunks)
  • spec/core/terraform_config/secret_spec.rb (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • lib/core/terraform_config/secret.rb
  • spec/core/terraform_config/secret_spec.rb

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 17

🧹 Outside diff range and nitpick comments (10)
lib/patches/hash.rb (1)

4-7: Effective implementation of symbolize_keys, consider refactoring error handling

The symbolize_keys method effectively converts all keys to symbols while handling potential errors. However, the use of a rescue modifier, while compact, can reduce readability.

Consider refactoring to use a block form of error handling for improved clarity:

def symbolize_keys
  transform_keys do |key|
    begin
      key.to_sym
    rescue
      key
    end
  end
end

This approach maintains the functionality while improving readability and removing the need for the Rubocop disable comment.

lib/patches/string.rb (2)

21-24: Approve changes with suggestions for improvement

The updated underscore method significantly improves the string conversion functionality. However, I have a few suggestions:

  1. The comment "Copied from Rails" might be misleading if the implementation has been modified. Consider updating it to "Adapted from Rails" or add a note about any modifications.

  2. The method doesn't handle non-ASCII characters, which could be a limitation in some cases. Consider adding a note about this limitation in the method's documentation.

  3. To improve clarity, consider adding examples in the method's documentation to illustrate its behavior with different input types (e.g., namespaced constants, mixed case strings, strings with hyphens).

Would you like me to provide an example of how the documentation could be improved with these suggestions?


Line range hint 1-1: Consider explaining rubocop disables

The file uses rubocop disable comments for Style/OptionalBooleanParameter and Lint/UnderscorePrefixedVariableName. While it's good that these are scoped to just this file, it would be helpful to add a brief comment explaining why these rules are disabled. This can help future maintainers understand the reasoning behind these exceptions.

Would you like me to suggest a format for adding these explanations?

Also applies to: 26-26

lib/core/terraform_config/generator.rb (2)

31-32: LGTM: Consistent handling of secret configurations.

The addition of the "secret" case in the tf_config method is consistent with the existing pattern and correctly calls the new secret_config method.

For consistency with the other cases, consider using a single-line format:

when "secret" then secret_config

71-79: LGTM: Well-structured secret configuration method.

The secret_config method is implemented correctly and consistently with other configuration methods in the class. It properly initializes a TerraformConfig::Secret instance with the necessary attributes from the template object.

Consider adding error handling or validation to ensure the template object contains all required attributes. This could prevent potential runtime errors if the template is malformed. For example:

def secret_config
  required_keys = %w[name description type data tags]
  missing_keys = required_keys - template.keys
  raise ArgumentError, "Missing required keys: #{missing_keys.join(', ')}" unless missing_keys.empty?

  TerraformConfig::Secret.new(
    name: template["name"],
    description: template["description"],
    type: template["type"],
    data: template["data"],
    tags: template["tags"]
  )
end

This addition would make the method more robust and easier to debug if issues arise.

spec/core/terraform_config/generator_spec.rb (2)

10-17: LGTM! Consider using a constant for the error message.

The new test case for unsupported template kinds is well-structured and correctly verifies the error handling. Good use of :aggregate_failures for multiple assertions.

Consider defining the error message as a constant in the TerraformConfig::Generator class to ensure consistency across the codebase:

# In TerraformConfig::Generator class
UNSUPPORTED_KIND_ERROR = "Unsupported template kind - %s".freeze

# In the test
expect { generator.tf_config }.to raise_error(TerraformConfig::Generator::UNSUPPORTED_KIND_ERROR % template['kind'])
expect { generator.filename }.to raise_error(TerraformConfig::Generator::UNSUPPORTED_KIND_ERROR % template['kind'])

This approach would make it easier to maintain consistent error messages and update them if needed.


102-125: LGTM! Consider adding a test for the 'data' field.

The new test case for the "secret" template kind is well-structured and correctly verifies the basic attributes of the secret. Good use of :aggregate_failures for multiple assertions.

To improve test coverage, consider adding an assertion to verify that the 'data' field is correctly handled by the TerraformConfig::Secret instance. You can add this assertion after line 120:

expect(tf_config.data).to eq({ "key1" => "key1_value", "key2" => "key2_value2" })

This will ensure that the secret data is correctly passed to and stored in the TerraformConfig::Secret instance.

lib/core/terraform_config/secret.rb (3)

36-36: Raise a more specific exception for invalid secret types

Raising a generic RuntimeError may make error handling less clear for users of this class. Consider raising a more specific exception, such as ArgumentError, to provide clearer context about the nature of the error.

Apply this diff to specify the exception type:

-raise "Invalid secret type given - #{type}"
+raise ArgumentError, "Invalid secret type given - #{type}"

88-94: Handle optional chain argument consistently

In the tls_tf method, the chain argument is fetched with a default of nil and marked as optional:

argument :chain, data.fetch(:chain, nil), optional: true

Since fetch with a default value will not raise an error if the key is missing, you can simplify it by using data[:chain]:

Apply this diff for consistency and readability:

-argument :chain, data.fetch(:chain, nil), optional: true
+argument :chain, data[:chain], optional: true

96-102: Ensure consistent handling of optional arguments

In the userpass_tf method, the encoding argument is optional. Similar to the previous comment, consider using data[:encoding] for consistency:

Apply this diff:

-argument :encoding, data.fetch(:encoding, nil), optional: true
+argument :encoding, data[:encoding], optional: true
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1a87e3e and 152452a.

📒 Files selected for processing (12)
  • lib/command/terraform/generate.rb (1 hunks)
  • lib/core/terraform_config/dsl.rb (1 hunks)
  • lib/core/terraform_config/generator.rb (3 hunks)
  • lib/core/terraform_config/gvc.rb (1 hunks)
  • lib/core/terraform_config/secret.rb (1 hunks)
  • lib/patches/hash.rb (1 hunks)
  • lib/patches/string.rb (1 hunks)
  • spec/command/terraform/generate_spec.rb (1 hunks)
  • spec/core/terraform_config/generator_spec.rb (2 hunks)
  • spec/core/terraform_config/secret_spec.rb (1 hunks)
  • spec/dummy/.controlplane/templates/secret.yml (1 hunks)
  • spec/pathces/hash_spec.rb (1 hunks)
🧰 Additional context used
🪛 Gitleaks
spec/core/terraform_config/secret_spec.rb

244-284: Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.

(private-key)


23-23: Identified a pattern that may indicate AWS credentials, risking unauthorized cloud resource access and data breaches on AWS platforms.

(aws-access-token)


174-174: Identified a pattern that may indicate AWS credentials, risking unauthorized cloud resource access and data breaches on AWS platforms.

(aws-access-token)


87-87: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


357-357: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


302-486: Identified a Private Key, which may compromise cryptographic security and sensitive data encryption.

(private-key)

spec/dummy/.controlplane/templates/secret.yml

1-6: Possible Kubernetes Secret detected, posing a risk of leaking credentials/tokens from your deployments

(kubernetes-secret-with-data-after)

🔇 Additional comments (12)
lib/patches/hash.rb (3)

1-1: Good use of frozen_string_literal: true

The use of frozen_string_literal: true is a good practice. It helps improve performance and prevents accidental string mutations.


1-17: Overall, well-implemented extensions to the Hash class

The additions to the Hash class provide useful utility methods for key transformation. Both symbolize_keys and underscore_keys are implemented with proper error handling, ensuring robustness.

The suggestions provided earlier aim to improve:

  1. Readability of the symbolize_keys method by using a block form for error handling.
  2. Robustness of the underscore_keys method by adding a dependency check.

These changes will enhance the overall quality and maintainability of the code.


9-16: Effective implementation of underscore_keys, consider adding a dependency check

The underscore_keys method effectively converts keys to underscored format while preserving the original key type (string or symbol). The error handling is well-implemented.

However, the method relies on the underscore method, which is not part of Ruby's standard library. It's likely from ActiveSupport. Consider adding a check to ensure the required library is available:

def underscore_keys
  raise "Required method 'underscore' not found. Ensure ActiveSupport is included." unless "".respond_to?(:underscore)

  transform_keys do |key|
    underscored = key.to_s.underscore
    key.is_a?(Symbol) ? underscored.to_sym : underscored
  rescue StandardError
    key
  end
end

This addition will provide a clear error message if the required dependency is missing.

Let's verify the presence of the underscore method in the codebase:

spec/pathces/hash_spec.rb (1)

1-7: LGTM: Well-structured test file setup

The file is well-structured with proper use of the frozen_string_literal pragma and spec_helper requirement. The RSpec structure is clear and follows best practices.

lib/core/terraform_config/gvc.rb (1)

27-27: Improved readability with potential performance benefits. Verify method availability.

The change from a custom transform_keys block to using underscore_keys and symbolize_keys methods improves code readability while maintaining the same functionality. This approach is likely more efficient, depending on the implementation of these methods.

Please ensure that underscore_keys and symbolize_keys methods are available in the project's context. They might be part of a custom extension or a library like ActiveSupport. Run the following script to verify the availability and usage of these methods:

If these methods are custom implementations, ensure they are properly tested and documented.

✅ Verification successful

Verification Successful: underscore_keys and symbolize_keys methods are defined and available.

The methods underscore_keys and symbolize_keys are defined in lib/patches/hash.rb and are consistently used across the codebase. This confirms their availability and correct implementation, ensuring that the change maintains the intended functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the availability and usage of underscore_keys and symbolize_keys methods

# Test 1: Check for method definitions or inclusions
echo "Searching for method definitions or inclusions:"
rg --type ruby -e '(def (underscore_keys|symbolize_keys)|include .*Support)'

# Test 2: Check for usage of these methods in other files
echo "Searching for usage of these methods in other files:"
rg --type ruby -e '(underscore_keys|symbolize_keys)'

# Test 3: Check for ActiveSupport inclusion or requiring
echo "Checking for ActiveSupport inclusion or requiring:"
rg --type ruby -e '(include ActiveSupport|require .active_support.)'

Length of output: 1333

lib/core/terraform_config/dsl.rb (1)

Line range hint 1-44: Overall assessment of changes

The modifications to the tf_value method in the TerraformConfig::Dsl module enhance its capability to handle multi-line strings in Terraform configurations. This improvement allows for more flexible and readable representation of complex string values.

The changes are well-contained within the tf_value method and don't introduce breaking changes to the module's interface. The existing functionality for single-line strings and expressions is preserved, ensuring backward compatibility.

While the implementation achieves its goal, there's room for further refinement as suggested in the previous comment. These refinements would make the method more flexible and robust, catering to various use cases and coding standards.

To ensure that these changes don't negatively impact other parts of the codebase, please run the following verification:

These checks will help identify any potential conflicts or areas that might need adjustment due to the new multi-line string handling.

lib/core/terraform_config/generator.rb (2)

16-17: LGTM: Appropriate filename for secret configurations.

The addition of the "secret" case in the filename method is consistent with the existing pattern and provides an appropriate filename for secret configurations.


Line range hint 1-91: Summary: Successful implementation of secret template support.

The changes to the Generator class effectively implement support for the new "secret" template kind. The modifications are consistent with existing patterns and integrate well with the current structure. The new secret_config method appropriately handles the creation of TerraformConfig::Secret instances.

A few minor suggestions have been made for potential improvements:

  1. Consistent formatting in the tf_config method.
  2. Adding error handling in the secret_config method.

Overall, these changes enhance the functionality of the Terraform configuration generator by adding support for secret templates.

lib/command/terraform/generate.rb (1)

50-50: 🛠️ Refactor suggestion

Consider a more flexible approach for template kind filtering

The addition of 'secret' to the allowed template kinds aligns with the PR objective of supporting secret templates. However, there are a few points to consider:

  1. The TODO comment above this line suggests that this filtering is temporary. It would be beneficial to address this comment and implement a more permanent solution.

  2. The current approach of explicitly listing allowed kinds might not be scalable if more template kinds are added in the future.

  3. It's not clear what happens to templates that don't match these kinds. Are they silently skipped?

Consider refactoring this to use a more flexible approach. For example:

ALLOWED_TEMPLATE_KINDS = %w[gvc identity secret].freeze

# ...

next unless ALLOWED_TEMPLATE_KINDS.include?(template["kind"])

This allows for easier management of allowed kinds and makes it simpler to add or remove kinds in the future.

For a long-term solution, consider implementing a strategy pattern where each template kind has its own handler. This would eliminate the need for this kind of filtering altogether and make it easier to add new template kinds in the future.

To ensure this change doesn't introduce any regressions, let's verify the usage of template kinds across the codebase:

This will help us understand if there are any other places in the code that might need to be updated to handle the new 'secret' template kind.

✅ Verification successful

Addition of 'secret' to allowed template kinds verified

The addition of 'secret' to the allowed template kinds aligns with the objective of supporting secret templates. However, please note the existing TODO comment indicates that this filtering is intended to be temporary and should be revisited once all template kinds are supported.

  • Location: lib/command/terraform/generate.rb line 50
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of template kinds across the codebase

echo "Searching for template kind usage:"
rg --type ruby -i 'template\[["'']kind["'']\]'

echo "\nSearching for 'secret' usage in relation to templates:"
rg --type ruby -i 'secret.*template|template.*secret'

Length of output: 1164


Script:

#!/bin/bash
# Description: Search for TODO comments related to template kind filtering across the codebase

echo "Searching for TODOs in template kind filtering:"
rg --type ruby -i 'TODO.*template["kind"]|template["kind"].*TODO'

Length of output: 172


Script:

#!/bin/bash
# Description: Search for all TODO comments in lib/command/terraform/generate.rb

echo "Searching for TODO comments in lib/command/terraform/generate.rb:"
rg --type ruby 'TODO' lib/command/terraform/generate.rb

Length of output: 271

spec/command/terraform/generate_spec.rb (1)

102-104: LGTM! Verify impact on other test cases.

The addition of secrets.tf to the app_config_files method aligns with the PR objective of supporting secret template conversion to Terraform config. This change is consistent and doesn't introduce any issues.

To ensure all test cases are updated accordingly, please run the following script to check for any occurrences of app_config_files method calls or expectations:

If the script returns any results, please review those occurrences to ensure they account for the new secrets.tf file.

✅ Verification successful

Verification Passed

The addition of secrets.tf to the app_config_files method has been successfully verified. No other test cases are affected by this change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for occurrences of app_config_files method calls or expectations

# Test: Search for app_config_files method calls or expectations
rg --type ruby -g '!generate_spec.rb' 'app_config_files'

Length of output: 56


Script:

#!/bin/bash
# Description: Comprehensive search for all occurrences of app_config_files and related test assertions

# Search for all occurrences of app_config_files across the entire codebase
echo "Searching for all usages of app_config_files method:"
rg --type ruby 'app_config_files'

# Search for test expectations related to the number of config files
echo -e "\nSearching for test expectations on the number of config files:"
rg --type ruby 'expect.*\.to\s+(eq|match)' spec/

Length of output: 26642

spec/core/terraform_config/generator_spec.rb (1)

Line range hint 1-125: Overall, great additions to the test suite!

The new test cases for unsupported template kinds and the "secret" template kind significantly improve the coverage of the TerraformConfig::Generator class. These additions will help ensure the robustness of the generator when dealing with various template types.

The structure of the tests is consistent with the existing ones, making the file easy to read and maintain. The use of :aggregate_failures in both new contexts is a good practice for cleaner test output.

With the suggested minor improvements (using a constant for the error message and adding a test for the 'data' field in the secret context), this update will provide comprehensive coverage for the new functionality.

lib/core/terraform_config/secret.rb (1)

1-104: Overall Implementation Looks Good

The Secret class is well-structured, and methods are appropriately defined for each secret type. The use of metaprogramming with dynamic method calls simplifies the code and makes it extensible.

spec/dummy/.controlplane/templates/secret.yml Show resolved Hide resolved
spec/dummy/.controlplane/templates/secret.yml Show resolved Hide resolved
spec/dummy/.controlplane/templates/secret.yml Show resolved Hide resolved
spec/pathces/hash_spec.rb Outdated Show resolved Hide resolved
spec/pathces/hash_spec.rb Outdated Show resolved Hide resolved
spec/core/terraform_config/secret_spec.rb Outdated Show resolved Hide resolved
spec/core/terraform_config/secret_spec.rb Outdated Show resolved Hide resolved
spec/core/terraform_config/secret_spec.rb Outdated Show resolved Hide resolved
spec/core/terraform_config/secret_spec.rb Outdated Show resolved Hide resolved
spec/core/terraform_config/secret_spec.rb Outdated Show resolved Hide resolved
@zzaakiirr
Copy link
Contributor Author

@coderabbitai review

Copy link

coderabbitai bot commented Oct 10, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (4)
lib/core/terraform_config/dsl.rb (1)

37-44: Excellent implementation of multi-line string handling!

The changes to the tf_value method address the previous suggestions effectively:

  1. The heredoc delimiter is now configurable.
  2. The indentation for multi-line strings is customizable.
  3. Whitespace in multi-line strings is preserved.

These improvements enhance the flexibility and robustness of the Terraform configuration generation.

For improved code clarity, consider extracting the multi-line string handling into a separate private method:

def tf_value(value, heredoc_delimiter: "EOF", multiline_indent: 2)
  value = value.to_s if value.is_a?(Symbol)

  return value unless value.is_a?(String)
  return value if expression?(value)
  return "\"#{value}\"" unless value.include?("\n")

  format_multiline_string(value, heredoc_delimiter, multiline_indent)
end

private

def format_multiline_string(value, delimiter, indent)
  "#{delimiter}\n#{value.indent(indent)}\n#{delimiter}"
end

This refactoring would make the main method more concise and easier to read.

spec/pathces/hash_spec.rb (2)

17-23: LGTM: Consider adding a test for deeper nesting

This test case effectively demonstrates that only top-level keys are transformed. However, to ensure comprehensive coverage, consider adding a test case with deeper nesting to verify the behavior remains consistent at multiple levels.

Here's a suggested additional test:

it "does not transform keys in deeper nested levels" do
  deep_nested_hash = { "outerCamelCase" => { "innerCamelCase" => { "deeperCamelCase" => "value" } } }
  expect(deep_nested_hash.underscore_keys).to eq(
    "outer_camel_case" => { "innerCamelCase" => { "deeperCamelCase" => "value" } }
  )
end

1-73: Overall: Excellent test coverage with room for minor improvements

This test suite for Hash#underscore_keys is comprehensive and well-structured. It covers various scenarios including empty hashes, nested hashes, already underscored keys, keys with special characters and numbers, and both string and symbol keys. The tests are clear, concise, and isolate different cases effectively.

To further enhance the test suite, consider the following suggestions:

  1. Add a test for deeper nesting levels, as mentioned earlier.
  2. Include a test case with a mix of string and symbol keys in the same hash.
  3. Consider adding a performance test for large hashes to ensure the method scales well.

These additions would make an already strong test suite even more robust.

lib/core/terraform_config/secret.rb (1)

56-65: Consider adding a comment explaining the use of send

The use of send to dynamically call methods is intentional and controlled in this context, as discussed in previous reviews. However, to improve code clarity and prevent future misunderstandings, consider adding a comment explaining why send is used here and how it's kept safe.

For example:

# Dynamic method call is safe here as the method names are strictly controlled
# by the case statement and correspond to private methods defined in this class.
send("#{type.underscore}_tf")

This comment would help future maintainers understand the design decision quickly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 152452a and e1d0440.

📒 Files selected for processing (4)
  • lib/core/terraform_config/dsl.rb (1 hunks)
  • lib/core/terraform_config/secret.rb (1 hunks)
  • spec/core/terraform_config/secret_spec.rb (1 hunks)
  • spec/pathces/hash_spec.rb (1 hunks)
🧰 Additional context used
📓 Learnings (1)
lib/core/terraform_config/secret.rb (1)
Learnt from: zzaakiirr
PR: shakacode/control-plane-flow#235
File: lib/core/terraform_config/secret.rb:34-34
Timestamp: 2024-10-10T14:56:14.688Z
Learning: In this project, it's acceptable to use `send` to call private methods when the method names are strictly controlled through constructs like `case` statements, ensuring only expected methods are invoked.
🪛 Gitleaks
spec/core/terraform_config/secret_spec.rb

87-87: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (7)
spec/pathces/hash_spec.rb (5)

9-15: LGTM: Good coverage of edge case

This test case appropriately checks the behavior of underscore_keys with an empty hash, which is an important edge case to consider.


25-31: LGTM: Good test for idempotence

This test case effectively verifies that the underscore_keys method is idempotent, ensuring that already underscored keys remain unchanged. This is an important property to maintain.


33-39: LGTM: Comprehensive edge case coverage

This test case effectively covers important edge cases by including keys with numbers and special characters. It ensures that the underscore_keys method can handle these scenarios correctly, which is crucial for robust functionality.


41-55: LGTM: Thorough coverage of string key scenarios

These test cases provide comprehensive coverage for various string key formats, including camelCase, snake_case, and keys with multiple uppercase letters. The separate tests for each scenario allow for easy isolation of potential issues.


57-71: LGTM: Consistent coverage for symbol keys

These test cases mirror the string key tests, providing consistent coverage for symbol key formats. This parallel structure ensures that the underscore_keys method behaves consistently regardless of whether the keys are strings or symbols.

lib/core/terraform_config/secret.rb (2)

42-54: Well-structured data preparation and validation

The prepare_data and validate_required_data_keys! methods are well-implemented:

  1. The use of tap in prepare_data is a clean Ruby idiom.
  2. The validation logic in validate_required_data_keys! is thorough and raises a clear ArgumentError when required keys are missing.
  3. The methods work together to ensure data consistency and completeness.

This approach enhances the robustness of the secret creation process. Good job!


1-132: Overall, well-implemented and flexible secret management

This Secret class provides a comprehensive and flexible way to manage various types of secrets for Terraform configurations. Key strengths include:

  1. Clear structure and organization of code.
  2. Robust data preparation and validation.
  3. Flexible handling of different secret types.
  4. Good use of Ruby idioms and practices.

While there are opportunities for refactoring to reduce complexity and improve maintainability, the overall implementation is solid and well-thought-out. Great job on creating a versatile solution for secret management!

lib/core/terraform_config/secret.rb Outdated Show resolved Hide resolved
lib/core/terraform_config/secret.rb Outdated Show resolved Hide resolved
spec/core/terraform_config/secret_spec.rb Outdated Show resolved Hide resolved
spec/core/terraform_config/secret_spec.rb Outdated Show resolved Hide resolved
spec/core/terraform_config/secret_spec.rb Outdated Show resolved Hide resolved
@zzaakiirr
Copy link
Contributor Author

@coderabbitai review

Copy link

coderabbitai bot commented Oct 10, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@zzaakiirr zzaakiirr marked this pull request as ready for review October 10, 2024 16:10
Copy link
Collaborator

@rafaelgomesxyz rafaelgomesxyz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 💯

Left just a couple nits, which you can address before merging if you want. No need to ask for a re-review.

lib/core/terraform_config/generator.rb Outdated Show resolved Hide resolved
lib/core/terraform_config/secret.rb Outdated Show resolved Hide resolved
Base automatically changed from create-gvc-and-identity-tf-configs-from-templates to terraform-feature October 21, 2024 09:15
…e-flow into support-terraform-config-generation-from-secret-template
@zzaakiirr zzaakiirr merged commit fa966c8 into terraform-feature Oct 21, 2024
5 checks passed
@zzaakiirr zzaakiirr deleted the support-terraform-config-generation-from-secret-template branch October 21, 2024 09:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants