fetch and update particular field using terraform

2/2/2021

i have a scenario,

How to fetch particular field value and also update particular field value?

For example : Im deploying an application using terraform "kubernetes_deployment" resource configured with environment variables(endpoint=abc) and replicas=2.

resource "kubernetes_deployment" “app” {
…..….
spec {
  replicas = 2
  template {
    spec {
     ….
      env {
        name  = “ENDPOINT”
        value = “abc”
    }
}

Once i deployed using terraform script, another script might change configurations replicas=5 and environment values(endpoint=xyz)

Now i need to update only replicas to 20(if replicas < 20) through terraform script without changing the environment values(endpoint=abc)?

resource "kubernetes_deployment" “app” {
…..….
spec {
  replicas = 20       -> only this has to reflect in apply
  template {
    spec {
     ….
      env {
        name  = “ENDPOINT”
        value = “abc”
    }
}

How can i fetch particular field(replicas) to compare if replicas count > 20 and update only replicas count?

Can someone with more Terraform experience help me on this?

-- Prakash26790
kubernetes
kubernetes-pod
terraform
terraform-provider-aws

1 Answer

2/3/2021

Inside the "kubernetes_deployment" resource block, consider adding a lifecycle block. Use it to ignore changes to resource attributes that can be made outside of Terraform's knowledge.

Provide a list of resource attributes to "ignore_changes", which Terrform would ignore in subsequent runs. The arguments are the relative address of the attributes in the resource. Map and list elements can be referenced using index notation.

lifecycle {
    ignore_changes = [spec["env"]]
  }

Reference: https://www.terraform.io/docs/language/meta-arguments/lifecycle.html#ignore_changes

-- Aditya Kar
Source: StackOverflow