Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Created May 11, 2017 18:43
Show Gist options
  • Save Jaykul/f4edba36a187ad7d13d8ff9216bc4366 to your computer and use it in GitHub Desktop.
Save Jaykul/f4edba36a187ad7d13d8ff9216bc4366 to your computer and use it in GitHub Desktop.
I needed to do some octopus stuff, and didn't like any of the code I found ...
$OctopusInstallPath = "C:\Program Files\Octopus Deploy\Octopus";
Add-Type -Path "$OctopusInstallPath\Octopus.Client.dll"
function Set-OctopusEndpoint {
<#
.Synopsis
Sets the connection endpoint for an Octopus deploy instance
.DESCRIPTION
Registers the octopus endpoint with the given information.
In the ideal scenario, a Url and API key should be passed in, and the endpoint will be configured using them.
If credentials are provided instead, a new API key will be created and used.
If neither API Key nor credentials are available, and if the script is run on the actual Octopus server, (you must use -Force). In this case, the administrative user can be re-created, and an API key will be created and the endpoint configured.
The fact that this command has to be run manually from a console is as design. API Keys should be created only once, stored in a safe place and then reused.
API keys can be used to authenticate with the Octopus Deploy REST API in place of a username and password. Using API keys lets you keep your username and password secret, but the API key itself is still sensitive information that needs to be protected
.EXAMPLE
Set-OctopusEndpoint -ApiKeyReason "Scripting"
Does a full reset of the admin user with a random password and generates an API key with the reason "Scripting"
.LINK
Github project: https://github.com/Dalmirog/OctopusDeploy-Powershell-module
#>
[CmdletBinding(DefaultParameterSetName="FromCredential")]
param (
# The Url to the octopus API
[Parameter(Position=0)]
[string]$OctopusUrl = $Env:OctopusUrl,
# An API Key to use instead of credentials
[Parameter(ParameterSetName="ApiKey")]
[String]$APIKey,
# The credentials to use
[Parameter(ParameterSetName="FromCredential", Mandatory)]
[PSCredential]$Credential,
# If set, generate new credentials
[Parameter(ParameterSetName="NewAdminCredential", Mandatory)]
[Switch]$Force,
[Parameter(ParameterSetName="FromCredential")]
[Parameter(ParameterSetName="NewAdminCredential")]
[string]$ApiKeyReason = "Deployment Automation"
)
end {
if(!$APIKey) {
if($Force) {
$Credential = New-OctopusAdmin -Passthru
}
$endpoint = [Octopus.Client.OctopusServerEndpoint]$OctopusUrl
$repository = [Octopus.Client.OctopusRepository]$endpoint
$repository.Users.SignIn([Octopus.Client.Model.LoginCommand](
$Credential.GetNetworkCredential()| Select UserName, Password))
$user = $repository.Users.GetCurrent()
$APIKey = $repository.Users.CreateApiKey($user,$reason).ApiKey
write-warning "API keys cannot be retrieved once they are created. Make sure you save this key in a safe place like a password management tool."
}
# Return the actual endpoint itself
$script:Endpoint = [Octopus.Client.OctopusServerEndpoint]::new($OctopusUrl,$APIKey)
# Cast it to the repository to validate the API Key
$repository = [Octopus.Client.OctopusRepository]$endpoint
$script:Endpoint
}
}
enum OctopusResource {
Accounts
ActionTemplates
Artifacts
Backups
BuiltInPackageRepository
CertificateConfiguration
Certificates
Channels
CommunityActionTemplates
DashboardConfigurations
Dashboards
Defects
DeploymentProcesses
Deployments
Environments
Events
FeaturesConfiguration
Feeds
Interruptions
LibraryVariableSets
Lifecycles
MachinePolicies
MachineRoles
Machines
OctopusServerNodes
ProjectGroups
Projects
ProjectTriggers
Proxies
Releases
RetentionPolicies
Schedulers
ServerStatus
Subscriptions
TagSets
Tasks
Teams
Tenants
UserRoles
Users
VariableSets
}
function ParsePlural {
param([string]$Noun,[type]$enum)
if ($null -ne ($Noun -as $enum)) {
return $Noun -as $enum
} elseif ($null -ne ("${Noun}s" -as $enum)) {
return "${Noun}s" -as $enum
} elseif($null -ne "${Noun}es" -as $enum) {
return "${Noun}es" -as $enum
} elseif ($null -ne ${Noun} -replace "y","ies" -as $enum){
return ${Noun} -replace "y","ies" -as $enum
} else {
Write-Warning "Invalid value specified. $Noun is not a $enum"
}
}
function Remove-OctopusResource {
<#
.Synopsis
Removes octopus data model resource objects
.Description
The amazing generic resource function.
Warning: may not work for all resources, but works well enough for Users, Teams, and UserRoles ...
#>
[CmdletBinding(DefaultParameterSetName="All")]
param (
# Any valid resource type:
[Parameter()]
[OctopusResource]$Type = $(ParsePlural ($MyInvocation.InvocationName -replace "Remove-Octopus") "OctopusResource"),
[Parameter(ParameterSetName="Name", Mandatory, Position = 0)]
[string[]]$Name,
[Parameter(ParameterSetName="Filter", Mandatory, Position = 0)]
[ScriptBlock]$Filter,
[Parameter(ParameterSetName="Pipeline", Mandatory, ValueFromPipeline)]
[Octopus.Client.Model.Resource[]]$InputObject
)
# The ValidateSet is the output of this:
# $Repository | gm -Type Property | where Definition -match "Repositories" | Sort Name | % Name
begin {
if(!$Type) {
throw "Unspecified Type. You cannot call Remove-OctopusResource directly without specifying the type."
}
if(!$Script:Endpoint) {
throw "No endpoint configured. You must run Set-OctopusEndpoint"
}
if(!$Script:Repository) {
$Script:Repository = [Octopus.Client.OctopusRepository]$Endpoint
}
if(!$PSCmdlet.ParameterSetName -ne "Pipeline") {
$InputObject = $Repository.$Type.GetAll()
# # Certain things cannot be deleted (e.g. Builtin Teams, Roles)
# $InputObject = $InputObject.Where{ $_.CanBeDeleted -ne $False }
if($Filter){
$InputObject = $InputObject.Where($Filter)
} elseif($Name) {
$InputObject = $InputObject.Where{ $_.Name -in $Name }
}
}
}
process {
foreach($Resource in $InputObject) {
try {
$Repository.$Type.Delete($Resource)
} catch {
$ErrorMessage = "Cannot delete $Type $($Resource.Name)"
$Ex = if($_.Exception){ $_.Exception } else { $_ }
## Pass through the Errors to the Message so they're more visible
$ErrorMessages = @($Ex.Errors) + @($Ex.InnerException.Errors) | Where { $_ }
if($ErrorMessages) {
$ErrorMessage += ":`n - " + ($ErrorMessages -join "`n - ")
}
Write-Error -Exception $Ex -Message $ErrorMessage -TargetObject $Resource
}
}
}
}
function Get-OctopusResource {
[CmdletBinding(DefaultParameterSetName="All")]
param (
# Any valid resource type:
[Parameter()]
[OctopusResource]$Type = $(ParsePlural ($MyInvocation.InvocationName -replace "Get-Octopus") "OctopusResource"),
[Parameter(ParameterSetName="Name", Mandatory, Position=0)]
[string[]]$Name,
[Parameter(ParameterSetName="Filter", Mandatory, Position=0)]
[ScriptBlock]$Filter
)
# The ValidateSet is the output of this:
# $Repository | gm -Type Property | where Definition -match "Repositories" | Sort Name | % Name
begin {
if(!$Type) {
throw "Unspecified Type. You cannot call Get-OctopusResource directly without specifying the type."
}
if(!$Script:Endpoint) {
throw "No endpoint configured. You must run Set-OctopusEndpoint"
}
if(!$Script:Repository) {
$Script:Repository = [Octopus.Client.OctopusRepository]$Endpoint
}
}
process {
$Resources = $Repository.$Type.GetAll()
if($Filter){
$Resources = $Resources.Where($Filter)
} elseif($Name) {
$Resources = $Resources.Where{ $_.Name -in $Name -or $_.DisplayName -in $Name }
}
$Resources
}
}
function Set-OctopusResource {
[CmdletBinding()]
param(
# Any valid resource type:
[Parameter()]
[OctopusResource]$Type = $(ParsePlural ($MyInvocation.InvocationName -replace "Set-Octopus") "OctopusResource"),
[Parameter(Mandatory, ValueFromPipeline)]
[Octopus.Client.Model.TeamResource[]]$InputObject
)
begin {
if(!$Type) {
throw "Unspecified Type. You cannot call Remove-OctopusResource directly without specifying the type."
}
if(!$Script:Endpoint) {
throw "No endpoint configured. You must run Set-OctopusEndpoint"
}
if(!$Script:Repository) {
$Script:Repository = [Octopus.Client.OctopusRepository]$Endpoint
}
}
process {
## we need to ensure we don't remove ourselves from the admin
foreach($Resource in $InputObject) {
$Script:Repository.$Type.Modify($Resource)
}
}
}
Set-Alias Remove-OctopusUser Remove-OctopusResource
Set-Alias Remove-OctopusTeam Remove-OctopusResource
Set-Alias Remove-OctopusUserRole Remove-OctopusResource
Set-Alias Get-OctopusUser Get-OctopusResource
Set-Alias Get-OctopusTeam Get-OctopusResource
Set-Alias Get-OctopusUserRole Get-OctopusResource
Set-Alias Set-OctopusUser Set-OctopusResource
Set-Alias Set-OctopusTeam Set-OctopusResource
Set-Alias Set-OctopusUserRole Set-OctopusResource
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment