Home  Github   Github acti ...

GitHub Actions workflow - YAML files syntax and commands

In GitHub Actions workflow YAML files, you define your CI/CD pipeline using a structured format that includes jobs, steps, and various commands to perform tasks. Let's break down the key components and commands used in a GitHub Actions workflow YAML file, including how to work with variables:

Structure of GitHub Actions Workflow YAML File

A GitHub Actions workflow YAML file consists of the following main components:

  1. Name and Trigger:

    • name: Specifies the name of your workflow.
    • on: Specifies the event that triggers the workflow, such as push, pull_request, schedule, etc.
  2. Jobs:

    • jobs: Defines one or more jobs that run sequentially or in parallel. Each job can contain multiple steps.
  3. Steps:

    • steps: Defines the individual tasks or commands that make up a job. Steps can include shell commands, actions, or references to other actions.
  4. Environment Variables:

    • env: Allows you to define environment variables that are available to all steps within a job.
  5. Secrets:

    • secrets: Allows you to define sensitive information (like API keys) securely and use them in your workflow.
  6. Workflow Variables:

    • Variables defined within the workflow file using the jobs.<job_id>.steps[*].with context can be used to set variables used within a job.

Example Workflow YAML File with Explanation

name: CI/CD Pipeline

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v2

      - name: Set up Node.js
        uses: actions/setup-node@v2
        with:
          node-version: '14'

      - name: Install Dependencies
        run: npm install

      - name: Run Tests
        run: npm test

      - name: Deploy to Production
        if: github.ref == 'refs/heads/main'
        env:
          PRODUCTION_URL: ${{ secrets.PRODUCTION_URL }}
        run: |
          echo "Deploying to production at $PRODUCTION_URL"
          # Commands to deploy to production environment

      - name: Notify Slack
        if: success()
        env:
          SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}
        run: |
          curl -X POST -H 'Content-type: application/json' --data '{"text":"Build successful!"}' $SLACK_WEBHOOK

Explanation of Commands and Usage

Using Variables

GitHub Actions allow you to define variables dynamically within your workflow:

jobs:
  build:
    runs-on: ubuntu-latest
    
    steps:
      - name: Set Environment Variables
        run: echo "ENV_VAR_NAME=value" >> $GITHUB_ENV

      - name: Use Environment Variable in Step
        run: echo $ENV_VAR_NAME

In this example:

Published on: Jun 27, 2024, 02:10 AM  
 

Comments

Add your comment