Search code examples
powershellsshargumentsruntime-errorgithub-actions

Unable to use powershell's sshArgs to invoke a simple ssh command on remote linux host


Below is my github playbook that should invoke an ssh command hostname on remote linux host using windows runner's powershell.

name: Check Disk Space on Remote Hosts

on:
  push:
    branches:
      - main

jobs:
  check_disk_space:
    runs-on: windows-latest
steps:
  - name: Checkout code
    uses: actions/checkout@v3

  - name: Run PowerShell script
    shell: PowerShell
    run: |

      $remoteHosts = "80.240.24.192,80.240.24.193".Split(",")
      $user="root"
      Set-Content -Path "C:\id_rsa" -Value '{{ secrets.myunixkey }}'
      icacls "C:\id_rsa" /inheritance:r /grant $env:USERNAME`:`R"

      foreach ($eachHost in $remoteHosts) {
        echo $eachHost

        $sshArgs = @(
          "-o", "StrictHostKeyChecking=no",
          "-o", "UserKnownHostsFile=/dev/null",
          "-i", "C:\id_rsa",
          "$user@$eachHost",
          "hostname"
        )

        Write-Output "$sshArgs"
        #$sshCommand = "ssh.exe $sshArgs"
        #$output = Invoke-Expression $sshCommand
        #Write-Output $output
      }

I get the below error upon execution:

Run #$remoteHosts = "".Split(",")
  
At D:\a\_temp\01fae33c-005b-4e08-a955-7adb1085c97f.ps1:24 char:25
+   Write-Output "$sshArgs"
+                         ~
The string is missing the terminator: ".
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
 
Error: Process completed with exit code 1.

Note: it prints echo $eachHost alright each host at a time.

Test case here: https://github.com/knowyrtech/invokebashfrompowershell/blob/main/.github/workflows/main.yml

The error for the run "https://github.com/knowyrtech/invokebashfrompowershell/actions/runs/5875518287/job/15931923850" snapshot is below:

enter image description here

You are free to make changes in my public repository as u like.

Can you please suggest what I am missing in trying to construct my ssh args correctly in PowerShell?


Solution

  • This line uses incorrect quoting:

    icacls "C:\id_rsa" /inheritance:r /grant $env:USERNAME`:`R"
    

    Therefore, all following quotes will be interpreted wrong. Change it to:

    icacls "C:\id_rsa" /inheritance:r /grant "$($env:USERNAME):R"