Search code examples
yamlgithub-actions

How do you use an input variable to specify which self-hosted runner a GitHub action would run on?


I'm using GitHub Actions.

I'm trying to create a self-hosted runner that will run on one of several cloud servers, but be able to control which specific server it runs on. This is to do rolling updates on machines that have local resources.

I've setup tags with the self-hosted runners, but so far am having to make 1..N separate YML scripts:

 on: 

    workflow_dispatch:

  jobs:
    post-to-server1:
      runs-on: [self-hosted, server1 ]

Then I have to repeat this script n number of times.

What I'd like to do is this:

name: 'Server Patching'

on:
    workflow_dispatch:
      inputs:
        server-target:
            description: 'Target Server:'
            required: true
            default: 'dev'
    
jobs:
  test-params:    
    runs-on: [ self-hosted, ${{ github.event.inputs.server-target }}]
    steps:
      - name: Start cloning of ${{ github.event.inputs.server-target }}
        run: |
            echo "Starting patching of: '${{ github.event.inputs.server-target }}'"

Check failure on line 12 in .github/workflows/test_workflow.yml
GitHub Actions / .github/workflows/test_workflow.yml

Invalid workflow file

You have an error in your yaml syntax on line 12

Is there a way to do this?

I tagged this YAML also, because the variable substitution seems to be an issue with the YAML syntax as well (although it may be specific for GitHub Actions)

Update: Yes, you can, if you change this line:

    runs-on: [ self-hosted, ${{ github.event.inputs.server-target }}]

to:

    runs-on: ${{ github.event.inputs.server-target }}

The error actually happens on test-params: not the line below it.

My theory is that the syntax checker fires before the variable substitution?


Solution

  • I know I'm a bit late to this, but if anyone needs it here's what I found out. The solution proposed by timmeinerzhagen works only for one runner label. However, if an array of labels should be provided, it should look like this:

    on:
      workflow_dispatch:  
        inputs:
          runs_on:
            description: 'Runner requirements'
            required: true
            type: string
            default: "[\"self-hosted\"]"
    jobs:
      Build_project:
        runs-on: ${{ fromJSON(github.event.inputs.runs_on) }}
    

    Then, simply pass in a json array, like this: "[\\"myLabel\\",\\"myOtherLabel\\"]". This worked for me.