How to Use GitHub Actions: Simple Guide for Automation
Use
GitHub Actions by creating workflow files in the .github/workflows folder of your repository. Define triggers, jobs, and steps in YAML format to automate tasks like testing or deployment on events such as push or pull_request.Syntax
A GitHub Actions workflow is defined in a YAML file with these main parts:
- name: The workflow's name.
- on: Events that start the workflow (e.g., push, pull_request).
- jobs: One or more jobs to run, each with steps.
- steps: Commands or actions to execute in order.
yaml
name: Example Workflow on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Run a script run: echo "Hello from GitHub Actions!"
Example
This example workflow runs on every push to the repository. It checks out the code and prints a greeting message.
yaml
name: Greeting Workflow on: [push] jobs: greet: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Say Hello run: echo "Hello, GitHub Actions!"
Output
Hello, GitHub Actions!
Common Pitfalls
Common mistakes include:
- Placing workflow files outside
.github/workflowsfolder. - Using incorrect YAML indentation causing syntax errors.
- Not specifying
runs-onfor jobs, so the runner is undefined. - Forgetting to use
actions/checkoutto get repository code before running commands.
yaml
name: Faulty Workflow on: push jobs: build: steps: - name: Missing runner run: echo "This will fail" --- Corrected version --- name: Fixed Workflow on: push jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Works now run: echo "This works"
Quick Reference
| Keyword | Description |
|---|---|
| name | Defines the workflow name |
| on | Specifies events that trigger the workflow |
| jobs | Groups tasks to run |
| runs-on | Specifies the runner environment |
| steps | List of commands or actions to execute |
| uses | Calls an existing action from GitHub Marketplace |
| run | Runs shell commands |
Key Takeaways
Create workflow YAML files inside .github/workflows to enable GitHub Actions.
Define triggers with 'on' and specify jobs with 'runs-on' and 'steps'.
Always include 'actions/checkout' step to access your repository code.
Check YAML indentation carefully to avoid syntax errors.
Use GitHub Marketplace actions to simplify common tasks.