Getting the projects that use a machine role

I saw this topic

and although it was closed, I accomplished what I believe is similar. Here is C# code to do it.

// find the projects that reference the roles used by particular machines

// initialize endpoint and repo
var endpoint = new OctopusServerEndpoint(Environment.GetEnvironmentVariable("OCTOPUS_SERVER"), Environment.GetEnvironmentVariable("OCTOPUS_CLI_API_KEY"));
var repository = new OctopusRepository(endpoint);

// get the machines we are interested in
string[] machineNames = {"MTLWPVSCWEB11","MTLWPVSCWEB12","MTLWPVSCWEB13"};
var machines = repository.Machines.FindByNames(machineNames);

// get all the roles used by those machines
var roles = machines.SelectMany(m => m.Roles).Distinct();
Debug.WriteLine($"Looking for projects using these roles: [{String.Join(",",roles)}]");
Debug.WriteLine("----")

// get all the project groups to a dictionary for later lookup
var projGroups = repository.ProjectGroups.FindAll().ToDictionary(pg => pg.Id);

// get all the projects and iterate over them
var projs = repository.Projects.FindAll();
foreach (var p in projs) {
    // fetch the project's current deployment process
	var d = repository.DeploymentProcesses.Get(p.DeploymentProcessId);
	// see if the deployment process has any steps scoped to the roles of interest
	if (d.Steps.Any(st => st.Properties.ContainsKey("Octopus.Action.TargetRoles") && roles.Contains(st.Properties["Octopus.Action.TargetRoles"].Value)))
	{
		// output the project name and the group it's in
		Debug.WriteLine($"{p.Name} : {projGroups[p.ProjectGroupId].Name}");
	}
}

Hi Ross,

Thanks for getting in touch, and thank you very kindly for taking the time to post your solution here! As far as Iā€™m aware, this is the first sample script to get this specific info, so it will be very handy to be able to reference this in the future! Much appreciated. :slight_smile:

Best regards,

Kenny

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.