user833115xxx
user833115xxx

Reputation: 303

How to run an Azure DevOps pipeline from code?

I have been working with an Azure DevOps release definition and triggering it from some C# code:

var releaseClient = VssConnection.GetClient<ReleaseHttpClient>();

return await releaseClient.CreateReleaseAsync(
    _releaseDefinitionId,
    $"Release run for {build.BuildNumber}",
    build.Definition.Name,
    build.Id,
    new Dictionary<string, string> {
        { "InputVariable1", _value1 },
        { "InputVariable2", _value2 },
        { "DatabaseConnectionString", "xxxxxxx" }
    });

I've now converted that release definition to a pure YAML pipeline - is there any way to trigger the running of that pipeline from C#?

Thanks!

Upvotes: 2

Views: 4588

Answers (1)

Krzysztof Madej
Krzysztof Madej

Reputation: 40939

You can trigger YAML build in this way:

var credential = new VssBasicCredential(string.Empty, "PAT");
var connection = new VssConnection(new Uri("https://dev.azure.com/thecodemanual/"), credential);
var buildClient = connection.GetClient<BuildHttpClient>();

var projectClient = connection.GetClient<ProjectHttpClient>();
var project = projectClient.GetProject("DevOps Manual").Result;
Console.WriteLine(project.Name);

var definition = buildClient.GetDefinitionAsync("DevOps Manual", 48).Result;

Console.WriteLine(definition.Name);

var build = new Build()
{
    Definition = definition,
    Project = project
};
string _value1 = "someStr1";
string _value2 = "someStr2";
var dict = new Dictionary<string, string> { { "InputVariable1", _value1 }, { "InputVariable2", _value2 }, { "DatabaseConnectionString", "xxxxx" } };
build.Parameters = JsonConvert.SerializeObject(dict);

buildClient.QueueBuildAsync(build).Wait();

Upvotes: 7

Related Questions