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

GitHub Actions捕获IP:需数组格式而非字符串

解决方法

1. 修正第二个Job的IP捕获脚本

需要修改PowerShell步骤,正确收集所有VM的IP并输出为JSON数组格式,让GitHub Actions能识别为数组类型。

修改后的第二个Job代码:

jobs:
  # 第一个Job:创建VM(保留原有创建逻辑)
  create-vms:
    runs-on: ubuntu-latest
    # ... 你的VM创建步骤

  # 第二个Job:捕获VM IP并输出JSON数组
  capture-ips:
    needs: create-vms
    runs-on: ubuntu-latest
    outputs:
      ip-addresses: ${{ steps.get-ips.outputs.ips }}
    steps:
      - name: Capture Virtual Machine IPs
        id: get-ips
        shell: pwsh
        run: |
          # 直接获取目标资源组下所有网卡的私有IP
          $ips = (Get-AzNetworkInterface -ResourceGroupName rg).IpConfigurations.PrivateIpAddress
          # 将IP数组转换为紧凑的JSON格式(避免换行干扰)
          $jsonIps = $ips | ConvertTo-Json -Compress
          # 将JSON数组写入GitHub Actions输出变量
          echo "ips=$jsonIps" >> $env:GITHUB_OUTPUT

      - name: Output values
        run: |
          echo "Output ${{ steps.get-ips.outputs.ips }}"

关键修改点:

  • 移除无效的foreach循环:原循环会遍历vmcount的字符(比如输入2会仅遍历'2'),无实际意义,直接一次性获取资源组下所有网卡IP即可
  • 使用ConvertTo-Json -Compress将IP数组转为标准JSON字符串(格式为["1.1.1.1","2.2.2.2"])
  • 确保输出的ips变量是符合JSON规范的数组格式

2. 在第三个Job中用JSON数组作为Matrix输入

第三个Job通过needs依赖第二个Job,再用fromJSON()函数将输出的JSON字符串解析为数组,供Matrix策略使用:

# 第三个Job:补丁操作
apply-patches:
  needs: capture-ips
  runs-on: ubuntu-latest
  strategy:
    matrix:
      ip: ${{ fromJSON(needs.capture-ips.outputs.ip-addresses) }}
  steps:
    - name: Apply patch to ${{ matrix.ip }}
      run: |
        echo "Applying patch to VM with IP: ${{ matrix.ip }}"
        # 此处添加你的补丁操作代码

说明:

  • fromJSON()会将JSON字符串转为GitHub Actions可识别的数组
  • Matrix会自动遍历数组中的每个IP,为每个IP创建独立的任务实例

额外优化建议

  • 如果需要过滤特定VM的IP,可在Get-AzNetworkInterface后添加过滤条件:
    $ips = (Get-AzNetworkInterface -ResourceGroupName rg | Where-Object { $_.Name -match "指定VM名称前缀" }).IpConfigurations.PrivateIpAddress
    
  • 若需按vmcount限制IP数量,可添加Select-Object:
    $ips = (Get-AzNetworkInterface -ResourceGroupName rg).IpConfigurations.PrivateIpAddress | Select-Object -First ${{ github.event.inputs.vmcount }}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 22:10:24