Search code examples
github-actionsazure-powershell

Capturing IPs - github actions is looking for an array not a string


I am working on developing a deployment workflow via GH actions. The first job creates the vms(s) and I am using the second job to capture the IPs and then to shuttle these IPs over to the third job for patching.

The second job works well and captures the IPs but as a single string, '1.1.1.1 2.2.2.2'. I need the IPs in an array, ['1.1.1.1', '2.2.2.2'], for the matrix strategy in the third job to work.

The step in the second job is as follows:

outputs:
    ip-addresses: ${{ steps.get-ips.outputs.ips }}

- name: Capture Virtual Machine IPs
  id: get-ips
  shell: pwsh
  run: |
      foreach ($i in ${{ github.event.inputs.vmcount }}) {
         $ip=(Get-AzNetworkInterface -ResourceGroupName rg).IpConfigurations.PrivateIpAddress
      }
      Write-Output $ip
      echo "ips=$ip" >> $env:GITHUB_OUTPUT

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

Any ideas y'all?


Solution

  • The second job works well and captures the IPs but as a single string, '1.1.1.1 2.2.2.2'. I need the IPs in an array, ['1.1.1.1', '2.2.2.2'], for the matrix strategy in the third job to work.

    I agree with Azeem's comment; you can use $ip.Split(' ') | ConvertTo-Json -Compress in your script to get the IPs in an array.

    Alternatively, you can use the script below to get the required results.

    Script:

    outputs:
      ip-addresses: ${{ steps.get-ips.outputs.ips }}
    
    - name: Capture Virtual Machine IPs
      id: get-ips
      shell: pwsh
      run: |
        $ips = @()
        foreach ($i in ${{ github.event.inputs.vmcount }}) {
          $ip = (Get-AzNetworkInterface -ResourceGroupName rg).IpConfigurations.PrivateIpAddress
          $ips += $ip
        }
        $json = $ips | ConvertTo-Json -Compress
        Write-Output $json
        echo "ips=$json" >> $env:GITHUB_OUTPUT
    
    - name: Output values
      run: |
        echo "Output ${{ steps.get-ips.outputs.ips }}"
    

    Here, we can create an empty array called $ips before starting the loop. During each iteration of the loop, we add the IP address obtained from Get-AzNetworkInterface to the $ips array using the += operator. After the loop completes, we output the array of IP addresses and store it in the ips output variable.

    Output:

    ["10.5.0.7","10.5.0.8","10.5.0.9","10.5.0.12","10.5.0.10","10.5.0.6","10.5.0.4","10.5.0.5","10.5.0.15","10.5.0.11","10.5.0.4","10.5.0.16","10.5.0.17","10.5.0.14","10.5.0.13","10.1.0.4"]
    

    enter image description here