Search code examples
apirestpowershelloctopus-deploy

Create Octopus machine via REST API (PowerShell)


I’m trying to create a machine via the REST API, calling it through PowerShell.

According to the documentation, only the name and thumbprint of the machine are needed to create a machine. But everything I try leads to either 405 or 500 errors:

$newMachine = @{Name='machineName';Thumbprint='asdvblsafghkvadc';} | ConvertTo-Json
$webClient.UploadString('http://server/octopus/api/machines','POST',$newMachine)

### OR

$newMachine = @{Name='machineName';Thumbprint='asdvblsafghkvadc';Roles='[web-server]';EnvironmentIds='[Environment-12]'; | ConvertTo-Json
$webClient.UploadString('http://server/octopus/api/machines','POST',$newMachine)

Creating environments and editing machines work perfectly, I just can’t get this machine creation down.


Solution

  • To create a machine from the Octopus REST API, certain libraries need to imported. Dalmiro Grañas outlines this in the first of a series of blog posts on interfacing with Octopus through PowerShell

    He does not cover creating machines though, this is something I had to figure out myself from the library documentation on the MachineResource class

    Below is the code I wound up using to create machines:

    #Adding libraries
    Add-Type -Path 'C:\OctopusLibraries\Newtonsoft.Json.dll'
    Add-Type -Path 'C:\OctopusLibraries\Octopus.Client.dll'
    Add-Type -Path 'C:\OctopusLibraries\Octopus.Platform.dll'
    
    #Setting variables
    $apikey = 'API-QBGAAZEUMSUKJVSADFSDFA5Y2FLC'
    $OctopusURI = 'http://OctopusServer/octopus/api/'
    
    #Creating a connection
    $endpoint = new-object Octopus.Client.OctopusServerEndpoint $OctopusURI,$apikey
    $repository = new-object Octopus.Client.OctopusRepository $endpoint
    
    #Set the machine properties
    $Properties = @{Name="MachineName";Thumbprint="1AE1B6F81A30C2C5771AC5B234S4FE975";EnvironmentIds="Environments-65";Roles="web-server";URI="https://MyServer:10933/";CommunicationStyle="TentaclePassive"}
    
    $envObj = New-Object Octopus.Client.Model.MachineResource -Property $Properties
    $repository.Machines.Create($envObj)