Github Action 使用介绍

发布时间: 更新时间: 总字数:1261 阅读时间:3m 作者: IP上海 分享 网址

Github Action 是 Github 官方的 CICD 工具,你可以在 Github Action 中做,单元测试、代码编译、发布、部署等动作,是 Github 的利器。

简介

With GitHub Actions you can automate your workflow from idea to production.

官网

本人开源的Actions

代码托管在x-actions,说明:

Actions 开发文档

语法 icon 默认变量

推荐的 Actions

本地模拟

  • nektos/act 项目
  • 安装
brew install act
  • 常用命令
# 本地运行
act
# 列出actions
act -l

action 时区

sudo timedatectl set-timezone "Asia/Shanghai"

demo

  • 取消之前的任务
    - name: Cancel previous runs on the same branch
      if: ${{ github.ref != 'refs/heads/master' }}
      uses: styfle/cancel-workflow-action@0.7.0
      with:
        access_token: ${{ github.token }}
  • 触发其他的任务
    - name: Hook Update workflow
      run: |
        curl -XPOST -H "Authorization: token ${{ secrets.WORKFLOW_TRIGGERS }}" -H "Accept: application/vnd.github.v3+json" -H "Content-Type: application/json" https://api.github.com/repos/xiexianbin/xiexianbin.github.io/actions/workflows/deploy.yml/dispatches

添加手动触发工作流

手动工作流,通过 on.workflow_dispatch 字段指定,需要将代码何如 main or master 分支才生效。

on:
  ...
  workflow_dispatch:
    inputs:
      reason:
        description: 'run action reason'
        required: false
        type: string
        default: 'manually test'

推荐的 actions

CodeQL Action

Dependabot

# Basic set up for three package managers

version: 2
updates:

  # Maintain dependencies for GitHub Actions
  - package-ecosystem: "github-actions"
    # Workflow files stored in the default location of `.github/workflows`. (You don't need to specify `/.github/workflows` for `directory`. You can use `directory: "/"`.)
    directory: "/"
    schedule:
      interval: "weekly"

  # Maintain dependencies for npm
  - package-ecosystem: "npm"
    directory: "/"
    schedule:
      interval: "weekly"

  # Maintain dependencies for Composer
  - package-ecosystem: "composer"
    directory: "/"
    schedule:
      interval: "weekly"

Renovate

expand-id ...
name: Renovate
on:
  schedule:
    # The "*" (#42, asterisk) character has special semantics in YAML, so this
    # string has to be quoted.
    - cron: '0/15 * * * *'
jobs:
  renovate:
    runs-on: ubuntu-latest
    steps:
      - name: Get token
        id: get_token
        uses: actions/create-github-app-token@v1
        with:
          private-key: ${{ secrets.PRIVATE_KEY }}
          app-id: ${{ secrets.APP_ID }}
          owner: ${{ github.repository_owner }}
          # repositories: 'repo1,repo2'

      - name: Checkout
        uses: actions/checkout@v4.1.7

      - name: Self-hosted Renovate
        uses: renovatebot/github-action@v40.1.12
        with:
          configurationFile: example/renovate-config.js
          token: '${{ steps.get_token.outputs.token }}'
.github/workflows/renovate.yaml ...
name: Renovate
on:
  schedule:
    - cron: "0/15 * * * *"
  workflow_dispatch:

permissions:
  contents: write
  pull-requests: write

jobs:
  renovate:
    runs-on: ubuntu-latest
    steps:
      - name: Get token
        id: get_token
        uses: tibdex/github-app-token@v2
        with:
          app_id: ${{ secrets.JENKINS_DEPENDENCY_UPDATER_APP_ID }}
          private_key: ${{ secrets.JENKINS_DEPENDENCY_UPDATER_PRIVATE_KEY }}

      - name: Checkout
        uses: actions/checkout@v4

      - name: Self-hosted Renovate
        uses: renovatebot/github-action@v40.1.12
        with:
          token: "${{ steps.get_token.outputs.token }}"
          docker-cmd-file: .github/renovate-entrypoint.sh
          docker-user: root
          configurationFile: .github/renovate-config.json5
        env:
          LOG_LEVEL: 'debug'
#!/bin/bash

# renovate: datasource=github-tags depName=mikefarah/yq
export YQ_VERSION=v4.44.2

curl -fsSL -o /usr/local/bin/yq https://github.com/mikefarah/yq/releases/download/${YQ_VERSION}/yq_linux_amd64
chmod a+x /usr/local/bin/yq

runuser -u ubuntu renovate
.github/renovate-config.json5 ...
{
  $schema: "https://docs.renovatebot.com/renovate-schema.json",
  onboarding: false,
  requireConfig: "ignored",
  platform: "github",
  repositories: ["jenkinsci/helm-charts"],
  // eslint-disable-next-line
  allowedPostUpgradeCommands: ['^\.github\/renovate-postupgrade\.sh "{{{depName}}}" "{{{newVersion}}}"$'],
  prConcurrentLimit: 0,
  prHourlyLimit: 5,
  semanticCommits: "enabled",
  enabledManagers: [
    "helm-values",
    "github-actions",
    "regex",
  ],
  packageRules: [
    {
      matchPackageNames: ["jenkins/inbound-agent"],
      versioning: "regex:^(?<major>\\d+)?\\.(?<minor>\\w+?)?_(?<patch>\\w+)?-(?<build>\\d+)?$",
    },
    {
      matchPackageNames: ["jenkins/jenkins"],
      versioning: "regex:^(?<major>\\d+?)\\.(?<minor>\\d+?)\\.(?<patch>\\d+?)(-(?<compatibility>\\w+))?$",
    },
    {
      matchFileNames: ["charts/jenkins/**"],
      postUpgradeTasks: {
        commands: [
          '.github/renovate-postupgrade.sh "{{{depName}}}" "{{{newVersion}}}"',
        ],
        fileFilters: ["charts/jenkins/**"],
        executionMode: "branch",
      },
    },
    {
      matchPackagePatterns: [".*"],
      excludePackagePatterns: ["jenkins/jenkins"],
      minimumReleaseAge: "12 hours",
    },
  ],
  customDatasources: {
    "python_actions": {
      defaultRegistryUrlTemplate: "https://raw.githubusercontent.com/actions/python-versions/main/versions-manifest.json",
      transformTemplates: [
        "{\"releases\": $$[stable=true].files[arch=\"x64\" and platform=\"linux\"].{\"version\":%.version,\"changelogUrl\":\"https://docs.python.org/whatsnew/index.html\"},\"homepage\":\"https://python.org/\",\"changelogUrl\":\"https://docs.python.org/whatsnew/index.html\"}",
      ],
    },
  },
  customManagers: [
    {
      customType: "regex",
      fileMatch: ["(^|/)\\.github/workflows/[^/]+\\.ya?ml$", "(^|/)\\.github/[^/]+\\.sh$"],
      matchStrings: [
        "# renovate: datasource=(?<datasource>.*?) depName=(?<depName>.*?)( versioning=(?<versioning>.*?))?\\s+?[\\w\\s-]*?version:? (?<currentValue>.*)\\s",
        "# renovate: datasource=(?<datasource>.*?) depName=(?<depName>.*?)( versioning=(?<versioning>.*?))?\\s.*?_VERSION=(?<currentValue>.*)\\s",
      ],
    },
    {
      customType: "regex",
      fileMatch: [
        "^charts/jenkins/Chart.yaml$",
        "^charts/jenkins/values.yaml$",
      ],
      matchStrings: [
        "appVersion: (?<currentValue>.*?)\\s",
        'repository: \\"jenkins/jenkins\\"\\s*?# tag: \\"(?<currentValue>.*?)\\"',
      ],
      depNameTemplate: "jenkins/jenkins",
      datasourceTemplate: "docker",
    },
    {
      customType: "regex",
      fileMatch: ["^charts/jenkins/values.yaml$"],
      matchStringsStrategy: "recursive",
      matchStrings: [
        "installPlugins:[\\s\\w:.-]*?(?:\\r*\\n){2}",
        "- (?<depName>.*?):(?<currentValue>.*?)\\s",
      ],
      datasourceTemplate: "jenkins-plugins",
      versioningTemplate: "regex:^(?<major>\\d+)?\\.(?<minor>\\w+?)?(\\.(?<patch>\\d+?))?$",
    },
    {
      customType: "regex",
      fileMatch: ["^charts/jenkins/Chart.yaml$"],
      matchStringsStrategy: "recursive",
      matchStrings: [
        "artifacthub\\.io\\/images: \\|[\\s\\w:.\\/-]*(?:artifacthub)",
        "image: (?<depName>.*?):(?<currentValue>.*?)\\s",
      ],
      datasourceTemplate: "docker",
      versioningTemplate: "regex:^(?<major>\\d+)?\\.(?<minor>\\w+?)?(_|\\.)(?<patch>\\w+)?(-(?<build>\\d+))?.*",
      depNameTemplate: "{{#if (equals depName 'docker.io/jenkins/jenkins')}}jenkins/jenkins{{else}}{{{depName}}}{{/if}}",
    },
  ],
}
  • .github/renovate-postupgrade.sh
.github/renovate-postupgrade.sh ...
#!/bin/bash

CHARTVERSION="$(jx-release-version -previous-version=from-file:charts/jenkins/Chart.yaml)"
export CHARTVERSION
depName=$(echo "$1" | tr ' ' '\n' | sort | uniq)
export DEPNAME="$depName"
export NEWVERSION="$2"

helm unittest --strict -f 'unittests/*.yaml' charts/jenkins -u
yq eval '.version = env(CHARTVERSION)' -i charts/jenkins/Chart.yaml
sed -i "/git commit to be able to get more details./a \\\n## ${CHARTVERSION}\n\nUpdate \`${DEPNAME}\` to version \`${NEWVERSION}\`" charts/jenkins/CHANGELOG.md
.github/helm-docs.sh
  • 使用示例
          # renovate: datasource=github-tags depName=helm/helm
          version: v3.15.2

          # renovate: datasource=custom.python_actions depName=python
          python-version: 3.12.4

          # renovate: datasource=github-releases depName=norwoodj/helm-docs
          HELM_DOCS_VERSION=1.13.1
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数