Search code examples
c#gitlabgitlab-ci-runnergitlab-api

GitLab API: Create Job and run in runner


I would like to trigger new job for runner but I get bed request. How to do it correctly?

 public async Task<string> TriggerCommandOnRunner(int runnerId, string command)
    {
        try
        {
            // Create a new job to run the specified command on the GitLab Runner.
            var jobRequest = new
            {
                job = new
                {
                    runner_id = runnerId,
                    script = command
                }
            };

            var content = new StringContent(JsonSerializer.Serialize(jobRequest), Encoding.UTF8,
                "application/json");
            var response = await _httpClient.PostAsync($"{_gitLabUrl}jobs/request", content);

            if (response.IsSuccessStatusCode)
            {
                var responseBody = await response.Content.ReadAsStringAsync();
                // Parse and process the responseBody as needed.
                return responseBody;
            }

            return await Task.FromResult("failed with connection");
        }
        catch (Exception ex)
        {
            return await Task.FromResult($"failed {ex.Message}");
        }

        return string.Empty;
    }

Solution

  • The API that resides at /jobs/request is not a public API intended to be used directly by GitLab users. It should only ever be used by actual GitLab Runner executors provided by GitLab, never user code. Additionally, its purpose is not for creating jobs or commands to run. This is an internal API used by runners to request jobs that are already created and in the queue on the GitLab server.

    If you're trying to create new jobs for the runner to execute, you should be using an API intended for user consumption, like the pipelines API to create a pipeline or other normal ways of creating pipelines. If you want to create pipelines with dynamic scripts, see: dynamic child pipelines.