Sobre nós Guias Projetos Contactos
Админка
please wait

GitHub Actions é a plataforma de CI/CD integrada do GitHub que automatiza fluxos de trabalho de compilação, testes e deployment diretamente a partir do seu repositório. Com a sua sintaxe poderosa de workflows e um marketplace extenso de actions, o GitHub Actions tornou-se uma escolha de referência para DevOps moderno. Este guia aborda a implementação de pipelines de CI/CD para produção na perspetiva de um developer sénior.

Porquê GitHub Actions

O GitHub Actions oferece vantagens convincentes:

  1. Integração Nativa: Integrado no GitHub, sem serviços externos
  2. Configuração em YAML: Workflows com controlo de versões
  3. Marketplace: Milhares de actions pré-construídas
  4. Matrix Builds: Testar em múltiplos ambientes
  5. Plano Gratuito: Minutos generosos para repositórios públicos e privados

Noções Básicas de Workflows

Estrutura do Ficheiro de Workflow

Os workflows vivem em .github/workflows/*.yml:

name: CI Pipeline
# Triggers
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
workflow_dispatch: # Trigger manual
# Variáveis de ambiente
env:
NODE_VERSION: '20'
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build
run: npm run build

Eventos de Trigger

on:
# Push para branches específicas
push:
branches:
- main
- 'release/**'
paths:
- 'src/**'
- 'package.json'
paths-ignore:
- '**.md'
- 'docs/**'
# Pull requests
pull_request:
branches: [main]
types: [opened, synchronize, reopened]
# Agendado (cron)
schedule:
- cron: '0 2 * * *' # Diariamente às 2:00 UTC
# Trigger manual com inputs
workflow_dispatch:
inputs:
environment:
description: 'Deploy environment'
required: true
default: 'staging'
type: choice
options:
- staging
- production
# Release publicada
release:
types: [published]
# Outro workflow concluído
workflow_run:
workflows: ["Build"]
types: [completed]

CI/CD Completo para Node.js

name: Node.js CI/CD
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
NODE_VERSION: '20'
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- run: npm ci
- run: npm run lint
test:
runs-on: ubuntu-latest
needs: lint
services:
postgres:
image: postgres:15
env:
POSTGRES_USER: test
POSTGRES_PASSWORD: test
POSTGRES_DB: test
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- run: npm ci
- name: Run tests
run: npm test
env:
DATABASE_URL: postgresql://test:test@localhost:5432/test
build:
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- run: npm ci
- run: npm run build
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: build
path: dist/
retention-days: 7
deploy-staging:
runs-on: ubuntu-latest
needs: build
if: github.ref == 'refs/heads/main'
environment: staging
steps:
- uses: actions/checkout@v4
- name: Download artifacts
uses: actions/download-artifact@v4
with:
name: build
path: dist/
- name: Deploy to staging
run: |
# Script de deployment
echo "Deploying to staging..."
env:
DEPLOY_KEY: ${{ secrets.STAGING_DEPLOY_KEY }}
deploy-production:
runs-on: ubuntu-latest
needs: deploy-staging
if: github.ref == 'refs/heads/main'
environment: production
steps:
- uses: actions/checkout@v4
- name: Download artifacts
uses: actions/download-artifact@v4
with:
name: build
path: dist/
- name: Deploy to production
run: |
echo "Deploying to production..."
env:
DEPLOY_KEY: ${{ secrets.PRODUCTION_DEPLOY_KEY }}

Docker Build e Push

name: Docker Build
on:
push:
branches: [main]
tags: ['v*']
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=semver,pattern={{version}}
type=sha,prefix=
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max

Testes com Matrix

name: Matrix Tests
on: [push, pull_request]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node: [18, 20, 22]
exclude:
- os: windows-latest
node: 18
include:
- os: ubuntu-latest
node: 20
coverage: true
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
- run: npm ci
- run: npm test
- name: Upload coverage
if: matrix.coverage
uses: codecov/codecov-action@v3

Secrets e Variáveis de Ambiente

Utilizar Secrets

jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Deploy
run: ./deploy.sh
env:
API_KEY: ${{ secrets.API_KEY }}
DATABASE_URL: ${{ secrets.DATABASE_URL }}
- name: Mask sensitive output
run: |
echo "::add-mask::${{ secrets.API_KEY }}"
# A utilização adicional não mostrará o valor nos logs

Proteção de Ambiente

jobs:
deploy-production:
runs-on: ubuntu-latest
environment:
name: production
url: https://example.com
steps:
- name: Deploy
run: ./deploy.sh
# Secrets do ambiente «production»
env:
API_KEY: ${{ secrets.API_KEY }}

Caching

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# Node.js com cache do npm
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
# Cache personalizado
- name: Cache dependencies
uses: actions/cache@v4
with:
path: |
~/.npm
node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- run: npm ci

Workflows Reutilizáveis

Definir Workflow Reutilizável

.github/workflows/reusable-deploy.yml:

name: Reusable Deploy
on:
workflow_call:
inputs:
environment:
required: true
type: string
artifact-name:
required: true
type: string
secrets:
deploy-key:
required: true
jobs:
deploy:
runs-on: ubuntu-latest
environment: ${{ inputs.environment }}
steps:
- uses: actions/download-artifact@v4
with:
name: ${{ inputs.artifact-name }}
- name: Deploy
run: ./deploy.sh
env:
DEPLOY_KEY: ${{ secrets.deploy-key }}

Utilizar Workflow Reutilizável

name: CI/CD
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci && npm run build
- uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
deploy-staging:
needs: build
uses: ./.github/workflows/reusable-deploy.yml
with:
environment: staging
artifact-name: dist
secrets:
deploy-key: ${{ secrets.STAGING_KEY }}
deploy-production:
needs: deploy-staging
uses: ./.github/workflows/reusable-deploy.yml
with:
environment: production
artifact-name: dist
secrets:
deploy-key: ${{ secrets.PRODUCTION_KEY }}

Composite Actions

.github/actions/setup-project/action.yml:

name: 'Setup Project'
description: 'Setup Node.js and install dependencies'
inputs:
node-version:
description: 'Node.js version'
default: '20'
runs:
using: 'composite'
steps:
- uses: actions/setup-node@v4
with:
node-version: ${{ inputs.node-version }}
cache: 'npm'
- run: npm ci
shell: bash
- run: npm run build --if-present
shell: bash

Utilização:

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: ./.github/actions/setup-project
with:
node-version: '20'
- run: npm test

Execução Condicional

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# Executar apenas na branch main
- name: Deploy
if: github.ref == 'refs/heads/main'
run: ./deploy.sh
# Executar em caso de sucesso
- name: Notify success
if: success()
run: echo "Build succeeded"
# Executar em caso de falha
- name: Notify failure
if: failure()
run: echo "Build failed"
# Executar sempre
- name: Cleanup
if: always()
run: ./cleanup.sh
# Condições complexas
- name: Production deploy
if: |
github.ref == 'refs/heads/main' &&
github.event_name == 'push' &&
!contains(github.event.head_commit.message, '[skip deploy]')
run: ./deploy-prod.sh

Principais Conclusões

  1. Versione os seus workflows: Trate .github/workflows como código de produção
  2. Use caching: Acelere builds com caching de dependências
  3. Proteja ambientes: Exija aprovações para deployments em produção
  4. Reutilize workflows: O princípio DRY também se aplica a CI/CD
  5. Falhe cedo em PRs: Feedback rápido em pull requests
  6. Proteja secrets: Use secrets específicos por ambiente e regras de proteção

O GitHub Actions disponibiliza uma plataforma de CI/CD poderosa e flexível — invista tempo em workflows bem estruturados e estes servirão a sua equipa de forma fiável.

 
 
 
Языки
Темы
Copyright © 1999 — 2026
ZK Interactive