Create Tenant

Octopus.Script exported 2021-08-23 by benjimac93 belongs to ‘Octopus’ category.

Create an Octopus tenant with optional tenant tags and project connections.

Parameters

When steps based on the template are included in a project’s deployment process, the parameters below can be set.

Octopus URL

CloneTenantStep_OctopusUrl = #{if Octopus.Web.ServerUri}#{Octopus.Web.ServerUri}#{else}#{Octopus.Web.BaseUrl}#{/if}

The URL of the Octopus Server to create the tenant on.

Octopus API Key

CreateTenantStep_ApiKey =

The Octopus API Key to use for the API requests

Tenant Name

CreateTenantStep_TenantName =

The name of the tenant to create. Note this must be unique

Tenant Tags JSON

CreateTenantStep_TenantTags =

The tenant tags in a JSON array format. Example below.

[“TagSet1/Tag1”, “TagSet2/Tag1”, “TagSet2/Tag2”]

Project and Environments JSON

CreateTenantStep_ProjectEnvironments =

The projects and environments to connect the tenant to in JSON format. Example below.

{ “Projects-1”: [“Environments-1”, “Environments-2”], “Projects-2”: [“Environments-1”, “Environments-2”, “Environments-3”] }

Space Id

CloneTenantStep_SpaceId =

The Id of the Space used to clone the tenant. Leave blank if you are using an Octopus version earlier than 2019.1 or if you wish to use the Octopus.Space.Id variable value.

Script body

Steps based on this template will execute the following PowerShell script.

$securityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
[Net.ServicePointManager]::SecurityProtocol = $securityProtocol

$ErrorActionPreference = 'Stop'

$octopusBaseUrl = $CloneTenantStep_OctopusUrl.Trim('/')
$apiKey = $CreateTenantStep_ApiKey
$tenantName = $CreateTenantStep_TenantName
$tenantTags = if ($CreateTenantStep_TenantTags -eq $null) { @() } else { $CreateTenantStep_TenantTags | ConvertFrom-Json }
$projectEnvironments = if ($CreateTenantStep_ProjectEnvironments -eq $null) { @{} } else { $CreateTenantStep_ProjectEnvironments | ConvertFrom-Json }
$spaceId = $CloneTenantStep_SpaceId

if ([string]::IsNullOrWhiteSpace($octopusBaseUrl)) {
    throw "The step parameter 'Octopus Base Url' was not found. This step requires the Octopus Server URL to function, please provide one and try again."
}

if ([string]::IsNullOrWhiteSpace($apiKey)) {
    throw "The step parameter 'Octopus API Key' was not found. This step requires an API Key to function, please provide one and try again."
}

if ([string]::IsNullOrWhiteSpace($tenantName)) {
    throw "The step parameter 'Tenant Name' was not found. Please provide one and try again."
}

function Invoke-OctopusApi {
    param(
        [Parameter(Position = 0, Mandatory)]$Uri,
        [ValidateSet("Get", "Post", "Put", "Delete")]$Method = 'Get',
        $Body
    )
    
    $uriParts = @($octopusBaseUrl, $Uri.TrimStart('/'))    
    $uri = ($uriParts -join '/')
    
    Write-Verbose "Uri: $uri"
    
    $requestParameters = @{
        Uri = $uri
        Method = $Method
        Headers = @{ "X-Octopus-ApiKey" = $apiKey }
        UseBasicParsing = $true
    }
    
    if ($null -ne $Body) { $requestParameters.Add('Body', ($Body | ConvertTo-Json -Depth 10)) }
    
    return Invoke-WebRequest @requestParameters | % Content | ConvertFrom-Json
}

function Test-SpacesApi {
	Write-Verbose "Checking API compatibility";
	$rootDocument = Invoke-OctopusApi 'api/';
    if($rootDocument.Links -ne $null -and $rootDocument.Links.Spaces -ne $null) {
    	Write-Verbose "Spaces API found"
    	return $true;
    }
    Write-Verbose "Pre-spaces API found"
    return $false;
}

if([string]::IsNullOrWhiteSpace($spaceId)) {
	if(Test-SpacesApi) {
      	$spaceId = $OctopusParameters['Octopus.Space.Id'];
      	if([string]::IsNullOrWhiteSpace($spaceId)) {
          	throw "This step needs to be run in a context that provides a value for the 'Octopus.Space.Id' system variable. In this case, we received a blank value, which isn't expected - please reach out to our support team at https://help.octopus.com if you encounter this error or try providing the Space Id parameter.";
      	}
	}
}

$apiPrefix = "api/"
$tenantUrlBase = @($octopusBaseUrl, 'app#')

if ($spaceId) {
	Write-Host "Using Space $spaceId"
	$apiPrefix += $spaceId
    $tenantUrlBase += $spaceId
}

$body = @{
	Id = $null
    Name = $tenantName
    TenantTags = @($tenantTags)
    ProjectEnvironments = $projectEnvironments
}

Write-Host "Creating tenant $tenantName"
$tenant = Invoke-OctopusApi "$apiPrefix/tenants" -Method Post -Body $body
$tenantUrl = ($tenantUrlBase + "tenants" + $tenant.Id + "overview") -join '/'

Write-Highlight "New tenant [$tenantName]($tenantUrl) has been created."

Provided under the Apache License version 2.0.

Report an issue

To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.

{
  "Id": "581e7211-c9e2-4d7b-8934-bcdac421d022",
  "Name": "Create Tenant",
  "Description": "Create an Octopus [tenant](https://octopus.com/docs/deployment-patterns/multi-tenant-deployments) with optional tenant tags and project connections.",
  "Version": 4,
  "ExportedAt": "2021-08-23T12:40:10.975Z",
  "ActionType": "Octopus.Script",
  "Author": "benjimac93",
  "Packages": [],
  "Parameters": [
    {
      "Id": "9c6ce5ed-e370-4150-88c0-880984531a48",
      "Name": "CloneTenantStep_OctopusUrl",
      "Label": "Octopus URL",
      "HelpText": "The URL of the Octopus Server to create the tenant on.",
      "DefaultValue": "#{if Octopus.Web.ServerUri}#{Octopus.Web.ServerUri}#{else}#{Octopus.Web.BaseUrl}#{/if}",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "a57b379b-a0dd-4d0e-8229-7bd358448766",
      "Name": "CreateTenantStep_ApiKey",
      "Label": "Octopus API Key",
      "HelpText": "The Octopus API Key to use for the API requests",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "Sensitive"
      }
    },
    {
      "Id": "e02927d1-e2a3-4887-b5d3-c49b12a297a2",
      "Name": "CreateTenantStep_TenantName",
      "Label": "Tenant Name",
      "HelpText": "The name of the tenant to create. *Note this must be unique*",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "3c3364b8-69f9-458f-9b34-efc591c8882e",
      "Name": "CreateTenantStep_TenantTags",
      "Label": "Tenant Tags JSON",
      "HelpText": "The tenant tags in a JSON array format. Example below.\n\n*[\"TagSet1/Tag1\", \"TagSet2/Tag1\", \"TagSet2/Tag2\"]*",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "a68945f1-7adc-4015-80da-dc3a3ce0b571",
      "Name": "CreateTenantStep_ProjectEnvironments",
      "Label": "Project and Environments JSON",
      "HelpText": "The projects and environments to connect the tenant to in JSON format. Example below.\n\n*{ \"Projects-1\": [\"Environments-1\", \"Environments-2\"], \"Projects-2\": [\"Environments-1\", \"Environments-2\", \"Environments-3\"] }*",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "5f80b46a-d09c-4092-8a0f-fcc96c49fde2",
      "Name": "CloneTenantStep_SpaceId",
      "Label": "Space Id",
      "HelpText": "The Id of the Space used to clone the tenant. **Leave blank if you are using an Octopus version earlier than 2019.1 or if you wish to use the Octopus.Space.Id variable value.**",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptSource": "Inline",
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptBody": "$securityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12\n[Net.ServicePointManager]::SecurityProtocol = $securityProtocol\n\n$ErrorActionPreference = 'Stop'\n\n$octopusBaseUrl = $CloneTenantStep_OctopusUrl.Trim('/')\n$apiKey = $CreateTenantStep_ApiKey\n$tenantName = $CreateTenantStep_TenantName\n$tenantTags = if ($CreateTenantStep_TenantTags -eq $null) { @() } else { $CreateTenantStep_TenantTags | ConvertFrom-Json }\n$projectEnvironments = if ($CreateTenantStep_ProjectEnvironments -eq $null) { @{} } else { $CreateTenantStep_ProjectEnvironments | ConvertFrom-Json }\n$spaceId = $CloneTenantStep_SpaceId\n\nif ([string]::IsNullOrWhiteSpace($octopusBaseUrl)) {\n    throw \"The step parameter 'Octopus Base Url' was not found. This step requires the Octopus Server URL to function, please provide one and try again.\"\n}\n\nif ([string]::IsNullOrWhiteSpace($apiKey)) {\n    throw \"The step parameter 'Octopus API Key' was not found. This step requires an API Key to function, please provide one and try again.\"\n}\n\nif ([string]::IsNullOrWhiteSpace($tenantName)) {\n    throw \"The step parameter 'Tenant Name' was not found. Please provide one and try again.\"\n}\n\nfunction Invoke-OctopusApi {\n    param(\n        [Parameter(Position = 0, Mandatory)]$Uri,\n        [ValidateSet(\"Get\", \"Post\", \"Put\", \"Delete\")]$Method = 'Get',\n        $Body\n    )\n    \n    $uriParts = @($octopusBaseUrl, $Uri.TrimStart('/'))    \n    $uri = ($uriParts -join '/')\n    \n    Write-Verbose \"Uri: $uri\"\n    \n    $requestParameters = @{\n        Uri = $uri\n        Method = $Method\n        Headers = @{ \"X-Octopus-ApiKey\" = $apiKey }\n        UseBasicParsing = $true\n    }\n    \n    if ($null -ne $Body) { $requestParameters.Add('Body', ($Body | ConvertTo-Json -Depth 10)) }\n    \n    return Invoke-WebRequest @requestParameters | % Content | ConvertFrom-Json\n}\n\nfunction Test-SpacesApi {\n\tWrite-Verbose \"Checking API compatibility\";\n\t$rootDocument = Invoke-OctopusApi 'api/';\n    if($rootDocument.Links -ne $null -and $rootDocument.Links.Spaces -ne $null) {\n    \tWrite-Verbose \"Spaces API found\"\n    \treturn $true;\n    }\n    Write-Verbose \"Pre-spaces API found\"\n    return $false;\n}\n\nif([string]::IsNullOrWhiteSpace($spaceId)) {\n\tif(Test-SpacesApi) {\n      \t$spaceId = $OctopusParameters['Octopus.Space.Id'];\n      \tif([string]::IsNullOrWhiteSpace($spaceId)) {\n          \tthrow \"This step needs to be run in a context that provides a value for the 'Octopus.Space.Id' system variable. In this case, we received a blank value, which isn't expected - please reach out to our support team at https://help.octopus.com if you encounter this error or try providing the Space Id parameter.\";\n      \t}\n\t}\n}\n\n$apiPrefix = \"api/\"\n$tenantUrlBase = @($octopusBaseUrl, 'app#')\n\nif ($spaceId) {\n\tWrite-Host \"Using Space $spaceId\"\n\t$apiPrefix += $spaceId\n    $tenantUrlBase += $spaceId\n}\n\n$body = @{\n\tId = $null\n    Name = $tenantName\n    TenantTags = @($tenantTags)\n    ProjectEnvironments = $projectEnvironments\n}\n\nWrite-Host \"Creating tenant $tenantName\"\n$tenant = Invoke-OctopusApi \"$apiPrefix/tenants\" -Method Post -Body $body\n$tenantUrl = ($tenantUrlBase + \"tenants\" + $tenant.Id + \"overview\") -join '/'\n\nWrite-Highlight \"New tenant [$tenantName]($tenantUrl) has been created.\""
  },
  "Category": "Octopus",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/create-tenant.json",
  "Website": "/step-templates/581e7211-c9e2-4d7b-8934-bcdac421d022",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAC1QTFRFT6Tl////L5Pg8vj9Y67omsvwPJrisdfzfbzs5fL7y+T32Ov5isLucLXqvt31CJPHWwAABMJJREFUeNrs3deW4jAMAFDF3U75/89dlp0ZhiU4blJEjvQ8hYubLJsA00UCBCIQgQhEIAIRiEAEIhCBCEQgAhGIQAQiEIEIhD8kJm+t+QprfdKfB9HbYpx6CWfspj8HMi+gMgHL/AmQA8W3JTKH+ALFvzCeL0RbpyoCPE9IJeNOSQwh5Z3qd6yRGWQ2qi2cZQWxqj1WzQYSjeoJmJlAklOd4VlArOqPhQEkqBERToeMcfRJBkC0Uep8CfBpjz4JsHJ0zF3dkEWNje0kiB/sUC6eApndaIiCMyAa1PiwJ0AWhRGJHJJQHG2dC7h1rNbO1QOxSA7lNCkkKrQIpJCAB1GREILYIC1NAiwbpKFJgGWDNExcwGstfExcZBCHC6nOglshHtmhViLIig1RNBCN7qjtW8C0Z1UvJcC1Z9XmwMBzzvobmgAyEzgq91dtEEsBsQSQQAFZCSBAATEEEApHZb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fDZm8+zqP+HTIpK0xQ796b5Kv2hSIQAQiEIEIRCACEYhABCIQgQhEIAIRiEAEIpBf8UeAAQAEjtYmlDTcCgAAAABJRU5ErkJggg==",
  "$Meta": {
    "Type": "ActionTemplate"
  }
}

History

Page updated on Monday, August 23, 2021