opentofu: Some providers fail in a confusing way when their configuration contains unknown values

OpenTofu Version

1.7.X

Use Cases

  • Deploy Kubernetes CRDs after the associated Helm resource has been applied
  • Deploy any resource with certificates fetched from a Vault resource

Attempted Solutions

This feature is only possible with depends_on support for providers. The only workaround is to setup a multi stage apply phase where tofu apply is executed multiple times in a specific order with parameters which determine that order. Workspaces help to define the difference between stages but different states as well as guaranteeing order of execution can be tricky.

Proposal

As per the attached reference to a comment I have previously made on the Terraform project, I am often encountering a “chicken and egg” scenario when applying resources to infrastructure. Currently, the depends_on property is not valid on provider blocks, which makes it problematic when values for those providers aren’t available until particular resources have been applied.

With this limitation, my proposal is to introduce depends_on support for provider blocks, enabling a dependency chain at a higher level than ordinary module and resource blocks. When depends_on is defined on provider blocks, their read phase should be deferred to a later stage when the particular resource in the array is ready. I suspect that this speaks to a much larger implementation of multi stage applies where some providers are not setup until after apply, effectively running two applies internally, invisible to the user.

Examples

Kubernetes manifests using Helm packages within the same apply phase

terraform {
  required_version = ">= 1.7"

  required_providers {
    kubernetes = {
      source  = "hashicorp/kubernetes"
      version = "~> 2.30"
    }
    helm = {
      source = "hashicorp/helm"
      version = "~> 2.13"
    }
  }

  backend "local" {}
}

provider "kubernetes" {
  config_path = "~/.kube/config"

  depends_on = [
    helm_release.traefik
  ]
}

provider "helm" {
  kubernetes {
    config_path = "~/.kube/config"
  }

  registry {
    url = "oci://localhost:5000"
    username = "username"
    password = "password"
  }
}

resource "helm_release" "traefix" {
  name = "traefik"

  repository = "https://traefik.github.io/charts"
  chart = "traefik"
}

resource "kubernetes_manifest" "traefik" {
  manifest = {
    apiVersion = "traefik.io/v1alpha1"
    kind = "IngressRoute"
    metadata = {
      name = "dashboard"
    }
    spec = {
      entryPoints = [
        "web"
      ]
      routes = [
        {
          match = "PathPrefix(`/dashboard`)"
          kind = "Rule"
          services = [
            {
              name = "api@internal"
              kind = "TraefikService"
            }
          ]
        }
      ]
    }
  }
}

Depending on a deployment which provides the secret token necessary for Vault authentication

terraform {
  required_version = ">= 1.7"

  required_providers {
    kubernetes = {
      source  = "hashicorp/kubernetes"
      version = "~> 2.30"
    }
    vault = {
      source = "hashicorp/vault"
      version = "~> 4.2"
    }
  }

  backend "local" {}
}

provider "kubernetes" {
  config_path = "~/.kube/config"
}

provider "vault" {
  token = data.some_data_source.vault_credentials.token

  depends_on = [
    kubernetes_deployment_v1.app
  ]
}

data "some_data_source" "vault_credentials" {
  # Some kind of configuration
}

resource "kubernetes_deployment_v1" "app" {
  metadata {
    name = "some-app-which-creates-vault-credentials"
  }

  spec {
    template {
      spec {
        container {
          name = "pod-for-vault-credentials"
          image = "foo:bar"
        }
      }
    }
  }
}

References

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 18
  • Comments: 22 (5 by maintainers)

Most upvoted comments

Currently battling this issue at the moment. We would like to:

  1. Build an EKS cluster
  2. Deploy plugins into that EKS cluster

…and do so ideally without needing to manually intervene via targeted apply or splitting workspaces. I’d be happy even if it took multiple applies, as long as I didn’t need to mess with arguments.

If the provider was lazily evaluated and could therefore get it’s values “just in time” once the cluster is created, we can then provision things into it successfully.

Also worth noting that the linked terraform issue was:

  • Opened in 2015
  • Had 137 comments
  • Had 472 👍🏻

An alternative approach, that I think will also work: provide a way to let OpenTofu simulate the plan (maybe it’s not that good a simulation) before the new API is available.

If we do that and you do a successful apply, then the simulation hints can be kept in the repo and ignored. A bit like import or moved blocks.

This could also help with code that:

  • defines a new Kubernetes namespace
  • enables feature flags (for whatever product), and then uses the new feature
  • defines a Git repository and then interacts with it
  • defines a service account / role, and then acts as that service account

the list really goes on

We can potentially discuss ways to react in a more automatic way to these new -exclude suggestions, but given that we don’t even know yet whether this mechanism will be broadly effective – the provider-side part of this is apparently only implemented for two providers right now – I’d suggest that we start with the hopefully-low-effort approach with a human-readable error message and see where that gets us.

As I mentioned before, I wouldn’t consider that improved error message to be sufficient to close either of these issues, but that incremental step seems like something we could do without a lot of invasive redesign of OpenTofu Core (still tbd, of course) and will hopefully give us some experience to help with designing whatever the final solution to this is, for which “keep trying up to N times to become converged” is one possible option.

(Just to keep all of these somewhat-overlapping discussions connected, I wrote about something similar to that idea in https://github.com/opentofu/opentofu/issues/812#issuecomment-2735045611 a few days ago too, although given the context of that other issue I was imagining it as something that surrounding orchestration tools would drive, rather than something that would be built in to OpenTofu. Nothing’s decided yet though, so we’re just considering the available options for the moment.)

If “the halting problem” was intended to refer to the possibility that a multi-stage plan/apply might never reach a converged state no matter how many rounds you run:

Indeed, it’s already possible to write an OpenTofu configuration that cannot converge by including contradictions in the configuration where each plan/apply round produces a different desired state to the previous one. This is a consequence of features like data sources that allow the desired state to be defined in terms of the current state of another system, rather than purely based on the configuration source code.

Any orchestration tool that tries to facilitate a multi-stage model would therefore need some sort of “runaway train prevention”, such as requiring manual approval for each round’s plan and giving the operator feedback about how many rounds there have been since the system was converged, or imposing an upper limit on how many rounds can be executed automatically before the system halts for human intervention.


I think my current preferred strategy for this issue is to improve the error messages for these situations using something like what I had suggested in the other issue and then see where that leaves us.

What I proposed over there relies on providers being updated to be able to explicitly signal “I can’t plan because the configuration is not known enough”, and we have found code in the Kubernetes provider that seems to implement such a signal, but it remains to be seen how widely it’s implemented in other providers that can encounter similar situations.

If we find that all of the main providers that cause problems like this implement those signals then we can think about other ways OpenTofu could make use of those signals to make things work more automatically, but if not then we’ll probably need to find a different answer. Updating the error handling seems like a relatively low-effort way to experiment with this provider protocol feature and learn more.

Is there nothing we could add to the lifecycle rules for certain things that will allow failure or not abort on failure so that OpenTofu makes a best effort plan / apply for what it can, and skip the stuff it’ll fail on?

Alternatively, can we not leverage depends_on with an extra argument or something that effectively tells OpenTofu “no, really, we depend on x before we can do anything to do with y”?

I’d be totally OK with it either requiring 2 separate applies, or it completes what it can plan for the first time, then plans again for the stuff it now knows about and can plan for.

If OpenTofu can warn us of unknown values and guide us with suggestions of -exclude targets, can a new argument be added to automatically run OpenTofu X number of times serially where X is the number of applies needed?

For example, given an output of “you must first run apply with -exclude provider.some_resource”, can we add a new argument -multi which recursively runs apply with each subsequent exclude needed until there are no more errors suggesting the use of -exclude? By providing the -multi argument, you are agreeing to create resources that output data necessary to instantiate a provider at the cost of potentially failing at that point due to invalid data. The tradeoff here is that you get multiple applies but any providers instantiated after the first might fail.

Of course that basically puts us back where we started: running OpenTofu again anyway because data from the first apply wasn’t valid for the providers in the second. The difference being that there is a clear dependency chain if I wanted to share my OpenTofu plan - there’s no need to document the correct order of -exclude arguments because OpenTofu would know that internally based on the dependency tree of unknown values.

I think unfortunately this issue got “stuck” in much the same way that the Terraform one did: it was describing a valid problem, but framing it in terms of a solution that probably isn’t actually sufficient to solve the problem, so it’s unclear what exactly it would mean to “accept” it.

OpenTofu already does respect dependencies between provider blocks and the other objects they refer to. The problem is not that OpenTofu is configuring the provider at the wrong time during the planning phase, but that it just isn’t possible to configure the provider during this plan phase at all. Introducing extra dependency edges to the execution graph won’t make that any better, because the prerequisites for successfully configuring the provider won’t happen until the apply phase.

In subsequent discussion I see folks talking about “multi-stage apply”, which I’d agree seems like the most likely outcome here: we can’t ask a provider to plan anything without configuring it first, and so if a provider refuses to work before some other action has been taken then I don’t really see any alternative to excluding that provider from the first plan/apply round so that its prerequisites can get dealt with and then running a second plan/apply round when hopefully the affected downstream provider will then successfully accept the configuration without returning any errors.

There was also some discussion about this in https://github.com/opentofu/opentofu/issues/2464, and I was dithering about whether to merge these together as one issue since I think they are both discussing different symptoms of the same problem. 🤔 However, I’ve not done that yet because I wanted to leave some room for further discussion and analysis in case someone has an idea for how to address some of these symptoms more directly, including the potential short-term stopgap workaround I was talking about in https://github.com/opentofu/opentofu/issues/2464#issuecomment-2669365525. (To be clear: I don’t expect that implementing that would close either issue, but it would at least make the error messages describe the root cause rather than just a symptom, and give some direct advice on how to work around it.)

The use-cases are actually documented in a number of official provider documentation with explicit reasoning why you can’t actually do it sadly. In my case it’s actually the following case (note the big “warning” that would be solved with this feature): https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs#stacking-with-managed-kubernetes-cluster-resources

Also can second @tgmatt that multiple applies are fine IMO.

The first example provided by the OP will replicate the issue, and we’ve faced this as well. When using the kubernetes_manifest resource, it tries to use an api that won’t exist until the helm_release has been applied. We’ve worked around this by separating the kubernetes_manifests into a separate module and use targeted applies, but it is suboptimal.

This seems to be related to #1677, at least in the sense that both can be addressed with multi-stage applys, but multi-stage doesn’t seem ideal.

You can provide some examples, ideally with code samples to show how this change would function in practice.

@marziply thank you for your issue! We have marked this as needs-community-input in a hope to get concrete examples not possible with OpenTofu today and how the community envisions that they would be solved.

As examples are provided we can continue the discussion around if “depends-on support for providers” or equivalent features should be added to OpenTofu.

Hello and thank you for this issue! The core team regularly reviews new issues and discusses them, but this can take a little time. Please bear with us while we get to your issue. If you’re interested, the contribution guide has a section about the decision-making process.