Git Hub Notes
Git Hub Notes
GitHub Actions is a continuous integration and continuous deployment (CI/CD) platform that
enables developers to automate workflows directly within a GitHub repository. It allows you to
define custom workflows to build, test, package, and deploy applications efficiently.
Key Features:
A. Workflows
Example Workflow
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install Dependencies
run: npm install
- name: Run Tests
run: npm test
B. Jobs
A job is a group of steps executed in the same runner environment. Jobs run in parallel by
default but can be configured to run sequentially.
Job Dependencies
You can define dependencies between jobs using the needs keyword.
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Build Project
run: echo "Building the project..."
test:
runs-on: ubuntu-latest
needs: build # Runs only after the "build" job is complete
steps:
- name: Run Tests
run: echo "Running tests..."
C. Steps
D. Actions
Actions are reusable units of code used in workflows. You can use:
action.yml
Use it in a workflow:
- name: Run Custom Action
uses: ./path-to-action
with:
name: "GitHub User"
Key-value pairs:
name: "Workflow Name"
Lists (arrays):
steps:
- name: First Step
run: echo "Hello"
- name: Second Step
run: echo "World"
Nested structures:
job:
steps:
- name: Step 1
run: echo "Hello"
Expressions (${{ }}):
run: echo "Branch: ${{ github.ref }}"
Common Expressions
Example:
runs-on: ubuntu-latest
B. Self-Hosted Runners
Self-hosted runners are custom machines you manage. They support Linux, macOS, and
Windows.
Advantages
Disadvantages
Would you like mock interview questions or real-world workflow examples to deepen your
understanding?
Sure! Let's break down GitHub Actions workflow configuration in-depth, covering every key
aspect so that you can confidently answer any interview question.
Why is it important?
1. GitHub automatically detects workflows in this directory.
2. It provides an organized way to manage automation for your repository.
3. It enables easy collaboration and version control of workflows.
touch .github/workflows/my-workflow.yml
on:
push:
branches:
- main # Runs on pushes to main
tags:
- 'v*' # Runs when a tag matching 'v*' (e.g., v1.0) is pushed
paths:
- 'src/**' # Runs only if files in the src/ directory change
on:
pull_request:
branches:
- main
types:
- opened
- synchronize
- reopened
- closed
Use Case
You can use push and pull_request together to run tests on both direct commits and PRs.
on:
push:
branches:
- main
pull_request:
branches:
- main
You can schedule workflows to run at specific times using cron syntax.
Example
on:
schedule:
- cron: '0 2 * * *'
Cron Format
More Examples
Example
on:
workflow_dispatch:
inputs:
environment:
description: 'Select Environment'
required: true
default: 'staging'
type: choice
options:
- development
- staging
- production
How to trigger?
Example
on:
repository_dispatch:
types: [deploy]
This waits for an external service to send a POST request with { "event_type": "deploy" }.
How to trigger?
Send a POST request using GitHub API:
Basic Structure
jobs:
job1:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
Breakdown
test:
runs-on: ubuntu-latest
needs: build
steps:
- name: Run tests
run: echo "Running tests"
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14, 16, 18]
steps:
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test
This will run tests for Node.js 14, 16, and 18 in parallel.
steps:
- uses: actions/checkout@v4 # Checks out repo
- uses: actions/setup-node@v4
with:
node-version: 16
Conclusion
By mastering these concepts, you’ll be able to handle any GitHub Actions interview question.
Here are some key takeaways:
Would you like to go over real-world examples or do a mock interview session to test your
understanding?
In GitHub Actions, an Action is a reusable unit of code that automates tasks within a workflow.
Actions help simplify workflow steps by encapsulating logic in a modular way. They are often
used to:
Types of Actions
jobs:
example-job:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4 # Uses a prebuilt action from GitHub Marketplace
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 18
- name: Run a Node.js script
run: node -e "console.log('Hello, world!')"
A. JavaScript Actions
JavaScript actions are useful when you need to run logic directly within GitHub Actions using
Node.js.
try {
const name = core.getInput("name");
const greeting = `Hello, ${name}!`;
core.setOutput("greeting", greeting);
console.log(greeting);
} catch (error) {
core.setFailed(error.message);
}
Run:
npm init -y
npm install @actions/core
git add .
git commit -m "Initial commit"
git push origin main
jobs:
greeting-job:
runs-on: ubuntu-latest
steps:
- name: Greet
uses: your-username/your-action-repo@main
with:
name: "Alice"
B. Docker-Based Actions
Docker-based actions run inside a container, allowing you to use any programming language.
FROM ubuntu:20.04
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
#!/bin/sh
echo "Hello from Docker Action!"
jobs:
example-job:
runs-on: ubuntu-latest
steps:
- name: Run Custom Docker Action
uses: your-username/your-action-repo@main
Final Thoughts
Mastering GitHub Actions requires:
Would you like hands-on exercises or real-world scenarios to deepen your understanding?
GitHub Actions is a powerful CI/CD tool that allows you to automate workflows for your
repository. When dealing with sensitive information (like API keys, passwords, or tokens),
securely managing secrets and environment variables is crucial. This guide will provide a deep
dive into how GitHub Actions handles secrets and environment variables, best practices, and
security considerations.
GitHub Secrets are encrypted environment variables stored securely and used in workflows.
They help prevent exposing sensitive data in repositories.
1. Repository Secrets – Defined at the repository level and available only in that
repository.
2. Environment Secrets – Specific to GitHub Environments (e.g., staging, production).
3. Organization Secrets – Available to multiple repositories in an organization.
4. Actions and Workflow Secrets – Used within GitHub Actions but not hardcoded in
workflows.
Setting Up Repository Secrets
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Use Secret
env:
API_KEY: ${{ secrets.API_KEY }}
run: echo "Using API key"
✅Do NOT store secrets in your code. Avoid committing .env files with sensitive data.
✅Use GitHub Actions secrets instead of plaintext environment variables.
✅Restrict access – Only provide secrets to workflows that need them.
✅Rotate secrets regularly to minimize security risks.
✅Use repository and organization secrets appropriately (org-wide for shared secrets, repo-
level for repo-specific ones).
1. Workflow-Level
2. Job-Level
3. Step-Level
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Print Variables
run: echo "Using Node.js version $NODE_VERSION and API URL $API_URL"
Defined within a specific job and not accessible outside that job.
jobs:
build:
runs-on: ubuntu-latest
env:
NODE_VERSION: 18
steps:
- name: Print Node Version
run: echo "Node version is $NODE_VERSION"
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Set Environment Variable
env:
NODE_VERSION: 18
run: echo "Using Node.js $NODE_VERSION"
When secrets are echoed or logged in workflows, they might be exposed. GitHub automatically
masks values from secrets.*, but you should also take precautions.
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Print Secret
env:
API_KEY: ${{ secrets.API_KEY }}
run: echo "API Key: $API_KEY"
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Mask Custom Value
run: |
echo "::add-mask::SuperSecretValue"
echo "My secret is SuperSecretValue"
Best Practices
Organization secrets are secrets that can be shared across multiple repositories in an
organization.
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Use Org Secret
env:
API_KEY: ${{ secrets.ORG_API_KEY }}
run: echo "Using org-wide API key"
✅Use organization secrets for shared credentials (e.g., cloud service API keys).
✅Limit secret access to necessary repositories only.
✅Use repository-level secrets for repository-specific credentials.
✅Regularly audit and rotate secrets.
jobs:
setup:
runs-on: ubuntu-latest
steps:
- name: Fetch Secret from External Source
run: |
SECRET=$(curl -s https://example.com/get-secret)
echo "::add-mask::$SECRET"
echo "SECRET=$SECRET" >> $GITHUB_ENV
Key Takeaways
GitHub Secrets are encrypted environment variables used for security.
Use env: to define variables at workflow, job, or step levels.
Secrets are automatically masked in logs, but use ::add-mask:: for additional security.
Organization secrets help manage shared credentials across repositories.
Follow best practices: avoid hardcoding, restrict access, and rotate secrets regularly.
By mastering these concepts, you’ll be well-prepared to handle any interview question related
to secrets and environment variables in GitHub Actions. Want to test your knowledge with
some real interview-style questions?
Dependency management is a critical aspect of CI/CD workflows, ensuring that all required
libraries, modules, and packages are installed efficiently, consistently, and securely.
Understanding how to manage dependencies in GitHub Actions (or other CI/CD tools) can
significantly optimize build times and improve security.
1. Installing Dependencies in Workflows
When setting up a CI/CD pipeline, the first step is ensuring that dependencies are installed
properly. This typically involves using a package manager such as npm, pip, yarn, composer, bundler,
or gradle.
Each language has its own package manager that should be leveraged in CI/CD pipelines:
Node.js (npm/yarn)
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
Breakdown:
Python (pip)
Java (Gradle)
✅Use caching when dependencies don’t change often (e.g., npm modules, pip packages).
❌Avoid caching when dependencies are constantly updated (e.g., projects using latest versions).
1. Generate a Personal Access Token (PAT) in GitHub (Settings > Developer Settings > Tokens).
2. Store it as a GitHub Secret (e.g., GH_PAT).
3. Authenticate in the workflow:
Private package registries (like GitHub Packages, Nexus, Artifactory) require authentication.
Example: Authenticating npm with GitHub Packages
With this knowledge, you should be fully prepared for any interview question about
dependency management in CI/CD workflows! 🚀
Alright, let's break down these advanced workflow features in GitHub Actions in extreme
depth so you can confidently answer any interview question on them.
jobs:
example:
runs-on: ubuntu-latest
steps:
- name: Run only on main branch
if: github.ref == 'refs/heads/main'
run: echo "This step runs only on main!"
Common Conditions
Condition Description
github.ref == 'refs/heads/main' Runs only if the workflow is triggered on the main branch.
Condition Description
github.event_name == 'pull_request' Runs only if the workflow is triggered by a pull request event.
github.actor == 'your-username' Runs only if a specific user triggered the workflow.
success(), failure(), cancelled(), always() Controls execution based on the status of previous steps.
jobs:
example:
runs-on: ubuntu-latest
steps:
- name: Check modified files
id: changes
uses: dorny/paths-filter@v2
with:
filters: |
docs:
- 'docs/**'
- name: Run if docs changed
if: steps.changes.outputs.docs == 'true'
run: echo "Docs have changed!"
Basic Syntax
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node: [14, 16, 18]
steps:
- name: Print environment
run: echo "Running on ${{ matrix.os }} with Node.js ${{ matrix.node }}"
How to Use?
Define a reusable workflow in one repository.
Call it from another workflow using uses:.
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- run: echo "Deploying to ${{ inputs.environment }}!"
jobs:
deploy:
uses: repo-owner/repo-a/.github/workflows/reusable.yml@main
with:
environment: production
✅Reduces duplication
✅Makes maintenance easier
✅Ensures consistency across repositories
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
If a new CI workflow starts on the same branch, the previous one is canceled.
concurrency:
group: production-deploy
cancel-in-progress: false
needs: ensures that a job runs only after another job completes successfully.
test:
needs: build
runs-on: ubuntu-latest
steps:
- run: echo "Running tests"
deploy:
needs: test
runs-on: ubuntu-latest
steps:
- run: echo "Deploying to production"
jobs:
setup:
runs-on: ubuntu-latest
steps:
- run: echo "Setting up"
lint:
needs: setup
runs-on: ubuntu-latest
steps:
- run: echo "Linting the code"
test:
needs: setup
runs-on: ubuntu-latest
steps:
- run: echo "Running tests"
deploy:
needs: [lint, test]
runs-on: ubuntu-latest
steps:
- run: echo "Deploying"
jobs:
deploy:
needs: test
if: always()
runs-on: ubuntu-latest
steps:
- run: echo "Deploying even if tests fail"
🚀 Only the failed matrix entry stops; others continue. You can use fail-fast: false to prevent
stopping all jobs.
🚀 The calling workflow fails. You can handle this using if: always() in the parent workflow.
4. How do you prevent two workflows from running at the same time?
This should give you expert-level confidence! Want me to test you with some interview-style
scenarios? 🚀
GitHub Actions is a powerful tool for automating software workflows, but without proper
security measures, it can introduce significant vulnerabilities. Below is an in-depth analysis of
four crucial security best practices:
permissions:
contents: read # Grants only read access to the repository content
actions: none # No permission to modify actions
pull-requests: write # If the job needs to add comments to PRs
jobs:
deploy:
permissions:
contents: write # Only this job has write access
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Access a Secret
env:
API_KEY: ${{ secrets.API_KEY }}
run: echo "Using a secret safely"
jobs:
deploy:
environment: production # Requires approval before running
jobs:
deploy:
permissions:
id-token: write # Required for OIDC
steps:
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v2
with:
role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsRole
aws-region: us-east-1
Enabling Dependabot:
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
jobs:
analyze:
runs-on: ubuntu-latest
steps:
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: javascript
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
jobs:
scan:
runs-on: ubuntu-latest
steps:
- name: Run Trivy
uses: aquasecurity/trivy-action@master
with:
image-ref: "my-image:latest"
format: "table"
Final Thoughts
Mastering security in GitHub Actions involves minimizing permissions, verifying workflows,
handling third-party risks, and automating security scans. If you follow these best practices,
you will be well-prepared for any security-related interview question.
Debugging and monitoring workflows in GitHub Actions is crucial for ensuring smooth CI/CD
pipelines. Below is a deep dive into debugging failed workflows, using workflow logs effectively,
enabling detailed logging, and handling workflow failures efficiently.
1. Debugging Failed Workflows
When a GitHub Actions workflow fails, understanding the root cause is essential. Here’s how to
approach debugging effectively:
Check Exit Codes: Many commands return exit codes (0 for success, non-zero for
failure).
Echo Debug Messages: Use echo to print values in workflow steps.
Manually Run Commands: Reproduce the issue locally.
Use GitHub’s Re-run Feature: Allows re-running failed jobs after fixes.
Example:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Run a step that might fail
run: exit 1
continue-on-error: true
For transient failures (e.g., network issues, flaky tests), use run scripts with retry logic.
jobs:
retry-example:
runs-on: ubuntu-latest
steps:
- name: Retry a failing command
run: |
for i in {1..5}; do
curl -I https://example.com && break
echo "Retrying in 5 seconds..."
sleep 5
done
GitHub Actions does not have built-in retry steps, but you can use third-party actions.
Example using nick-fields/retry action:
jobs:
example:
runs-on: ubuntu-latest
steps:
- name: Run with retry
uses: nick-fields/retry@v2
with:
timeout_seconds: 10
max_attempts: 3
command: curl -I https://example.com
Use case: When interacting with external services that might fail intermittently.
jobs:
build:
runs-on: ubuntu-latest
steps:
- run: echo "Building project..."
test:
needs: build
runs-on: ubuntu-latest
steps:
- run: echo "Running tests..."
jobs:
notify:
if: failure()
runs-on: ubuntu-latest
steps:
- name: Send Slack alert
run: curl -X POST -H 'Content-type: application/json' --data '{"text":"Workflow failed!"}'
$SLACK_WEBHOOK_URL
For debugging complex failures, use tmatras/GitHub-Actions-Debug-SSH to open an SSH session into
the runner.
Example:
jobs:
debug:
runs-on: ubuntu-latest
steps:
- name: Setup Debugging
uses: mxschmitt/action-tmate@v3
By mastering these techniques, you’ll be fully prepared to handle any GitHub Actions
debugging question in an interview! 🚀
Got it! I'll break everything down in detail so that by the end, you'll have a deep understanding
of Continuous Integration (CI) with GitHub Actions, including running tests, code quality checks,
test coverage reporting, and parallel test execution.
GitHub Actions is a CI/CD platform that allows automation directly within GitHub repositories.
Key Components:
name: CI Tests
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
Explanation:
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
If ESLint finds issues, the workflow fails, preventing bad code from being merged.
Modify package.json:
"scripts": {
"test": "jest --coverage"
}
jobs:
coverage:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
But for GitHub Actions, it's often better to split tests across multiple jobs.
jobs:
test:
strategy:
matrix:
shard: [1, 2, 3]
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
How it works:
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
node: [16, 18]
This runs tests on Ubuntu & Windows for Node.js 16 & 18.
jobs:
test:
runs-on: ubuntu-latest
container: node:18
steps:
- name: Checkout Repository
uses: actions/checkout@v4
Caching Dependencies
Conclusion
You now have an in-depth understanding of CI with GitHub Actions, covering:
With this, you’ll be able to confidently answer any CI-related interview question. 🚀
Let's break this down into deep, practical insights so you can confidently handle any interview
question on Continuous Deployment (CD) with GitHub Actions, including advanced deployment
strategies.
1. Triggers (on) – When should the workflow run? Example: push, pull_request,
workflow_dispatch (manual trigger).
2. Jobs – A collection of steps that run in parallel or sequentially.
3. Steps – Individual actions executed in a job.
4. Runners – The virtual machines executing the workflow. GitHub provides hosted
runners, but you can also set up self-hosted ones.
1. Go to Settings → Pages
2. Select GitHub Actions as the deployment source
on:
push:
branches:
- main # Deploy when code is pushed to main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
This workflow:
✅Runs on Ubuntu
✅Installs dependencies
✅Builds the project
✅Deploys the build folder to GitHub Pages
1. Create an S3 bucket
2. Enable static website hosting
3. Create a CloudFront distribution
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Deploy to S3
run: aws s3 sync ./build s3://my-bucket-name --delete
This workflow:
✅Syncs the build folder to S3
✅Invalidates CloudFront cache
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 18
This workflow:
✅Builds the app
✅Deploys to Azure Web App
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app
image: my-dockerhub-username/my-app:latest
ports:
- containerPort: 80
on:
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
Blue-Green Deployment
Final Takeaways
✅Understand GitHub Actions workflows
✅Know how to deploy to GitHub Pages, AWS, Azure, and Kubernetes
✅Master advanced deployment strategies (Canary, Blue-Green)
Let's break this down deeply, covering Terraform with GitHub Actions, Docker build
automation, and server provisioning so you can confidently tackle interview questions.
Providers: Define which cloud/platform Terraform interacts with (AWS, Azure, etc.).
Resources: Define infrastructure components (VMs, databases, security groups).
Modules: Reusable infrastructure components.
State File (terraform.tfstate): Stores the current infrastructure state.
Plan-Apply Workflow:
1. terraform init – Initializes Terraform & downloads providers.
2. terraform plan – Shows changes Terraform will make.
3. terraform apply – Deploys the changes.
4. terraform destroy – Destroys infrastructure.
GitHub Actions is a CI/CD automation tool that helps run Terraform in response to code
changes.
on:
push:
branches:
- main
jobs:
terraform:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
Goal: Automatically build and push a Docker image to a registry when changes occur.
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
provider "aws" {
region = "us-east-1"
}
key_name = "my-key"
security_groups = ["web-sg"]
provisioner "remote-exec" {
inline = [
"sudo apt update -y",
"sudo apt install ansible -y",
"ansible-playbook -i 'localhost,' playbook.yml"
]
}
}
Docker Automation
Final Thoughts
Mastering these topics will make you highly proficient in DevOps automation, IaC, and CI/CD.
Would you like me to generate real-world project examples or mock interview questions to
solidify your understanding? 🚀
Let's break this down into a deep dive on event-driven workflows in GitHub Actions,
particularly focusing on repository_dispatch, webhooks, external API calls, and GitHub Apps.
repository_dispatch is a special event that allows external applications, CI/CD tools, or other
repositories to trigger a workflow via the GitHub REST API.
on:
repository_dispatch:
types: [deploy-trigger]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
The workflow listens for the deploy-trigger event coming via repository_dispatch.
When triggered, it prints the event type and simulates a deployment.
2️⃣ Trigger repository_dispatch from an External API Call Use curl or Postman to send a POST
request to the GitHub API:
If an external system supports webhooks (e.g., Stripe, Slack, or Jenkins), you can use GitHub
Actions to respond to them.
on:
repository_dispatch:
types: [webhook-event]
jobs:
process-webhook:
runs-on: ubuntu-latest
steps:
- name: Print Payload Data
run: echo "Received event data: ${{ toJson(github.event.client_payload) }}"
If a service (e.g., Stripe) allows webhook configuration, set its webhook URL to:
https://api.github.com/repos/YOUR_USERNAME/YOUR_REPOSITORY/dispatches
With a payload:
{
"event_type": "webhook-event",
"client_payload": {
"order_id": "12345",
"status": "paid"
}
}
The workflow will extract the order_id and status for further processing.
4. Using GitHub Actions with GitHub Apps
GitHub Apps provide more fine-grained permissions than Personal Access Tokens (PATs) and
are a secure way to interact with GitHub Actions.
More secure: Apps can have limited permissions instead of full repo access.
Better scalability: Can be installed on multiple repositories without sharing personal
tokens.
Easier revocation: If compromised, an app can be uninstalled without affecting users.
on:
repository_dispatch:
types: [app-event]
jobs:
authenticate:
runs-on: ubuntu-latest
steps:
- name: Authenticate as GitHub App
env:
APP_ID: ${{ secrets.GH_APP_ID }}
PRIVATE_KEY: ${{ secrets.GH_APP_PRIVATE_KEY }}
run: |
echo "Authenticating as GitHub App..."
echo "$PRIVATE_KEY" > private-key.pem
jwt_token=$(ruby -r openssl -r base64 -r json -e \
'payload = {"iat" => Time.now.to_i, "exp" => Time.now.to_i + 600, "iss" => ENV["APP_ID"]};
private_pem = File.read("private-key.pem");
private_key = OpenSSL::PKey::RSA.new(private_pem);
token = Base64.urlsafe_encode64(private_key.sign(OpenSSL::Digest::SHA256.new, JSON.generate(payload)));
puts token')
echo "JWT Token: $jwt_token"
Final Summary
Concept Explanation
repository_dispatch Triggers workflows via API calls from external services.
Webhooks External services notify GitHub of events via HTTP POST requests.
External API Calls Workflows can send requests to third-party APIs (e.g., Slack, Jenkins).
GitHub Apps Secure way to authenticate workflows with fine-grained permissions.
This guide gives you deep knowledge on event-driven workflows, repository_dispatch, webhooks,
and GitHub Apps. You should now be well-prepared for any interview questions on this topic! 🚀
Here’s a deep dive into real-world use cases and best practices for GitHub Actions in
monorepos, release automation, and large-scale workflow management. By the end of this,
you should have a master-level understanding of these topics.
Challenges in Monorepos
Use paths filters in on.push or on.pull_request triggers to execute workflows only when relevant
files are modified.
on:
push:
paths:
- "service-a/**"
pull_request:
paths:
- "service-a/**"
To optimize execution, use matrix builds to dynamically run tests/builds only for affected
components.
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
service: [service-a, service-b, service-c]
steps:
- name: Checkout repo
uses: actions/checkout@v4
- name: Run tests
run: |
cd ${{ matrix.service }}
npm test
With this setup, GitHub Actions executes only the required service’s tests instead of running
them all.
Instead of copy-pasting the same CI/CD pipeline across different services, create reusable
workflows.
jobs:
deploy:
uses: org-name/repo/.github/workflows/deploy.yml@main
GitHub Actions can automatically create a release when a new version is tagged.
If you’re releasing a package, automate publishing to npm, PyPI, Docker Hub, etc.
jobs:
ci:
uses: org/github-actions-templates/.github/workflows/ci.yml@main
Problem: Default GitHub-hosted runners are costly and slow for large-scale CI/CD.
Solution: Use self-hosted runners to save costs and improve performance.
runs-on: self-hosted
Set up autoscaling runners with Kubernetes or AWS EC2.
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
Conclusion
Mastering GitHub Actions for monorepos, automated releases, and large-scale workflows
gives you an edge in DevOps and CI/CD roles. Here’s a quick recap: ✅Use paths filtering &
matrix builds for monorepos
✅Automate semantic versioning & changelog generation
✅Centralize workflows & use self-hosted runners for scalability
✅Monitor workflows with logs, alerts, and observability tools
Here's a deep dive into real-world use cases and best practices for monorepos with GitHub
Actions, automating release workflows, and managing workflows at scale, with a strong focus
on large-scale GitHub Actions implementations.
Challenges in Monorepos
Instead of running all workflows on every push, use paths and paths-ignore in your workflow to
trigger jobs only when relevant files change.
on:
push:
paths:
- 'serviceA/**'
- '!docs/**'
If you have multiple projects inside a monorepo, use matrix builds to run tests in parallel.
jobs:
build:
strategy:
matrix:
service: [serviceA, serviceB, serviceC]
runs-on: ubuntu-latest
steps:
- run: cd ${{ matrix.service }} && npm install && npm test
Monorepos often have shared dependencies, and caching can dramatically reduce build times.
steps:
- uses: actions/cache@v3
with:
path: ~/.npm
key: npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: npm-
If a monorepo contains independent services, use GitHub Actions + GitHub API to dispatch
jobs dynamically.
steps:
- uses: actions/checkout@v3
- uses: conventional-changelog/standard-version@v1
3. Deploying Artifacts
For projects requiring artifacts (e.g., compiled binaries), upload them automatically:
Scaling Strategies
1. Reusable Workflows
jobs:
test:
uses: org/.github/.github/workflows/test.yml@main
Better control
Custom environments
Faster builds
runs-on: self-hosted
🚀 Benefit: Optimized performance and cost control.
Organizations often hit API limits. Prevent hitting GitHub rate limits with jobs.<job>.timeout-
minutes:
jobs:
deploy:
timeout-minutes: 30
This level of depth should prepare you for any interview question about GitHub Actions at
scale! 🚀🚀