Changing the environment of multiple targets using a script

We have a situation where we have environments that we replicate (Production/Staging principle) and want to know if it possible to run a script against a number of targets in one environment so that they are removed from that environment and added to a different one. I know you can deregister on the target and re-register but this is laborious for multiple targets so I am assuming this can be done with powershell?

Hi,

Thanks for reaching out. There’s an OSS project called Octoposh that could come in handy in this case.

The script below uses Octoposh and it removes an Environment ID from one or many machines, then adds a new one and saves the changes on the database


###Configuration###
$RemoveEnvName = "Development" #Name of the environment you want to remove from the machine

$AddEnvName = "Production" #name of the environment you want to add to the machine

$SourceEnv = "Development" #name of the environment from where you want to pick up the machines for the changes. This value will be used for the Get-OctopusMachine cmdlet. If you want to pass separate machine names instead of a whole environment, you can do so as well using the -machinename parameter

###Execution###

$RemoveEnv = Get-OctopusEnvironment -EnvironmentName $RemoveEnvName -ResourceOnly

$AddEnv = Get-OctopusEnvironment -EnvironmentName $AddEnvName -ResourceOnly

$machines = Get-OctopusMachine -ResourceOnly -EnvironmentName $SourceEnv

Foreach($machine in $machines){
    Write-Output "Updating machine $($machine.Name)"

    Write-Output "Removing environment $($RemoveEnv.name) from $($machine.Name)"

    $Machine.EnvironmentIds.Remove($RemoveEnv.id)

    Write-Output "Adding environment $($AddEnv.name) to $($machine.Name)"

    $Machine.EnvironmentIds.Add($AddEnv.id)

    Write-Output "Saving machine changes on database"

    Update-OctopusResource -Resource $machine -Force
}

Project site: http://octoposh.net/

Let me know if that helps,
Dalmiro