Cannot remove Environment from Lifecycle using Octopus.Client

I’m having a hard time removing an environment from a lifecycle. Here’s the code:

        private static void RemoveEnvironmentFromLifecycle(OctopusRepository repo, EnvironmentResource environment, string lifecycleName)
        {
            var lifecycle = repo.GetLifecycle(lifecycleName);

            lifecycle.RemoveEnvironment(environment);
            
            if (_force)
                repo.Lifecycles.Modify(lifecycle);
        }

        public static void RemoveEnvironment(this LifecycleResource lifecycle, EnvironmentResource environment)
        {
            var targets = lifecycle.Phases[0].OptionalDeploymentTargets;
            
            if (!targets.Contains(environment.Id))
            {
                Program.Logger.Info("Environment '{0}' is not in lifecycle '{1}'.", environment.Name, lifecycle.Name);
                return;
            }

            Program.Logger.Info("Removing environment '{0}' from lifecycle '{1}'.", environment.Name, lifecycle.Name);
            targets.Remove(environment.Id);
        }

It appears to simply not work, but maybe I’m missing something. I am using the latest version of Octopus.Client: 3.3.8.0 and my Octopus server is at 3.3.6.

Hi,

A few considerations:

  • repo.Lifecycles.Modify(lifecycle) will always have to be called if you wish to persist the lifecycle. I’m not sure currently what is setting your _force flag.

  • You are currently only removing the environment from the first phase of the lifecycle (i.e. lifecycle.Phases[0]). You must iterate over all phases if you wish to remove the environment from all phases.

  • You are currently only removing the environment from the OptionalDeploymentTargets. If the environment is automatically deployed to, it will be in the AutomaticDeploymentTargets collection.

  • If after removing the environment from the phase there are no remaining environments, that phase will be Any environment. This means that any environment not specifically listed in another phase can be deployed to. This can cause it to appear in the UI as if the environment had not been removed (if it is the last remaining environment that is not listed in another phase). This tripped me up :slight_smile:

I hope those points help. I just tested this myself, and taking those points into account, it appears to function as expected.

Please let me know if you’re still having issues.

Regards,
Michael