如何在GitHub Actions中传递MAP类型的变量?
在GitHub Actions中传递MAP类型变量的方法
GitHub Actions的workflow_call参数(即你示例里的with)不支持直接传递原生MAP类型,你写的tags: {"nginx":"new", "api":"old"}会被当作普通字符串处理,无法直接作为键值对使用。不过可以通过以下两种方式实现类似效果:
方法一:传递JSON字符串并解析
调用方工作流
jobs: docker_build_and_push: uses: test/test/.github/workflows/matrixDocker.yml@main with: service_name: nesso tags: '{"nginx":"new", "api":"old"}' # 用单引号包裹避免YAML解析歧义
被调用的matrixDocker.yml工作流
先定义输入参数为字符串类型,再通过GitHub Actions内置的fromJSON函数或jq工具解析为MAP:
on: workflow_call: inputs: service_name: type: string required: true tags: type: string required: true jobs: build: runs-on: ubuntu-latest steps: - name: 解析并遍历tags run: | # 直接用内置函数获取单个键值 echo "nginx的标签是: ${{ fromJSON(inputs.tags).nginx }}" # 用jq遍历所有键值对 echo '${{ inputs.tags }}' | jq -r 'to_entries[] | "\(.key)=\(.value)"' | while read -r line; do key=$(echo "$line" | cut -d'=' -f1) value=$(echo "$line" | cut -d'=' -f2) echo "处理服务: $key,标签: $value" done
方法二:传递键值对字符串并拆分
如果觉得JSON格式繁琐,可使用逗号分隔的键值对字符串传递:
调用方工作流
jobs: docker_build_and_push: uses: test/test/.github/workflows/matrixDocker.yml@main with: service_name: nesso tags: "nginx=new,api=old"
被调用的matrixDocker.yml工作流
通过shell脚本拆分字符串提取键值对:
on: workflow_call: inputs: service_name: type: string required: true tags: type: string required: true jobs: build: runs-on: ubuntu-latest steps: - name: 拆分并处理tags run: | IFS=',' read -ra TAG_LIST <<< "${{ inputs.tags }}" for tag_pair in "${TAG_LIST[@]}"; do IFS='=' read -r service tag <<< "$tag_pair" echo "构建服务: $service,使用标签: $tag" # 在这里添加你的Docker构建推送逻辑 done
内容的提问来源于stack exchange,提问作者Amir Damirov
相关产品推荐
相关产品推荐

