class EnvVarsConverter implements ConfigurationProvisioner {

  @Override
  @Traced
  public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity)
      throws InfrastructureException {

    TracingTags.WORKSPACE_ID.set(identity::getWorkspaceId);

    for (PodData pod : k8sEnv.getPodsData().values()) {
      for (Container container : pod.getSpec().getContainers()) {
        String machineName = Names.machineName(pod, container);
        InternalMachineConfig machineConf = k8sEnv.getMachines().get(machineName);

        // we need to combine the env vars from the machine config with the variables already
        // present in the container. Let's key the variables by name and use the map for merging
        Map<String, EnvVar> envVars =
            machineConf
                .getEnv()
                .entrySet()
                .stream()
                .map(e -> new EnvVar(e.getKey(), e.getValue(), null))
                .collect(toMap(EnvVar::getName, identity()));

        // the env vars defined in our machine config take precedence over the ones already defined
        // in the container, if any
        container.getEnv().forEach(v -> envVars.putIfAbsent(v.getName(), v));

        // The environment variable expansion only works if a variable that is referenced
        // is already defined earlier in the list of environment variables.
        // We need to produce a list where variables that reference others always appear later
        // in the list.

        List<EnvVar> sorted = topoSort.sort(envVars.values());

        container.setEnv(sorted);
      }
    }
  }

}