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

feat: create new gh action to retag container image #1

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

joshuagibeonm
Copy link

@joshuagibeonm joshuagibeonm commented Feb 13, 2025

Summary by CodeRabbit

  • New Features
    • Introduced the "Image Retag" GitHub Action to streamline container image management by automatically pulling an image, tagging it with a new identifier, and pushing it to a target registry.
    • Now you can easily specify both the source image and the new target image when using the action.

Copy link

coderabbitai bot commented Feb 13, 2025

Walkthrough

This pull request introduces a new GitHub Action called "Image Retag." The action automates the process of pulling a container image from a source, tagging it with a new identifier, and then pushing the retagged image to a target registry. It uses a composite run structure with three sequential steps and requires two input parameters: image_source and image_target.

Changes

File Path Change Summary
.github/actions/image-retag/action.yml Added new "Image Retag" action with description, required inputs (image_source & image_target), and a composite run sequence to pull, tag, and push a container image.

Sequence Diagram(s)

sequenceDiagram
    participant Action as "Image Retag Action"
    participant Docker as "Docker Registry"
    Action->>Docker: Pull image (image_source)
    Action->>Action: Tag the image as (image_target)
    Action->>Docker: Push image (image_target)
Loading

Poem

I'm a rabbit with a coder's flair,
Hopping through actions with utmost care.
I pull, I tag, then push on cue,
A container journey shiny and new.
With whiskers twitching, I celebrate this debut!


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.

@joshuagibeonm joshuagibeonm marked this pull request as ready for review February 14, 2025 02:30
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

🧹 Nitpick comments (2)
.github/actions/image-retag/action.yml (2)

3-10: Consider adding input validation for image parameters.

While the input parameters are well-defined, consider adding pattern validation to ensure the image references follow valid Docker image naming conventions.

Add pattern validation using this diff:

 inputs:
   image_source:
     description: 'The source image to pull.'
     required: true
+    pattern: '^[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*(/[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*)*:[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*$'
   image_target:
     description: 'The target image to tag and push.'
     required: true
+    pattern: '^[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*(/[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*)*:[a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*$'

22-22: Add newline at end of file.

Add a newline character at the end of the file to comply with YAML standards.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 22-22: no new line character at the end of file

(new-line-at-end-of-file)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a28aaef and 8351412.

📒 Files selected for processing (1)
  • .github/actions/image-retag/action.yml (1 hunks)
🧰 Additional context used
🪛 YAMLlint (1.35.1)
.github/actions/image-retag/action.yml

[error] 22-22: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (1)
.github/actions/image-retag/action.yml (1)

1-2: LGTM!

The action name and description are clear and descriptive.

Comment on lines +11 to +22
runs:
using: composite
steps:
- name: Pull docker images
shell: bash
run: docker pull ${{ inputs.image_source }}
- name: Tag docker images
shell: bash
run: docker tag ${{ inputs.image_source }} ${{ inputs.image_target }}
- name: Push docker images
shell: bash
run: docker push ${{ inputs.image_target }}
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🛠️ Refactor suggestion

🧩 Analysis chain

Add error handling and registry authentication support.

The current implementation has the following limitations:

  1. No error handling for docker commands
  2. No support for authenticating with private registries

Consider these improvements:

 runs:
   using: composite
   steps:
+    - name: Check docker daemon
+      shell: bash
+      run: |
+        if ! docker info > /dev/null 2>&1; then
+          echo "Error: Docker daemon is not running"
+          exit 1
+        fi
+    - name: Docker login
+      shell: bash
+      run: |
+        if [[ "${{ inputs.image_source }}" == *"docker.io"* ]] || [[ "${{ inputs.image_target }}" == *"docker.io"* ]]; then
+          echo "Please configure DOCKER_USERNAME and DOCKER_PASSWORD secrets if pulling from or pushing to Docker Hub"
+        fi
     - name: Pull docker images
       shell: bash
-      run: docker pull ${{ inputs.image_source }}
+      run: |
+        if ! docker pull ${{ inputs.image_source }}; then
+          echo "Error: Failed to pull image ${{ inputs.image_source }}"
+          exit 1
+        fi
     - name: Tag docker images
       shell: bash
-      run: docker tag ${{ inputs.image_source }} ${{ inputs.image_target }}
+      run: |
+        if ! docker tag ${{ inputs.image_source }} ${{ inputs.image_target }}; then
+          echo "Error: Failed to tag image ${{ inputs.image_source }} as ${{ inputs.image_target }}"
+          exit 1
+        fi
     - name: Push docker images
       shell: bash
-      run: docker push ${{ inputs.image_target }}
+      run: |
+        if ! docker push ${{ inputs.image_target }}; then
+          echo "Error: Failed to push image ${{ inputs.image_target }}"
+          exit 1
+        fi

Let's verify if there are any best practices or recommendations for Docker authentication in GitHub Actions:


🌐 Web query:

What are the best practices for Docker authentication in GitHub Actions?

💡 Result:

To ensure secure and efficient Docker authentication in GitHub Actions workflows, follow these best practices based on industry standards and official documentation:

Credential Management

  • Use GitHub Secrets for storing sensitive credentials like Docker access tokens[1][5][9]
  • Avoid password authentication - use personal access tokens (PATs) instead of account passwords[5][7]
  • Create separate credentials with:
    • Read-only access for pull operations
    • Write access only for CI/CD pipelines needing push privileges[6]

Authentication Methods

For different container registries:

Registry Authentication Method
Docker Hub username: ${{ secrets.DOCKERHUB_USERNAME }}, password: ${{ secrets.DOCKERHUB_TOKEN }}[2][5]
GHCR Use automatic GITHUB_TOKEN[2][10] or PAT with repo/write:packages scope[5][10]
AWS ECR Use AWS credentials or temporary tokens via configure-aws-credentials action[2][5]
Google GCR/GAR Workload Identity Federation or JSON key authentication[2][5][6]
Azure ACR Service principal credentials[2][5]

Security Best Practices

  1. Principle of Least Privilege

    • Restrict GITHUB_TOKEN permissions[3][6][8]
    permissions:
      contents: read
      packages: write
  2. Third-Party Action Security

    • Pin actions to full-length commit SHA instead of tags[6][8]
    • Audit actions from Marketplace before use[8]
  3. Workflow Hardening

    • Use environment-specific secrets[6]
    • Avoid string interpolation in run steps[6]
    # Unsafe
    - run: echo "Using secret ${{ secrets.MY_SECRET }}"
    
    # Safe
    - run: echo "Using secret" 
      env:
        MY_SECRET: ${{ secrets.MY_SECRET }}

Cross-Registry Authentication Example

- name: Login to multiple registries
  uses: docker/login-action@v3
  with:
    registry: |
      ghcr.io
      docker.io
    username: |
      ${{ github.actor }}
      ${{ vars.DOCKERHUB_USERNAME }}
    password: |
      ${{ secrets.GITHUB_TOKEN }}
      ${{ secrets.DOCKERHUB_PAT }}

Advanced Configurations

  • For AWS Public ECR:
    - uses: docker/login-action@v3
      with:
        registry: public.ecr.aws
        username: ${{ secrets.AWS_ACCESS_KEY_ID }}
        password: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
  • For Google Artifact Registry using Workload Identity:
    - uses: google-github-actions/auth@v1
      with:
        workload_identity_provider: projects/123456789/locations/global/workloadIdentityPools/my-pool/providers/my-provider
        service_account: [email protected]
    
    - uses: docker/login-action@v3
      with:
        registry: us-docker.pkg.dev
        username: oauth2accesstoken
        password: ${{ steps.auth.outputs.access_token }}

Implementing these practices ensures secure credential handling while maintaining workflow efficiency across different container registries[2][5][6][8]. Regularly audit your workflows using tools like OpenSSF Scorecards and GitHub's built-in security features to maintain compliance with evolving security standards[8].

Citations:


Key Improvements Required: Robust error handling and secure Docker registry authentication.

The current composite action lacks proper error handling for Docker operations and does not actually authenticate with registries using secure credentials. Based on recent best practices:

  • Docker Daemon Check: Confirm that the Docker daemon is running before executing any Docker commands.
  • Registry Authentication: Instead of only warning about Docker Hub, perform an actual login using GitHub Secrets (e.g., DOCKERHUB_USERNAME and DOCKERHUB_TOKEN), which aligns with industry recommendations.
  • Command Error Handling: Each Docker command (pull, tag, push) should verify success and abort on failure.
  • File Formatting: Append a newline at the end of the file to satisfy static analysis requirements.

Below is an updated diff snippet incorporating these suggestions:

 runs:
   using: composite
   steps:
+    - name: Check Docker Daemon
+      shell: bash
+      run: |
+        if ! docker info > /dev/null 2>&1; then
+          echo "Error: Docker daemon is not running"
+          exit 1
+        fi
+    - name: Docker Login (for Docker Hub)
+      shell: bash
+      env:
+        DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
+        DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
+      run: |
+        if [[ "${{ inputs.image_source }}" == *"docker.io"* ]] || [[ "${{ inputs.image_target }}" == *"docker.io"* ]]; then
+          echo "Logging into Docker Hub"
+          if ! docker login -u "$DOCKERHUB_USERNAME" -p "$DOCKERHUB_TOKEN"; then
+            echo "Error: Docker login failed"
+            exit 1
+          fi
+        fi
     - name: Pull docker images
       shell: bash
-      run: docker pull ${{ inputs.image_source }}
+      run: |
+        if ! docker pull ${{ inputs.image_source }}; then
+          echo "Error: Failed to pull image ${{ inputs.image_source }}"
+          exit 1
+        fi
     - name: Tag docker images
       shell: bash
-      run: docker tag ${{ inputs.image_source }} ${{ inputs.image_target }}
+      run: |
+        if ! docker tag ${{ inputs.image_source }} ${{ inputs.image_target }}; then
+          echo "Error: Failed to tag image ${{ inputs.image_source }} as ${{ inputs.image_target }}"
+          exit 1
+        fi
     - name: Push docker images
       shell: bash
-      run: docker push ${{ inputs.image_target }}
+      run: |
+        if ! docker push ${{ inputs.image_target }}; then
+          echo "Error: Failed to push image ${{ inputs.image_target }}"
+          exit 1
+        fi

Additional Note: Ensure the file ends with a newline.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
runs:
using: composite
steps:
- name: Pull docker images
shell: bash
run: docker pull ${{ inputs.image_source }}
- name: Tag docker images
shell: bash
run: docker tag ${{ inputs.image_source }} ${{ inputs.image_target }}
- name: Push docker images
shell: bash
run: docker push ${{ inputs.image_target }}
runs:
using: composite
steps:
- name: Check Docker Daemon
shell: bash
run: |
if ! docker info > /dev/null 2>&1; then
echo "Error: Docker daemon is not running"
exit 1
fi
- name: Docker Login (for Docker Hub)
shell: bash
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
run: |
if [[ "${{ inputs.image_source }}" == *"docker.io"* ]] || [[ "${{ inputs.image_target }}" == *"docker.io"* ]]; then
echo "Logging into Docker Hub"
if ! docker login -u "$DOCKERHUB_USERNAME" -p "$DOCKERHUB_TOKEN"; then
echo "Error: Docker login failed"
exit 1
fi
fi
- name: Pull docker images
shell: bash
run: |
if ! docker pull ${{ inputs.image_source }}; then
echo "Error: Failed to pull image ${{ inputs.image_source }}"
exit 1
fi
- name: Tag docker images
shell: bash
run: |
if ! docker tag ${{ inputs.image_source }} ${{ inputs.image_target }}; then
echo "Error: Failed to tag image ${{ inputs.image_source }} as ${{ inputs.image_target }}"
exit 1
fi
- name: Push docker images
shell: bash
run: |
if ! docker push ${{ inputs.image_target }}; then
echo "Error: Failed to push image ${{ inputs.image_target }}"
exit 1
fi
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 22-22: no new line character at the end of file

(new-line-at-end-of-file)

Comment on lines +5 to +8
description: 'The source image to pull.'
required: true
image_target:
description: 'The target image to tag and push.'
Copy link
Contributor

Choose a reason for hiding this comment

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

nits: removed the quotation for consistency and the article that I feel is redundant because every input will end up needing articles. Unless you want to emphasis it, we don't need articles.

Suggested change
description: 'The source image to pull.'
required: true
image_target:
description: 'The target image to tag and push.'
description: Source image to pull.
required: true
image_target:
description: Target image to tag and push.

Copy link
Contributor

Choose a reason for hiding this comment

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

Also, I'd like to ask you to remove the period in the description for consistency.

Ref:

description: Environment variable name of the Cloud Run service

runs:
using: composite
steps:
- name: Pull docker images
Copy link
Contributor

Choose a reason for hiding this comment

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

nits: proper product name and make it singular.

Suggested change
- name: Pull docker images
- name: Pull Docker image

- name: Pull docker images
shell: bash
run: docker pull ${{ inputs.image_source }}
- name: Tag docker images
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
- name: Tag docker images
- name: Tag Docker image

- name: Tag docker images
shell: bash
run: docker tag ${{ inputs.image_source }} ${{ inputs.image_target }}
- name: Push docker images
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
- name: Push docker images
- name: Push Docker image

Comment on lines +4 to +7
image_source:
description: 'The source image to pull.'
required: true
image_target:
Copy link
Contributor

Choose a reason for hiding this comment

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

I think the action name already explains what it does, so maybe we don't need the prefix image_.

Suggested change
image_source:
description: 'The source image to pull.'
required: true
image_target:
source:
description: 'The source image to pull.'
required: true
target:

IMHO, even in the example below, people can understand that the source and the target are for images.

- uses: .../image-retag
  with:
    source: reearth
    target: reearth-mirror

run: docker tag ${{ inputs.image_source }} ${{ inputs.image_target }}
- name: Push docker images
shell: bash
run: docker push ${{ inputs.image_target }}
Copy link
Contributor

Choose a reason for hiding this comment

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

nits: last line.

Suggested change
run: docker push ${{ inputs.image_target }}
run: docker push ${{ inputs.image_target }}

@joshuagibeonm joshuagibeonm marked this pull request as draft February 18, 2025 01:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants