8000 Update `atmos.Component` template function for `helmfile` components by aknysh · Pull Request #1217 · cloudposse/atmos · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Update atmos.C 8000 omponent template function for helmfile components #1217

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

Merged
merged 8 commits into from
Apr 25, 2025

Conversation

aknysh
Copy link
Member
@aknysh aknysh commented Apr 25, 2025

what

  • Update atmos.Component template function for helmfile components
  • Add tests
  • Update docs

why

  • atmos.Component template function allows reading any section or attribute from the component (vars, settings, etc.), including the outputs section (Terraform state). Helmfile components don't have Terraform state. This PR adds detecting the component type (terraform or helmfile) when executing atmos.Component, and don't try to read the remote state for the helmfile components
components:
  # Terraform components
  terraform:
    component-1:
      vars:
        foo: "foo"
        bar: "bar"
        baz: "baz

    component-2:
      vars:
        foo: '{{ (atmos.Component "component-1" .stack).outputs.foo }}'
        bar: '{{ (atmos.Component "component-1" .stack).outputs.bar }}'
        baz: '{{ (atmos.Component "component-1" .stack).outputs.bar }}--{{ (atmos.Component "component-1" .stack).outputs.baz }}'

  # Helmfile components
  helmfile:
    component-3:
      vars:
        foo: '{{ (atmos.Component "component-1" .stack).vars.foo }}'
        bar: '{{ (atmos.Component "component-1" .stack).vars.bar }}'
        baz: '{{ (atmos.Component "component-1" .stack).vars.baz }}'

    component-4:
      vars:
        foo: '{{ (atmos.Component "component-1" .stack).outputs.foo }}'
        bar: '{{ (atmos.Component "component-3" .stack).vars.bar }}'
        # Helmfile components don't have `outputs` (terraform output) - this should result in `<no value>` and not throwing errors
        baz: '{{ (atmos.Component "component-3" .stack).outputs.baz }}'

Summary by CodeRabbit

  • New Features

    • Added support for a new output section displaying the component type (terraform or helmfile) when describing a component.
    • Enabled cross-component variable referencing between terraform and helmfile components, with clear handling for missing outputs in helmfile components.
  • Bug Fixes

    • Improved handling and display of outputs for helmfile components, ensuring appropriate placeholders when outputs are not available.
  • Documentation

    • Updated CLI documentation to reflect the new component type output section.
    • Clarified integration documentation for the updated Atmos CLI version.
  • Tests

    • Expanded test coverage to include scenarios with helmfile components and cross-component references.
  • Chores

    • Updated Atmos CLI version to 1.173.0 in Dockerfile and integration workflows.

@aknysh aknysh added the patch A minor, backward compatible change label Apr 25, 2025
@aknysh aknysh self-assigned this Apr 25, 2025
@aknysh aknysh requested a review from a team as a code owner April 25, 2025 13:53
Copy link
mergify bot commented Apr 25, 2025

Important

Cloud Posse Engineering Team Review Required

This pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes.

To expedite this process, reach out to us on Slack in the #pr-reviews channel.

@mergify mergify bot added the needs-cloudposse Needs Cloud Posse assistance label Apr 25, 2025
Copy link
Contribut 8000 or
coderabbitai bot commented Apr 25, 2025
📝 Walkthrough

Walkthrough

This update introduces a new component_type section to the output of the atmos describe component command, indicating whether the component is of type terraform or helmfile. The implementation refactors how component types and outputs are handled and referenced, including the use of new constants for section names. Function signatures are updated to streamline parameter passing, and test coverage is extended to include helmfile components and their behavior regarding outputs. Documentation and configuration files are updated to reflect these changes, and the Atmos version is incremented to 1.173.0 in relevant locations.

Changes

File(s) Change Summary
examples/quick-start-advanced/Dockerfile
website/docs/integrations/atlantis.mdx
Updated the Atmos version from 1.172.0 to 1.173.0 in Dockerfile and Atlantis integration documentation.
internal/exec/describe_component.go Refactored internal logic to introduce and populate a ComponentSection map for tracking component type; switched from hardcoded strings to constants for component types; updated comments.
internal/exec/template_funcs.go Updated the Component method to remove the configAndStacksInfo argument from calls to componentFunc.
internal/exec/template_funcs_component.go Removed configAndStacksInfo parameter from componentFunc; replaced hardcoded section names and component type references with new constants; updated logic to dynamically retrieve component type and outputs section; improved debug logging.
internal/exec/template_funcs_component_test.go Updated tests to match new componentFunc signature; added test cases for helmfile components; verified correct handling of outputs and cross-component references.
pkg/config/const.go Added new constants: ComponentTypeSectionName ("component_type") and OutputsSectionName ("outputs").
tests/fixtures/scenarios/stack-templates-3/atmos.yaml Added a new helmfile component under components with a specified base_path.
tests/fixtures/scenarios/stack-templates-3/stacks/deploy/nonprod.yaml Added component-3 and component-4 under helmfile components; introduced cross-component variable and output references; included a test for the absence of outputs in helmfile components.
website/docs/cli/commands/describe/describe-component.mdx Documented the new component_type output section for the atmos describe component command.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant DescribeComponent
    participant Config
    participant TemplateFuncs

    User->>CLI: Run "atmos describe component"
    CLI->>DescribeComponent: ExecuteDescribeComponent
    DescribeComponent->>Config: Load stacks and config
    DescribeComponent->>DescribeComponent: Determine component type (terraform/helmfile)
    DescribeComponent->>DescribeComponent: Populate ComponentSection with component_type
    DescribeComponent->>TemplateFuncs: Prepare section outputs (using constants)
    DescribeComponent->>CLI: Return merged configuration with component_type section
    CLI->>User: Output component configuration (includes component_type)
Loading

Possibly related PRs

Suggested labels

minor

Suggested reviewers

  • osterman
  • mcalhoun
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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 or @auto-summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @auto-title anywhere in the PR title to generate the title automatically.

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
Contributor
@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: 0

🧹 Nitpick comments (2)
internal/exec/template_funcs_component.go (2)

51-52: Add validation for component type existence and type.

Current implementation assumes sections[cfg.ComponentTypeSectionName] exists and is comparable to cfg.TerraformComponentType. Consider adding validation to handle cases where the component type might be missing or of unexpected type.

-componentType := sections[cfg.ComponentTypeSectionName]
-if componentType == cfg.TerraformComponentType {
+componentType, ok := sections[cfg.ComponentTypeSectionName].(string)
+if !ok {
+    log.Debug("Component type not found or not a string", "component", component, "stack", stack)
+    componentType = ""
+}
+if componentType == cfg.TerraformComponentType {
🧰 Tools
🪛 GitHub Check: golangci-lint

[warning] 52-52:
if componentType == cfg.TerraformComponentType has complex nested blocks (complexity: 5)


52-91: Consider refactoring to reduce complexity.

The static analysis tool flags high complexity in this conditional block. Consider extracting the terraform-specific logic into a separate function to improve readability and maintainability.

func componentFunc(
    atmosConfig *schema.AtmosConfiguration,
    component string,
    stack string,
) (any, error) {
    // ... existing code ...
    
    sections, err := ExecuteDescribeComponent(component, stack, true, true, nil)
    if err != nil {
        return nil, err
    }

    componentType, ok := sections[cfg.ComponentTypeSectionName].(string)
    if !ok {
        log.Debug("Component type not found or not a string", "component", component, "stack", stack)
        componentType = ""
    }
    
    // Process Terraform remote state
    if componentType == cfg.TerraformComponentType {
+        err = processTerraformComponent(atmosConfig, component, stack, sections)
+        if err != nil {
+            return nil, err
+        }
-        // Check if the component in the stack is configured with the 'static' remote state backend,
-        // in which case get the `output` from the static remote state instead of executing `terraform output`
-        remoteStateBackendStaticTypeOutputs, err := GetComponentRemoteStateBackendStaticType(sections)
-        if err != nil {
-            return nil, err
-        }
-
-        if remoteStateBackendStaticTypeOutputs != nil {
-            // Return the static backend outputs
-            terraformOutputs = remoteStateBackendStaticTypeOutputs
-        } else {
-            // Execute `terraform output`
-            terraformOutputs, err = execTerraformOutput(atmosConfig, component, stack, sections)
-            if err != nil {
-                return nil, err
-            }
-        }
-
-        outputs := map[string]any{
-            cfg.OutputsSectionName: terraformOutputs,
-        }
-
-        sections = lo.Assign(sections, outputs)
    }

    // Cache the result
    componentFuncSyncMap.Store(stackSlug, sections)

    log.Debug("Executed template function", "function", functionName)

-    // Print the `outputs` section of the Terraform component
-    if componentType == cfg.TerraformComponentType {
-        y, err2 := u.ConvertToYAML(terraformOutputs)
-        if err2 != nil {
-            log.Error(err2)
-        } else {
-            log.Debug("'outputs' of the template function", "function", functionName, cfg.OutputsSectionName, y)
-        }
-    }

+    // Print debug information if this is a terraform component
+    if componentType == cfg.TerraformComponentType {
+        printTerraformOutputDebug(functionName, sections)
+    }

    return sections, nil
}

+ // processTerraformComponent handles terraform-specific logic for component outputs
+ func processTerraformComponent(
+     atmosConfig *schema.AtmosConfiguration,
+     component string,
+     stack string,
+     sections map[string]any,
+ ) error {
+     // Check if the component has static remote state backend
+     terraformOutputs, err := GetComponentRemoteStateBackendStaticType(sections)
+     if err != nil {
+         return err
+     }
+     
+     // If no static outputs, execute terraform output command
+     if terraformOutputs == nil {
+         terraformOutputs, err = execTerraformOutput(atmosConfig, component, stack, sections)
+         if err != nil {
+             return err
+         }
+     }
+     
+     // Update sections with terraform outputs
+     outputs := map[string]any{
+         cfg.OutputsSectionName: terraformOutputs,
+     }
+     
+     lo.Assign(sections, outputs)
+     return nil
+ }
+
+ // printTerraformOutputDebug logs terraform outputs for debugging
+ func printTerraformOutputDebug(functionName string, sections map[string]any) {
+     if outputs, ok := sections[cfg.OutputsSectionName]; ok {
+         y, err := u.ConvertToYAML(outputs)
+         if err != nil {
+             log.Error(err)
+         } else {
+             log.Debug("'outputs' of the template function", "function", functionName, cfg.OutputsSectionName, y)
+         }
+     }
+ }
🧰 Tools
🪛 GitHub Check: golangci-lint

[warning] 52-52:
if componentType == cfg.TerraformComponentType has complex nested blocks (complexity: 5)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7c5d11d and e40446c.

📒 Files selected for processing (10)
  • examples/quick-start-advanced/Dockerfile (1 hunks)
  • internal/exec/describe_component.go (2 hunks)
  • internal/exec/template_funcs.go (1 hunks)
  • internal/exec/template_funcs_component.go (4 hunks)
  • internal/exec/template_funcs_component_test.go (2 hunks)
  • pkg/config/const.go (1 hunks)
  • tests/fixtures/scenarios/stack-templates-3/atmos.yaml (1 hunks)
  • tests/fixtures/scenarios/stack-templates-3/stacks/deploy/nonprod.yaml (1 hunks)
  • website/docs/cli/commands/describe/describe-component.mdx (1 hunks)
  • website/docs/integrations/atlantis.mdx (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
examples/quick-start-advanced/Dockerfile (1)
Learnt from: aknysh
PR: cloudposse/atmos#775
File: examples/quick-start-advanced/Dockerfile:9-9
Timestamp: 2024-11-12T03:15:15.627Z
Learning: It is acceptable to set `ARG ATMOS_VERSION` to a future version like `1.105.0` in `examples/quick-start-advanced/Dockerfile` if that will be the next release.
🧬 Code Graph Analysis (2)
internal/exec/template_funcs_component_test.go (1)
pkg/utils/yaml_utils.go (1)
  • ConvertToYAML (84-90)
internal/exec/template_funcs_component.go (2)
pkg/config/const.go (3)
  • OutputsSectionName (74-74)
  • ComponentTypeSectionName (73-73)
  • TerraformComponentType (44-44)
pkg/utils/yaml_utils.go (1)
  • ConvertToYAML (84-90)
🪛 LanguageTool
website/docs/cli/commands/describe/describe-component.mdx

[typographical] ~106-~106: To join two clauses or introduce examples, consider using an em dash.
Context: ...ovides configuration - component_type - the type of the component (terraform o...

(DASH_RULE)

🪛 GitHub Check: golangci-lint
internal/exec/template_funcs_component.go

[warning] 52-52:
if componentType == cfg.TerraformComponentType has complex nested blocks (complexity: 5)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Summary
🔇 Additional comments (19)
website/docs/integrations/atlantis.mdx (1)

676-676: Bump ATMOS_VERSION to 1.173.0
Aligns the Atlantis integration example with the newly released Atmos CLI version.

examples/quick-start-advanced/Dockerfile (1)

9-9: Update ATMOS_VERSION build argument
Synchronizes the Docker image build with Atmos CLI v1.173.0.

pkg/config/const.go (1)

73-74: Introduce constants for component_type and outputs
Adds ComponentTypeSectionName and OutputsSectionName to avoid hardcoded strings and improve maintainability.

tests/fixtures/scenarios/stack-templates-3/atmos.yaml (1)

10-11: Register new Helmfile component section
Defines the helmfile component with its base_path to enable Helmfile support in test fixtures.

website/docs/cli/commands/describe/describe-component.mdx (1)

106-107: Document new component_type output section
Adds the component_type bullet to the describe-component docs, reflecting the enhanced output for Terraform and Helmfile components.

🧰 Tools
🪛 LanguageTool

[typographical] ~106-~106: To join two clauses or introduce examples, consider using an em dash.
Context: ...ovides configuration - component_type - the type of the component (terraform o...

(DASH_RULE)

internal/exec/template_funcs.go (1)

40-42: Correct signature update for Component function call

The modification properly aligns with the refactored componentFunc implementation that now dynamically determines the component type rather than requiring it as a parameter.

tests/fixtures/scenarios/stack-templates-3/stacks/deploy/nonprod.yaml (1)

29-41: Good test coverage for helmfile components

The added helmfile components provide good test coverage for cross-component references:

  • Component-3 correctly references vars from the terraform component
  • Component-4 demonstrates proper handling of outputs from terraform components and missing outputs from helmfile components

The comment on line 40 appropriately documents the expected behavior for invalid output references.

internal/exec/template_funcs_component_test.go (3)

65-67: Function call updated correctly

The test has been updated to match the new signature of componentFunc which no longer requires the configAndStacksInfo parameter.


76-85: Good test coverage for helmfile component-3

The test appropriately verifies that helmfile component-3 can reference:

  • Variables from terraform component-1
  • Configuration settings from terraform component-1

This ensures cross-component references work correctly between terraform and helmfile components.


87-97: Comprehensive test for helmfile component-4

The test properly verifies:

  1. That helmfile components can reference outputs from terraform components
  2. That helmfile components can reference vars from other helmfile components
  3. That attempting to access outputs from helmfile components results in <no value>

This covers the key scenarios needed to validate the PR objective of gracefully handling missing outputs in helmfile components.

internal/exec/describe_component.go (6)

13-14: Minor documentation improvement

Added period to the function comment for consistency.


109-109: Good initialization of ComponentSection map

Properly initializes the map that will track component type information.


116-119: Improved component type handling for terraform components

The changes properly:

  1. Use a constant for the component type instead of a hardcoded string
  2. Store the component type in the ComponentSection map for consumer access

120-123: Proper fallback to helmfile component type

Good implementation of fallback logic that:

  1. Tries helmfile if terraform component processing fails
  2. Records the component type appropriately in the ComponentSection map

124-125: Appropriate error handling

Correctly clears the component type in the ComponentSection map if both component types fail, preventing incorrect type information from being returned with the error.


132-133: Minor documentation improvement

Added period to the function comment for consistency.

internal/exec/template_funcs_component.go (3)

32-38: Good use of constants instead of hardcoded strings.

Replacing hardcoded "outputs" with cfg.OutputsSectionName improves maintainability and consistency across the codebase. This change aligns with best practices for avoiding magic strings.


72-73: Good use of constant for output section.

Using cfg.OutputsSectionName instead of hardcoded "outputs" string here is consistent with other changes.


83-91: Conditional output based on component type is a good improvement.

This change properly handles the PR's objective by only attempting to print terraform outputs for terraform components, preventing potential errors with helmfile components.

Copy link
codecov bot commented Apr 25, 2025

Codecov Report

Attention: Patch coverage is 93.33333% with 1 line in your changes missing coverage. Please review.

Project coverage is 31.31%. Comparing base (7c5d11d) to head (e40446c).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/exec/describe_component.go 83.33% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1217      +/-   ##
==========================================
+ Coverage   30.87%   31.31%   +0.43%     
==========================================
  Files         206      206              
  Lines       23038    23044       +6     
==========================================
+ Hits         7114     7216     +102     
+ Misses      14858    14747     -111     
- Partials     1066     1081      +15     
Flag Coverage Δ
unittests 31.31% <93.33%> (+0.43%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@aknysh aknysh added no-release Do not create a new release (wait for additional code changes) and removed patch A minor, backward compatible change labels Apr 25, 2025
@aknysh aknysh requested a review from osterman April 25, 2025 14:40
@aknysh aknysh changed the title Update atmos.Component template functions for helmfile components Update atmos.Component template function for helmfile components Apr 25, 2025
@aknysh aknysh changed the title Update atmos.Component template function for helmfile components Update atmos.Component template function for helmfile components Apr 25, 2025
@aknysh aknysh merged commit 896f8f0 into main Apr 25, 2025
76 of 77 checks passed
@aknysh aknysh deleted the update-templates-for-helmfile branch April 25, 2025 14:53
@mergify mergify bot removed the needs-cloudposse Needs Cloud Posse assistance label Apr 25, 2025
Copy link

These changes were released in v1.173.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-release Do not create a new release (wait for additional code changes)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
0