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 agent template #241

Open
wants to merge 1 commit into
base: terraform-feature
Choose a base branch
from

Conversation

zzaakiirr
Copy link
Contributor

@zzaakiirr zzaakiirr commented Nov 7, 2024

What does this PR do?

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

Terraform docs

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

Examples

kind: agent
name: agent-name
description: agent description
tags:
  tag: value

Transforms to:

resource "cpln_agent" "agent-name" {
  name = "agent-name"
  description = "agent description"
  tags = {
    tag = value
  }
}

Summary by CodeRabbit

  • New Features

    • Introduced a new Agent class for managing Terraform configurations, allowing users to define agents with attributes like name, description, and tags.
    • Expanded the Generator class to support a new template kind, "agent," enhancing configuration generation capabilities.
    • Added a new YAML configuration file for defining agents.
  • Tests

    • Added tests for the new Agent class and its to_tf method.
    • Created test cases for the Generator class to ensure correct handling of "agent" templates.
  • Chores

    • Updated .gitignore to refine ignored directories.

Copy link

coderabbitai bot commented Nov 7, 2024

Walkthrough

The changes in this pull request include updates to the .gitignore file to restrict the ignoring of the terraform and .controlplane directories to the root level. Additionally, a new Agent class is introduced in agent.rb, which includes methods for initializing agent attributes and generating Terraform configurations. The Generator class is modified to support a new template kind, agent, and corresponding tests are added to validate these changes. A new YAML configuration file for the agent is also introduced.

Changes

File Path Change Summary
.gitignore Updated entries for terraform/ and .controlplane/ to include leading slashes for root-level ignoring.
lib/core/terraform_config/agent.rb Added Agent class with attributes name, description, tags, and methods initialize and to_tf.
lib/core/terraform_config/generator.rb Updated SUPPORTED_TEMPLATE_KINDS to include agent and added agent_config_params method.
spec/command/terraform/generate_spec.rb Added agents to TEMPLATE_CONFIG_PATHS array for testing.
spec/core/terraform_config/agent_spec.rb Introduced tests for #to_tf method in TerraformConfig::Agent.
spec/core/terraform_config/generator_spec.rb Added tests for handling "agent" templates in Generator.
spec/dummy/.controlplane/templates/agent.yml Created new YAML file defining an agent with properties: kind, name, description, and tags.

Possibly related PRs

Suggested labels

approved for merge

Suggested reviewers

  • borela
  • rafaelgomesxyz

🐇 In the garden where changes bloom,
A new agent finds its room.
With tags and names, it takes its flight,
Generating Terraform, oh what a sight!
The .gitignore now stands tall,
Ignoring paths, it heeds the call! 🌱


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.

@zzaakiirr
Copy link
Contributor Author

@coderabbitai review

Copy link

coderabbitai bot commented Nov 7, 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: 1

🧹 Outside diff range and nitpick comments (5)
lib/core/terraform_config/agent.rb (2)

5-13: Consider adding input validation.

While the initialization looks good, consider adding validation for:

  • Ensuring name is not empty or nil
  • Validating tags format if present (should be a hash/dictionary)

Here's a suggested implementation:

 def initialize(name:, description: nil, tags: nil)
   super()
 
+  raise ArgumentError, "Name cannot be empty" if name.nil? || name.empty?
+  raise ArgumentError, "Tags must be a hash" if tags && !tags.is_a?(Hash)
+
   @name = name
   @description = description
   @tags = tags
 end

15-21: Add documentation for the Terraform configuration format.

Consider adding documentation comments to explain the expected Terraform configuration format that will be generated. This would help developers understand the output structure.

+    # Generates Terraform configuration for a Control Plane agent
+    # Example output:
+    # resource "cpln_agent" "agent_name" {
+    #   name        = "agent_name"
+    #   description = "Optional description"
+    #   tags        = { key = "value" }
+    # }
     def to_tf
spec/core/terraform_config/agent_spec.rb (3)

5-7: Consider adding test coverage for invalid configurations.

The current setup only tests the happy path. Consider adding test cases for:

  • Missing required attributes
  • Invalid tag formats
  • Empty or nil values

Example:

context "with invalid configuration" do
  context "when name is missing" do
    let(:options) { { description: "desc", tags: {} } }
    
    it "raises an error" do
      expect { config.to_tf }.to raise_error(ArgumentError)
    end
  end
end

8-18: Add test cases for tag edge cases.

Consider adding test cases for:

  • Empty tags hash
  • Tags with special characters
  • Maximum number of tags (if there's a limit)

Example:

context "with special characters in tags" do
  let(:options) do
    {
      name: "agent-name",
      description: "description",
      tags: { "special@tag" => "value-with-spaces" }
    }
  end
  
  it "properly escapes special characters" do
    # Add expectations
  end
end

19-32: Consider making the assertions more robust.

The current exact string matching might be too brittle. Consider:

  1. Using JSON/HCL parsing to compare the structural equality instead of exact string matching
  2. Adding assertions for individual attributes

Example approach:

it "generates valid configuration" do
  # Parse the generated output as HCL
  parsed = parse_hcl(generated)
  
  # Test individual attributes
  expect(parsed.dig("resource", "cpln_agent", "agent-name", "name")).to eq("agent-name")
  expect(parsed.dig("resource", "cpln_agent", "agent-name", "description")).to eq("agent description")
  expect(parsed.dig("resource", "cpln_agent", "agent-name", "tags")).to eq({
    "tag1" => "true",
    "tag2" => "value"
  })
end
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4b762a8 and 3a73ceb.

📒 Files selected for processing (7)
  • .gitignore (1 hunks)
  • lib/core/terraform_config/agent.rb (1 hunks)
  • lib/core/terraform_config/generator.rb (2 hunks)
  • spec/command/terraform/generate_spec.rb (1 hunks)
  • spec/core/terraform_config/agent_spec.rb (1 hunks)
  • spec/core/terraform_config/generator_spec.rb (1 hunks)
  • spec/dummy/.controlplane/templates/agent.yml (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • .gitignore
  • spec/dummy/.controlplane/templates/agent.yml
🔇 Additional comments (8)
lib/core/terraform_config/agent.rb (2)

1-5: LGTM! Well-structured class definition.

The class follows Ruby conventions and is properly organized within the TerraformConfig module.


15-21: Verify the cpln_agent resource type exists in Terraform provider.

The code generates a cpln_agent resource type. Let's verify its existence and proper usage in the Terraform provider.

✅ Verification successful

The previous search might have been too restrictive. Let's broaden our search to understand the context better and find any provider or resource type definitions.


Let's examine the provider configuration and test files to understand if this is a custom provider and how it's being used.


The cpln_agent resource type is valid and properly configured

The verification shows that:

  • The cpln_agent resource type is part of the controlplane-com/cpln provider, which is properly configured in required_providers.tf
  • The provider source is set to "controlplane-com/cpln" with version "~> 1.0"
  • The test file confirms the expected Terraform configuration format for the resource
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for provider documentation or usage examples
rg -g "*.{tf,md}" "cpln_agent"

Length of output: 30


Script:

#!/bin/bash
# Let's search for any references to cpln_agent in the entire codebase
rg "cpln_agent"

# Also check for any provider-related files or documentation
fd -e tf -e md -e rb "provider|terraform"

Length of output: 465


Script:

#!/bin/bash
# Let's check the provider configuration files to understand the provider setup
cat lib/core/terraform_config/provider.rb lib/core/terraform_config/required_provider.rb lib/core/terraform_config/workload/required_providers.tf

# Also check the test file to understand the expected usage
cat spec/core/terraform_config/agent_spec.rb

Length of output: 1830

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

1-4: LGTM! File setup follows best practices.

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

5-5: LGTM! Addition of 'agent' to supported template kinds.

The change is consistent with the PR objectives and maintains backward compatibility.


107-109: Verify completeness of agent configuration parameters.

The agent_config_params method only extracts basic attributes (name, description, tags), while other template kinds (like gvc_config_params, workload_config_params) extract additional spec-specific parameters. Please verify if there are any agent-specific parameters that should be included.

Let's check the agent template structure and requirements:

✅ Verification successful

Based on the results, I can see that the Agent class in lib/core/terraform_config/agent.rb only has three attributes: name, description, and tags. These exactly match the parameters being extracted by the agent_config_params method. Let me verify if there are any other required parameters by checking the base class and related specs.


Based on the comprehensive verification results, I can now generate the final response:

The agent_config_params implementation is correct and complete

The method correctly extracts all required parameters for agent configuration. This is verified by:

  • The Agent class implementation showing exactly these three attributes: name, description, and tags
  • The agent specs demonstrating these are the only parameters used in testing
  • No additional required parameters found in the base class
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check agent template structure and related files

# Test 1: Find and display agent template examples
echo "Looking for agent template examples..."
fd -e yml -e yaml . | xargs rg -l "kind:\s*agent" -A 10

# Test 2: Check Agent class for required parameters
echo "Checking Agent class implementation..."
rg -A 10 "class\s+Agent" lib/

Length of output: 863


Script:

#!/bin/bash
# Check base class and specs for any additional required parameters

# Test 1: Check the base class implementation
echo "Checking Base class implementation..."
rg -A 5 "class\s+Base" lib/core/terraform_config/

# Test 2: Check agent-related specs
echo "Checking agent-related specs..."
fd -e rb . | xargs rg "describe.*Agent" -A 10

# Test 3: Check for any YAML configuration examples
echo "Checking for agent YAML examples..."
fd -e yaml -e yml . | xargs rg "kind:\s*agent" -B 2 -A 5

Length of output: 1440

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

26-26: LGTM! Addition of 'agents' path aligns with PR objectives.

The addition of 'agents' to TEMPLATE_CONFIG_PATHS correctly extends test coverage for the new agent template type support.

Let's verify the integration with related changes:

✅ Verification successful

✅ Integration verified: Agent template type is fully supported

The verification confirms all necessary components are in place:

  • Agent class implementation exists in lib/core/terraform_config/agent.rb
  • Agent type is included in SUPPORTED_TEMPLATE_KINDS in the generator
  • The addition of 'agents' path in test configuration aligns with the implementation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the presence of supporting agent-related files and configurations

# Test 1: Check for agent template configuration files
echo "Checking for agent template files..."
fd -t f "agent.*\.ya?ml" templates/

# Test 2: Verify agent class implementation
echo "Checking for Agent class implementation..."
rg -l "class\s+Agent" "lib/core/terraform_config/"

# Test 3: Verify generator support for agent type
echo "Checking for agent support in generator..."
rg "SUPPORTED_TEMPLATE_KINDS.*agent" "lib/core/terraform_config/"

Length of output: 595

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

534-561: LGTM! Well-structured test coverage for agent template.

The test context for the agent template kind is well-implemented and follows the established patterns in the file. It effectively validates:

  • The correct output filename
  • The proper instance type
  • The accurate transfer of template fields to the configuration

The use of aggregate_failures ensures comprehensive error reporting.


536-543: Consider expanding test coverage for agent templates.

The current test covers basic fields, but consider adding test cases for:

  1. The 'type' field mentioned in the PR objectives
  2. Any agent-specific configuration fields
  3. Edge cases (e.g., missing required fields, validation scenarios)

Let's check if there are any agent-specific fields we should test:

✅ Verification successful

Test coverage for agent templates appears sufficient

Based on the implementation in agent.rb and existing tests, the current test coverage is adequate because:

  1. The 'type' field mentioned in PR objectives appears to be a migration detail, not a required field in the actual agent configuration
  2. All supported fields (name, description, tags) are already covered in both the implementation and tests
  3. The implementation shows these are the only fields supported, with proper handling of optional fields
  • The agent implementation in lib/core/terraform_config/agent.rb matches exactly what's being tested
  • Both required (name) and optional (description, tags) fields are properly tested
  • The test verifies the correct Terraform resource generation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for agent-related configuration or type definitions
rg -l "type.*agent" --type ruby

Length of output: 33


Script:

#!/bin/bash
# Let's try different search patterns to find agent-related configurations
rg -A 5 "kind.*agent|type.*agent" --type ruby

# Also search for the template structure and validations
rg -A 5 "template.*agent" --type ruby

# Look for any agent-related specs
fd "agent.*spec.rb"

Length of output: 2447


Script:

#!/bin/bash
# Let's check the agent_spec.rb file to understand the required fields and validations
cat spec/core/terraform_config/agent_spec.rb

# Also check for any agent-related implementation files
fd "agent.rb"

Length of output: 830


Script:

#!/bin/bash
# Let's check the agent implementation to see all supported fields
cat lib/core/terraform_config/agent.rb

# Also search for any agent-related migrations or changes that might indicate required fields
rg -A 5 "type.*=>.*agent|type:.*agent" --type ruby

Length of output: 581

spec/core/terraform_config/agent_spec.rb Show resolved Hide resolved
terraform/
.controlplane/
/terraform/
/.controlplane/
Copy link
Contributor Author

Choose a reason for hiding this comment

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

We need to ignore .controlplane folder on root level, otherwise folder spec/dummy/.controlplane is also ignored

@zzaakiirr zzaakiirr marked this pull request as ready for review November 7, 2024 09:12
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.

2 participants