Remove environments from Scopes

Hi,

I would like to know if it’s possible to remove an environment directly from all the scopes to be able to delete it without going into every projects’ variable?

We’ve got thousands of variables and it will be very nice if we can do it like that :slight_smile:

Thanks

Hi there,

Thanks for getting in touch!

There’s a couple of ways you can go about it

  1. You can delete the environment which will also remove the environment from any variable that is scoped to it, and if the variable is only scoped to that environment it will be deleted (so we don’t leave variables that were scoped to become global), or
  2. You can write a script to use the API to delete the environment from any variables that are scoped to the environment. See sample script below:
var endpoint = new OctopusServerEndpoint("<urltoyouroctopusserver>", "<yourapikey>");
var repository = new OctopusRepository(endpoint);
var environment = repository.Environments.FindByName("<theenvironmentyouwanttoremove>");

var projects = repository.Projects.GetAll();
foreach (var project in projects)
{
	var variableSet = repository.VariableSets.Get(project.VariableSetId);
	foreach (var variable in variableSet.Variables.Where(v => v.Scope.ContainsKey(ScopeField.Environment) && v.Scope[ScopeField.Environment].Contains(environment.Id)))
	{
		variable.Scope[ScopeField.Environment].Remove(environment.Id);
	}
	repository.VariableSets.Modify(variableSet);
}

var libraryVariableSets = repository.LibraryVariableSets.FindAll();
foreach (var libraryVariableSet in libraryVariableSets)
{
	var variableSet = repository.VariableSets.Get(libraryVariableSet.VariableSetId);
	foreach (var variable in variableSet.Variables.Where(v => v.Scope.ContainsKey(ScopeField.Environment) && v.Scope[ScopeField.Environment].Contains(environment.Id)))
	{
		variable.Scope[ScopeField.Environment].Remove(environment.Id);
	}
	repository.VariableSets.Modify(variableSet);
}

I hope that helps!

Thank you and best regards,
Henrik