Skip to content

Conversation

milldr
Copy link
Contributor

@milldr milldr commented Jan 13, 2025

what

  • Added pull through cache
  • Resolve all tflint failures

why

  • Pull caching is directly tied to ECR and can be included with this component
  • We now require TFLint to pass

references

Examples

Enable pull through caching with ECR as such:

  1. Create an AWS Secrets Manager secret
  2. Add your Pull Through Cache rules to the ecr component
components:
  terraform:
    ecr:
      vars:
        enabled: true
...
        pull_through_cache_rules:
          dockerhub:
            registry: "registry-1.docker.io"
            secret: "ecr-pullthroughcache/dockerhub"

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for pull-through cache rules in Amazon ECR.
    • Introduced configuration options for specifying registry credentials.
  • Improvements

    • Updated output syntax for IAM user attributes.
    • Enhanced module flexibility with conditional resource creation.
  • Documentation

    • Updated README with new resource and input parameter details, including examples for pull-through cache configuration.
  • Chores

    • Added .gitignore entry for account-map/ directory.

@milldr milldr requested review from a team as code owners January 13, 2025 17:03
Copy link

coderabbitai bot commented Jan 13, 2025

Walkthrough

The pull request introduces enhancements to the ECR (Elastic Container Registry) component by adding support for pull-through cache rules. This includes a new variable pull_through_cache_rules that allows configuring cache rules with optional secrets, a new resource for creating these rules, and corresponding updates to documentation and outputs. The changes also involve syntax updates for clarity in accessing resource attributes while maintaining the existing module structure.

Changes

File Change Summary
.gitignore Added account-map/ entry to ignore directory pulled from remote repository
src/README.md Added documentation for new aws_ecr_pull_through_cache_rule.this resource and pull_through_cache_rules input parameter
src/main.tf Introduced enabled local variable, new aws_secretsmanager_secret data block, and aws_ecr_pull_through_cache_rule resource
src/outputs.tf Updated output syntax from .* to [*] for ecr_user_name, ecr_user_arn, and ecr_user_unique_id
src/variables.tf Added new pull_through_cache_rules variable with map of objects for cache rule configuration

Sequence Diagram

sequenceDiagram
    participant User as User/Module
    participant ECR as AWS ECR
    participant Secrets as AWS Secrets Manager
    
    User->>ECR: Configure pull-through cache rules
    User->>Secrets: Optionally provide cache credentials
    ECR->>Secrets: Retrieve credentials if specified
    ECR-->>User: Create pull-through cache rules
Loading

Poem

🐰 A Rabbit's Ode to ECR Delight

Pulling images with cache so bright,
Secrets tucked away, out of sight,
Terraform's magic, smooth and clean,
ECR rules now reign supreme!
Hop, hop, hooray for cloud's new might! 🚀


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

mergify bot commented Jan 13, 2025

Merge Protections

Your pull request matches the following merge protections and will not be merged until they are valid.

🟠 Require terratest

Waiting checks: test/terratest.

This rule require terratest status

  • check-success = test/terratest

@mergify mergify bot added the needs-test Needs testing label Jan 13, 2025
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: 0

🧹 Nitpick comments (2)
src/variables.tf (1)

62-69: Enhance variable definition with validation and examples

Add validation and improve the description with examples to make the variable more user-friendly.

Apply this enhancement:

 variable "pull_through_cache_rules" {
   type = map(object({
     registry = string
     secret   = optional(string, "")
   }))
-  description = "Map of pull through cache rules to configure"
+  description = <<-EOT
+    Map of pull through cache rules to configure. Each rule requires:
+    - registry: The upstream registry URL (e.g., public.ecr.aws)
+    - secret: (Optional) The name of the AWS Secrets Manager secret containing credentials
+
+    Example:
+    {
+      "upstream-cache" = {
+        registry = "public.ecr.aws"
+        secret   = "ecr/upstream/credentials"
+      }
+    }
+  EOT
   default     = {}
+
+  validation {
+    condition     = alltrue([
+      for k, v in var.pull_through_cache_rules : 
+      can(regex("^[a-zA-Z0-9][a-zA-Z0-9-]*\\.dkr\\.ecr\\.[a-zA-Z0-9][a-zA-Z0-9-]*\\.amazonaws\\.com$", v.registry))
+    ])
+    error_message = "All registry values must be valid ECR registry URLs"
+  }
 }
src/README.md (1)

90-95: Add usage example for pull-through cache configuration

While the documentation correctly lists the new resource and input parameter, it would be helpful to add an example of how to configure pull-through cache rules in the usage section.

Add this example to the usage section:

         read_only_account_role_map:
           corp: ["*"]
           dev: ["*"]
           prod: ["*"]
           stage: ["*"]
+        pull_through_cache_rules:
+          "upstream-cache":
+            registry: "public.ecr.aws"
+            secret: "ecr/upstream/credentials"  # Optional: AWS Secrets Manager secret name

Also applies to: 122-122

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33b297f and 0adb495.

📒 Files selected for processing (5)
  • .gitignore (1 hunks)
  • src/README.md (2 hunks)
  • src/main.tf (3 hunks)
  • src/outputs.tf (1 hunks)
  • src/variables.tf (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Summary
🔇 Additional comments (4)
src/main.tf (2)

43-51: Add validation for secret existence

The current implementation doesn't validate if the secret exists before attempting to use it. This could lead to runtime errors if a secret is misconfigured.

Add error handling by using a lifecycle block with precondition:

 data "aws_secretsmanager_secret" "cache_credentials" {
   for_each = local.enabled ? {
     for key, rule in var.pull_through_cache_rules :
     key => rule.secret
     if length(rule.secret) > 0
   } : {}

   name = each.value
+
+  lifecycle {
+    precondition {
+      condition     = can(data.aws_secretsmanager_secret.cache_credentials[each.key])
+      error_message = "Secret ${each.value} does not exist in AWS Secrets Manager"
+    }
+  }
 }

53-59: Add validation for registry URLs

The implementation should validate the upstream registry URL format to prevent configuration errors.

Add validation using a lifecycle block:

 resource "aws_ecr_pull_through_cache_rule" "this" {
   for_each = local.enabled ? var.pull_through_cache_rules : {}

   ecr_repository_prefix = each.key
   upstream_registry_url = each.value.registry
   credential_arn        = length(each.value.secret) > 0 ? data.aws_secretsmanager_secret.cache_credentials[each.key].arn : null
+
+  lifecycle {
+    precondition {
+      condition     = can(regex("^[a-zA-Z0-9][a-zA-Z0-9-]*\\.dkr\\.ecr\\.[a-zA-Z0-9][a-zA-Z0-9-]*\\.amazonaws\\.com$", each.value.registry))
+      error_message = "Invalid upstream registry URL format. Must be a valid ECR registry URL."
+    }
+  }
 }
src/outputs.tf (1)

17-27: LGTM! Syntax update improves readability

The change from .* to [*] syntax is a good modernization that aligns with current Terraform best practices.

.gitignore (1)

39-41: LGTM! Well-documented gitignore entry

The addition is properly commented and explains the rationale for including the account-map directory.

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

🧹 Nitpick comments (3)
src/README.md (3)

63-63: Fix article usage before "AWS"

Change "a AWS" to "an AWS" to follow proper English grammar rules.

-To configure a pull through cache rule, you can use the `pull_through_cache_rules` input. Each rule requires a AWS Secrets Manager secret, by name, to be provided.
+To configure a pull through cache rule, you can use the `pull_through_cache_rules` input. Each rule requires an AWS Secrets Manager secret, by name, to be provided.
🧰 Tools
🪛 LanguageTool

[misspelling] ~63-~63: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ..._cache_rules` input. Each rule requires a AWS Secrets Manager secret, by name, to...

(EN_A_VS_AN)


65-76: Enhance the configuration example with additional details

While the example is clear, it would be more helpful to include:

  1. Comments explaining each field
  2. Multiple registry examples (e.g., GitHub Container Registry)
  3. Secret format requirements

Here's an enhanced example:

 ```yaml
 components:
   terraform:
     ecr:
       vars:
         enabled: true
 ...
         pull_through_cache_rules:
+          # Docker Hub configuration
           dockerhub:
+            # Docker Hub registry endpoint
             registry: "registry-1.docker.io"
+            # Secret containing {"username": "user", "password": "pass"}
             secret: "ecr-pullthroughcache/dockerhub"
+          # GitHub Container Registry configuration
+          ghcr:
+            registry: "ghcr.io"
+            secret: "ecr-pullthroughcache/github"

---

`139-139`: **Enhance the input parameter description**

The current description could be more detailed to help users understand the parameter better.

```diff
-| <a name="input_pull_through_cache_rules"></a> [pull_through_cache_rules](#input_pull_through_cache_rules) | Map of pull through cache rules to configure | <pre>map(object({<br/>    registry = string<br/>    secret   = optional(string, "")<br/>  }))</pre> | `{}` | no |
+| <a name="input_pull_through_cache_rules"></a> [pull_through_cache_rules](#input_pull_through_cache_rules) | Map of pull through cache rules to configure. Each rule requires a registry endpoint (e.g., 'registry-1.docker.io' for Docker Hub) and optionally a secret name from AWS Secrets Manager containing registry credentials in {"username": "user", "password": "pass"} format. | <pre>map(object({<br/>    registry = string<br/>    secret   = optional(string, "")<br/>  }))</pre> | `{}` | no |
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0adb495 and e169354.

📒 Files selected for processing (1)
  • src/README.md (3 hunks)
🧰 Additional context used
🪛 LanguageTool
src/README.md

[misspelling] ~63-~63: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ..._cache_rules` input. Each rule requires a AWS Secrets Manager secret, by name, to...

(EN_A_VS_AN)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Summary
🔇 Additional comments (1)
src/README.md (1)

107-107: LGTM!

The resource documentation is well-formatted and includes a helpful link to the Terraform registry.

@milldr milldr added the minor New features that do not break anything label Jan 13, 2025
@milldr milldr merged commit 0a87adf into main Jan 13, 2025
31 of 36 checks passed
@milldr milldr deleted the feat/pull-through-cache branch January 13, 2025 20:01
Copy link

These changes were released in v1.536.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

minor New features that do not break anything needs-test Needs testing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants