Dynamic creation of Target role using REST API

usability
known
(Rock26in) #1

Hi,

Is there a way by which I could dynamically create Target Role for a set of deployment targets in Octopus maybe by using REST API?

I’ve explored many pages but could not find a concrete answer. Neither I could find any rest API to create target roles.

Any help would be highly appreciated.

(Paul Calvert) #3

Hi @rock26in,

Thanks for getting in touch!

If you’re looking to work with the API, an excellent resource to start with is our GitHub page which includes a lot of samples for various actions.

We’d generally advise using the Octopus.Client when interacting with the API as it is typically simpler than scripting full REST API calls.

This script adds a target role to all deployment targets but would be a good starting point for you. If you’re planning to run this during a deployment, you could make use of the Octopus.Deployment.Machines system variable to only select the machine IDs used in the deployment.

# You can get this dll from your Octopus Server/Tentacle installation directory or from
# https://www.nuget.org/packages/Octopus.Client/
Add-Type -Path 'Octopus.Client.dll' 

$apikey = 'API-RASSW3YNB6FJL3FNWBSSUUCX0C' # Get this from your profile
$octopusURI = 'http://localhost:8065' # Your server address

$role = "A new role" # The role to add to each machine

$endpoint = New-Object Octopus.Client.OctopusServerEndpoint $octopusURI,$apikey 
$repository = New-Object Octopus.Client.OctopusRepository $endpoint

$machines = $repository.Machines.FindAll();

foreach ($machine in $machines) {
    $machine.Roles.Add($role)
    $repository.Machines.Modify($machine)
}

I hope this helps; let me know if you have any further questions.

Best regards,
Paul

(Rock26in) #4

Hi @paul.calvert,

Thank you so much for the useful information. It really helps!

I’m still thinking about your below comment as-in what would be the scenario?


If you’re planning to run this during a deployment, you could make use of the “Octopus.Deployment.Machines” system variable to only select the machine IDs used in the deployment.


Q: During deployment, is it possible to use this script or any other to create target roles at 1st step, and then dynamically pass-on that role into the 2nd step for deployment (in short having target role as a variable)?

As far as I know, step doesn’t even allow to save changes if we do not provide one or more target roles (existing, or new).

Thanks! :slight_smile:

(Paul Calvert) #5

Hi @rock26in,

It isn’t possible to have the target role as a variable, but it could be possible to change the role of a machine mid-deployment so steps that wouldn’t initially apply to it, now do.
This wouldn’t be particularly recommended, and I honestly can’t think of a scenario where you would want to, but I mentioned just in case you did.

Regards,
Paul

1 Like