You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitHub Actions中是否可传递数组或键值对作为参数?

在GitHub Actions中传递数组或键值对参数的方法

GitHub Actions 本身没有原生的数组/键值对输入类型,但可以通过字符串模拟,再在 Action 内部解析实现需求,下面是几种常用的实现方式:

传递数组

方式1:空格分隔的字符串

将数组元素用空格拼接成字符串传入,在 Action 里用 shell 命令拆分:

工作流配置示例:

jobs:
  demo:
    runs-on: ubuntu-latest
    steps:
      - uses: your-namespace/your-action@v1
        with:
          target-items: "file1.txt file2.jpg dir3"

Action 的 action.yml 及处理逻辑:

inputs:
  target-items:
    description: "数组参数,用空格分隔元素"
    required: true
runs:
  using: "composite"
  steps:
    - name: 遍历处理数组元素
      shell: bash
      run: |
        # 拆分字符串为数组
        IFS=' ' read -r -a items <<< "${{ inputs.target-items }}"
        for item in "${items[@]}"; do
          echo "正在处理:$item"
        done

方式2:多行字符串(每行一个元素)

如果元素包含空格,用多行字符串更稳妥,每行放一个数组元素:

工作流配置:

- uses: your-namespace/your-action@v1
  with:
    target-items: |
      "document with space.txt"
      image.png
      "folder name with spaces"

Action 处理逻辑:

steps:
  - name: 处理多行数组
    shell: bash
    run: |
      while IFS= read -r item; do
        # 去掉首尾引号(如果有)
        cleaned_item=$(echo "$item" | sed -e 's/^"//' -e 's/"$//')
        echo "正在处理:$cleaned_item"
      done <<< "${{ inputs.target-items }}"

传递键值对

方式1:key=value 格式的多行字符串

将键值对按 key=value 格式逐行写入,在 Action 里解析为关联数组:

工作流配置:

- uses: your-namespace/your-action@v1
  with:
    config: |
      env=production
      timeout=300
      max-retry=5

Action 处理逻辑:

steps:
  - name: 解析键值对
    shell: bash
    run: |
      declare -A config_map
      while IFS='=' read -r key value; do
        config_map["$key"]="$value"
      done <<< "${{ inputs.config }}"
      
      echo "环境:${config_map[env]}"
      echo "超时时间:${config_map[timeout]}秒"

方式2:JSON 字符串

如果键值对结构复杂,直接传 JSON 字符串,用 jq 工具解析(需要确保 runner 安装了 jq):

工作流配置:

- uses: your-namespace/your-action@v1
  with:
    config: '{"env": "staging", "credentials": {"user": "test", "pass": "xxx"}, "timeout": 120}'

Action 处理逻辑:

steps:
  - name: 解析JSON配置
    shell: bash
    run: |
      env=$(echo "${{ inputs.config }}" | jq -r '.env')
      username=$(echo "${{ inputs.config }}" | jq -r '.credentials.user')
      echo "环境:$env"
      echo "用户名:$username"

内容的提问来源于stack exchange,提问作者testbg testbg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 16:20:17