Summary

This document provides an overview of GitHub Actions, a platform for automating software development tasks. It details key components like workflows, jobs, actions, and runners, along with concepts like reusable actions and workflow triggers. The material covers both basic and advanced features, making it a useful guide for developers.

Full Transcript

Overview : Key Components 1. Workflows: ○ Configurable processes defined in YAML files located in the.github/workflows directory. ○ Triggered by repository events, manually, or on a schedule. ○ Can perform tasks like building, testing, deploying, or labeling issues....

Overview : Key Components 1. Workflows: ○ Configurable processes defined in YAML files located in the.github/workflows directory. ○ Triggered by repository events, manually, or on a schedule. ○ Can perform tasks like building, testing, deploying, or labeling issues. 2. Events: ○ Specific repository activities (e.g., creating a pull request, pushing a commit) that trigger workflows. ○ Workflows can also be triggered via schedule, REST API, or manually. 3. Jobs: ○ A sequence of steps executed on a single runner. ○ Steps include running shell scripts or actions. ○ Jobs can run independently in parallel or have dependencies on other jobs. 4. Actions: ○ Reusable custom applications for performing repetitive tasks (e.g., setting up environments or cloud authentication). ○ Available in GitHub Marketplace or can be custom-built. 5. Runners: ○ Servers that execute workflows, each running one job at a time. ○ GitHub provides Linux, Windows, and macOS virtual runners, or you can use self-hosted runners for custom configurations. Capabilities and Use Cases Automate builds, tests, deployments, and more. Build CI/CD pipelines for continuous integration and delivery. Run workflows on GitHub-hosted or self-hosted environments. Actions : Key Features of Actions 1. Reusable: Use actions across multiple workflows and repositories to avoid rewriting code. 2. Pre-written: Many community-created actions are available in the GitHub Marketplace. 3. Configurable: Actions can accept inputs, generate outputs, and use environment variables. 4. Community-driven: You can create custom actions and share them. Types of Actions Same Repository: Actions stored in the same repository as the workflow. Public Repository: Actions from any public repository. Docker Containers: Actions defined as Docker images on Docker Hub. Using Actions in Workflows 1. Browsing GitHub Marketplace: ○ Use the workflow editor to search and add actions. ○ Actions verified by GitHub display a checkmark badge. 2. Adding Actions to a Workflow: ○ Add an action as a step in your workflow file (.yml). ○ Reference actions using: {owner}/{repo}@{version} for external actions../path/to/dir for local actions. 3. Versioning Actions: ○ Tags: Specify a tag (e.g., v1.0.1). ○ SHAs: Use immutable SHA values for more reliability. ○ Branches: Target a branch, but this may include breaking changes. Inputs and Outputs Actions may require inputs and provide outputs: Inputs: Define required data (e.g., file paths). Outputs: Provide results for further use in workflows. Example: yaml Copy code inputs: file-path: description: "Path to test script" required: true default: "test-file.js" outputs: results-file: description: "Path to results file" Security and Best Practices Use Dependabot to keep actions updated. Prefer SHAs for third-party actions to ensure security. Verify Docker images when using Docker actions. Work Flow : A workflow is an automated process defined by a YAML file in the.github/workflows directory of a repository. Workflows run one or more jobs and can be triggered by events, manually, or on a schedule. Workflow Basics A workflow consists of: 1. Triggers: Events that start the workflow (e.g., push, pull request, issue creation). 2. Jobs: Units of work run on a runner machine. 3. Steps: Actions or scripts executed sequentially within a job. Workflow Triggers Workflows can be triggered by: Repository events: Pushes, releases, issue creation. External events: Triggered via repository_dispatch. Schedules: Using cron syntax. Manual triggers: Via the GitHub interface. Workflow Templates GitHub offers preconfigured templates to simplify workflow creation, such as: CI (Continuous Integration) Deployments Automation Code Scanning Pages Templates can be customized to suit project needs. Advanced Workflow Features 1. Secrets: ○ Store sensitive data (e.g., passwords, tokens) securely. ○ Use as environment variables in workflows. Example: yaml Copy code env: secret_var: ${{ secrets.SECRET_VAR }} 2. 3. Dependent Jobs: ○ Use the needs keyword to create job dependencies. Example: yaml Copy code jobs: setup: steps:... build: needs: setup steps:... test: needs: build steps:... ○ 4. Matrix Strategy: ○ Run jobs with different configurations (e.g., Node.js versions). Example: yaml Copy code strategy: matrix: node: [14, 16] ○ 5. Caching Dependencies: ○ Improve performance by caching reused files. Example: yaml Copy code uses: actions/cache@v3 with: path: ~/.npm key: ${{ runner.os }}-build-${{ hashFiles('**/package-lock.json') }} ○ 6. Service Containers: ○ Run temporary containers (e.g., databases) alongside jobs. Example: yaml Copy code services: postgres: image: postgres ○ 7. Labels for Runners: ○ Specify self-hosted or GitHub-hosted runners using labels. Example: yaml Copy code runs-on: [self-hosted, linux, x64] 8. 9. Reusable Workflows: ○ Call workflows within other workflows to avoid duplication. Security Features Use Dependabot to track vulnerabilities and update actions. Configure environments with protection rules and secrets to control job execution. Security : 1. Using Secrets: Secrets are encrypted using Libsodium sealed boxes before reaching GitHub, minimizing accidental disclosure in logs. Secrets can be configured at the organization, repository, or environment levels. Redaction: GitHub attempts to redact secrets in logs but is not guaranteed to catch all cases, especially for transformed values (e.g., Base64). 2. Best Practices: Avoid Structured Data as Secrets: Do not use structured data like JSON, XML, or YAML as secrets because it may prevent proper redaction. Register All Derived Secrets: If a secret is used to generate another sensitive value (e.g., a JWT), register the derived value as a secret. Audit and Review: Regularly audit how secrets are used, and verify that they are properly redacted in logs. Use Least Privilege Credentials: Ensure that credentials used in workflows have minimal permissions. Rotate Secrets: Periodically rotate secrets and remove those that are no longer needed. 3. Access Controls: Only users with write access to the repository can view secrets. Use CODEOWNERS to restrict workflow changes to trusted reviewers. Consider requiring review approvals for environment secrets. 4. Risk of Script Injection: Custom Actions and Workflow Security: Untrusted inputs in workflows can lead to script injection vulnerabilities. For instance, attackers could inject malicious code into workflow contexts (e.g., pull request titles). Mitigation: ○ Use actions instead of inline scripts to avoid code execution vulnerabilities. ○ Use environment variables for untrusted inputs to avoid shell script injection. ○ Ensure defensive programming when handling potentially untrusted input. 5. Security Enhancements: Use workflow templates for code scanning (e.g., CodeQL) to detect vulnerabilities early. Restrict token permissions to minimize risks associated with exposed tokens. Use OpenID Connect (OIDC) for cloud access to eliminate the need for storing long-lived credentials. 6. Warnings: Users with write access can read all secrets in the repository. Mismanagement of secrets or improper redaction in logs can lead to accidental leaks. Risks of Third-Party Actions and Workflows: Pin Actions to Full Commit SHA: This ensures immutability and prevents backdoor risks from action updates. Audit Source Code: Verify that actions don’t misuse secrets or leak them. Pin Actions to a Tag Only If Trusted: If you pin to a tag, ensure you trust the creator. Tags can be deleted or moved, posing risks. Use Dependabot: It can automatically keep actions and workflows up-to-date, improving security. Prevent GitHub Actions from Approving Pull Requests: Limiting this action reduces security risks. Compromised Runner Risks: Accessing Secrets: Secrets can be accessed by malicious actors if they steal or expose the environment variables, including using the GITHUB_TOKEN. Exfiltrating Data: Secrets can be leaked through logs or HTTP requests by an attacker. Stealing the GITHUB_TOKEN: If stolen, an attacker could modify repositories with write permissions. GitHub Action Runner Types: GitHub-Hosted Runners: These run in isolated virtual environments, reducing the risk of persistent compromise. Self-Hosted Runners: More vulnerable, as they can be compromised by any untrusted code running in workflows. Limit access to sensitive environments and avoid using them for public repositories. Just-in-Time (JIT) Runners: These runners are ephemeral, only executing one job before being removed, enhancing security. Security Measures: Use the GITHUB_TOKEN whenever possible, as it's scoped to a single repository. Repository Deploy Keys and GitHub App Tokens: Use them for repository-specific access. Avoid Personal Access Tokens and SSH Keys: They grant broader access, which poses security risks. Security Hardening with OpenID Connect: For cloud deployments, use OpenID Connect for creating short-lived, scoped tokens. Reusing Work Flows : Reusable workflows in GitHub Actions allow you to avoid duplicating code across different workflows, making your automation processes easier to maintain and expand. Here's an overview of the key concepts: Key Concepts: 1. Caller Workflow: This is the workflow that invokes another workflow (the reusable workflow). It is a workflow that calls a reusable workflow to perform specific tasks. 2. Called Workflow: This is the reusable workflow that contains the jobs and steps that are executed when it is invoked by a caller workflow. 3. Workflow Reuse: Instead of copying and pasting entire workflow definitions, you can create reusable workflows that can be called by multiple workflows. This improves maintainability and promotes best practices. 4. Job Dependencies: A reusable workflow can contain multiple jobs with dependencies. For example, you can have a "Deploy" job that calls a reusable workflow containing jobs for "Staging", "Review", and "Production" deployments. Advantages of Reusable Workflows: Avoid Code Duplication: Reusable workflows let you centralize common tasks and avoid writing the same steps in different workflows. Faster Workflow Creation: By reusing pre-designed workflows, you can quickly set up new workflows. Promote Best Practices: Centralized workflows are easier to test, maintain, and use, ensuring that teams follow consistent and effective practices. How Reusable Workflows Work: A "caller" workflow invokes a "called" workflow using a single line reference. The entire called workflow is executed as if it were part of the caller workflow. If a reusable workflow is in another repository, any actions used in the called workflow will run as part of the caller workflow. For example, if the called workflow uses actions/checkout, it will check out the repository of the caller workflow, not the called one. Calling Reusable Workflows: When calling a reusable workflow, the caller workflow uses the context associated with it (like github.token and secrets.GITHUB_TOKEN). The dependency graph in GitHub Actions shows how workflows depend on each other, which helps to visualize the relationships between them. Inputs and Secrets in Reusable Workflows: You can define inputs and secrets for a reusable workflow. The caller workflow can pass values to these inputs, which will be used by the called workflow. Inputs and secrets can be defined in the reusable workflow using on.workflow_call.inputs and on.workflow_call.secrets. Security Considerations: Ensure that you trust the version of a reusable workflow you reference, particularly if you use a tag or branch, as security vulnerabilities can be introduced if untrusted versions are used. Environment secrets cannot be passed directly from the caller workflow to the reusable workflow. Creating and Using Reusable Workflows: Reusable workflows are located in the.github/workflows directory of a repository and defined with the on.workflow_call trigger. Example: yaml Copy code on: workflow_call: inputs: config-path: required: true type: string secrets: personal_access_token: required: true To reference a reusable workflow from a caller workflow, use the uses keyword in a job. Example: yaml Copy code jobs: call-workflow-passing-data: uses: my-org/my-repo/.github/workflows/my-reusable-workflow.yml@main with: config-path:.github/config.yml secrets: personal_access_token: ${{ secrets.TOKEN }} Limits and Considerations: You can nest up to four levels of reusable workflows. A maximum of 20 unique reusable workflows can be called from a single workflow. Variables defined at the workflow level in the caller workflow are not propagated to the called workflow, but you can pass them as outputs. GitHub-hosted runners are associated with the caller workflow for billing and execution. 1. Reusable Workflow Setup (workflow-B.yml) A reusable workflow (workflow-B.yml) is designed to take inputs and secrets from a calling workflow and use them in actions. It defines: ○ inputs: Required parameters (e.g., config-path). ○ secrets: Sensitive data (e.g., token) that is passed securely. The job within this reusable workflow uses an action (e.g., actions/labeler@v4) with the input and secret values. 2. Calling a Reusable Workflow A reusable workflow is called using the uses keyword directly within a job. The syntax: ○ owner/repo/.github/workflows/{filename}@{ref} (for external workflows). ○./.github/workflows/{filename} (for workflows within the same repository). You can pass inputs and secrets using the with and secrets keywords. 3. Passing Inputs and Secrets Inputs must match the data types specified in the reusable workflow (string, number, boolean). You can pass secrets using secrets keyword. inherit allows passing secrets automatically from the caller workflow. 4. Using a Matrix Strategy A matrix strategy allows running a reusable workflow for multiple variables (e.g., dev, stage, prod). Each matrix combination can use a different value for the workflow input. 5. Supported Keywords for Jobs Calling Reusable Workflows Only specific keywords are allowed in jobs calling reusable workflows (e.g., name, uses, with, secrets, strategy, needs, etc.). 6. Example Caller Workflow A caller workflow (e.g., workflow-A.yml) calls multiple reusable workflows, passing inputs and secrets. A reusable workflow can be called with uses in multiple jobs. 7. Nesting Reusable Workflows You can nest workflows up to four levels. Nested workflows receive secrets passed through previous levels. Secrets are only available in the direct calling workflow unless explicitly passed to nested workflows. 8. Using Outputs from Reusable Workflows A reusable workflow can set outputs using outputs at the job level, which can then be used in the caller workflow. Outputs must be mapped from step-level to job-level, and then mapped in the workflow_call.outputs section. 9. Monitoring Workflows You can monitor which workflows are being used in your project through GitHub’s REST API, using logs to track which workflows are being called and from which repositories. 10. Re-running Workflows and Jobs Re-running a workflow uses the reusable workflow reference (branch, tag, SHA). If the reference is not a SHA, re-running will refer to the latest reference, which may be different than the original execution. Key Points: Reusable workflows help reduce duplication and maintain consistency across workflows. Inputs, secrets, and outputs allow for dynamic workflow execution. You can manage permissions, monitor workflows, and efficiently pass data through different workflow levels.

Use Quizgecko on...
Browser
Browser