Terraform-provider-aws: Agregar un atributo de grupo de usuarios cognito personalizado fuerza un nuevo recurso

Creado en 22 mar. 2018  ·  44Comentarios  ·  Fuente: hashicorp/terraform-provider-aws

Agregar nuevos atributos personalizados no debería forzar la recreación del grupo de usuarios cognito.

Versión Terraform

$ terraform -v
Terraform v0.11.4
+ provider.aws v1.11.0

Recursos afectados

aws_cognito_user_pool

Archivos de configuración de Terraform

variable "region" {
  default = "us-east-1"
}

provider "aws" {
  region = "${var.region}"
}

resource "aws_cognito_user_pool" "pool" {
  name = "bug-test-pool"

  /*
  schema {
    attribute_data_type      = "Number"
    developer_only_attribute = false
    mutable                  = false
    name                     = "custom-attribute"
    required                 = false
  }
  */
}

Salida de depuración

Resultado de ejecutar terraform plan después de agregar el atributo personalizado anterior.

Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

aws_cognito_user_pool.pool: Refreshing state... (ID: us-east-1_Cj77gRCdj)

------------------------------------------------------------------------

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

-/+ aws_cognito_user_pool.pool (new resource required)
      id:                                               "us-east-1_Cj77gRCdj" => <computed> (forces new resource)
      admin_create_user_config.#:                       "1" => <computed>
      arn:                                              "arn:aws:cognito-idp:us-east-1:326947223243:userpool/us-east-1_Cj77gRCdj" => <computed>
      creation_date:                                    "2018-03-22T19:06:44Z" => <computed>
      email_verification_message:                       "" => <computed>
      email_verification_subject:                       "" => <computed>
      lambda_config.#:                                  "0" => <computed>
      last_modified_date:                               "2018-03-22T19:06:44Z" => <computed>
      mfa_configuration:                                "OFF" => "OFF"
      name:                                             "bug-test-pool" => "bug-test-pool"
      password_policy.#:                                "1" => <computed>
      schema.#:                                         "" => "1" (forces new resource)
      schema.2616754751.attribute_data_type:            "" => "Number"
      schema.2616754751.developer_only_attribute:       "" => "false"
      schema.2616754751.mutable:                        "" => "false"
      schema.2616754751.name:                           "" => "custom-attribute"
      schema.2616754751.number_attribute_constraints.#: "" => "0"
      schema.2616754751.required:                       "" => "false"
      schema.2616754751.string_attribute_constraints.#: "" => "0"
      verification_message_template.#:                  "1" => <computed>


Plan: 1 to add, 0 to change, 1 to destroy.

------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

Salida de pánico

Ninguna

Comportamiento esperado

Agregue el atributo sin destruir ni reconstruir el grupo de usuarios cognito. Esto es compatible a través de la interfaz de usuario y la API de cognito (https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AddCustomAttributes.html).

Comportamiento real

Se reconstruyó el grupo de usuarios de cognito.

schema.#: "" => "1" (forces new resource)

Pasos para reproducir

  1. terraform apply - Crear nuevo grupo de usuarios
  2. Agregar un nuevo atributo personalizado
  3. terrform plan : ver la salida muestra que reconstruiría el grupo de usuarios de cognito.

Factoides importantes

Ninguna

Referencias

Ninguna

enhancement serviccognito

Comentario más útil

¿Algún progreso en esto? Ustedes nos están obligando a destruir un recurso que implica pedirle al cliente que restablezca sus contraseñas (asumiendo que incluso tenemos datos de respaldo para importar en primer lugar), o para mí, configuro un ciclo de vida ignore_changes * y espero que alguien finalmente se mueva para arreglar esto antes de que necesite otro cambio.

El hecho de que esto haya estado ahí durante 9 meses me hace preguntarme seriamente si debería confiar en la infraestructura crítica a Terraform.

Todos 44 comentarios

No estoy seguro de cómo funciona la eliminación de atributos personalizados, ya que AWS no parece admitir la eliminación de atributos personalizados o la actualización de atributos personalizados.

Como se sospecha, uno no puede actualizar o eliminar atributos personalizados una vez creados como parte de user_pool. Entonces, creo que el comportamiento actual es la única salida 🤔 Más detalles en la documentación de AWS

Correcto, una vez que se agregan los atributos, no se pueden eliminar. Sin embargo, puede agregar nuevos atributos.

¿Existe una solución alternativa para agregar nuevos atributos a través de terraform sin tener que volver a crear todo el grupo de usuarios? Parece que será complicado agregar un nuevo atributo en el futuro cuando la aplicación esté activa.

Editar: Parece que vincular la versión a 1.12 solucionó esto para nosotros.

Mientras tanto, puede hacerlo fuera de Terraform (consola web, CLI, etc.) y luego sincronizar su configuración de Terraform.

Investigando un poco más. Encontré el problema. Si el atributo de esquema (en mi caso, String) no incluye string_attribute_constraints , forzará un nuevo recurso cada vez.

Lo siguiente genera un nuevo recurso cada vez:

schema {
    attribute_data_type      = "String"
    developer_only_attribute = false
    mutable                  = false
    name                     = "picture"
    required                 = true
  }

Si bien esto no lo hace:

schema {
    attribute_data_type      = "String"
    developer_only_attribute = false
    mutable                  = false
    name                     = "picture"
    required                 = true

    string_attribute_constraints {
      min_length = 6
      max_length = 32
    }
  }

Lo más probable es que sea un error diferente.

@leonfs Creo que necesitamos una función personalizada aquí. que evalúa thwbrules para saber cuándo se debe volver a crear el grupo y cuándo se debe modificar. @bflad ¿Puede por favor confirmar lo que se debe hacer y puedo retomar esto?

@ Puneeth-n Sí, parece que ese será el caso. Por el momento, hay un ForceNew: true en el conjunto de esquemas, pero claramente ese no es el caso con los atributos personalizados.

He mencionado (ver arriba) otro problema que encontré después de agregar un proveedor de identidad (Google) al grupo de usuarios.

Parece que AWS agrega un atributo personalizado llamado identities después de agregar un proveedor, lo que hace que el esquema cambie y obliga a que se vuelva a crear un grupo completamente nuevo. Puede ver que le proporcioné una solución a corto plazo, pero solo funciona si sabe de antemano (creación de recursos) que utilizará proveedores de identidad.

Parece que terraform fuerza la destrucción y la creación de un grupo de usuarios incluso si nada cambia en el archivo .tf.

$ cat main.tf

provider "aws" {
}

resource "aws_cognito_user_pool" "pankajk_security" {
  name                       = "pankajk-security"
  email_verification_subject = "Your Verification Code"
  email_verification_message = "Please use the following code: {####}"
  alias_attributes           = ["email", "preferred_username"]
  auto_verified_attributes   = ["email"]

  verification_message_template {
    default_email_option = "CONFIRM_WITH_CODE"
  }

  password_policy {
    minimum_length    = 10
    require_lowercase = true
    require_numbers   = true
    require_symbols   = true
    require_uppercase = true
  }

  schema {
    attribute_data_type      = "String"
    developer_only_attribute = false
    mutable                  = true
    name                     = "email"
    required                 = true

    string_attribute_constraints {
      min_length = 7
      max_length = 256
    }
  }

  schema {
    attribute_data_type      = "String"
    developer_only_attribute = false
    mutable                  = true
    name                     = "oid"
    required                 = false

    number_attribute_constraints {
      min_value = 1
      max_value = 256
    }
  }
}

$ terraform -v

Terraform v0.11.7
+ provider.aws v1.14.1

$ terraform aplicar

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  + aws_cognito_user_pool.pankajk_security
      id:                                                          <computed>
      admin_create_user_config.#:                                  <computed>
      alias_attributes.#:                                          "2"
      alias_attributes.1888159429:                                 "preferred_username"
      alias_attributes.881205744:                                  "email"
      arn:                                                         <computed>
      auto_verified_attributes.#:                                  "1"
      auto_verified_attributes.881205744:                          "email"
      creation_date:                                               <computed>
      email_verification_message:                                  "Please use the following code: {####}"
      email_verification_subject:                                  "Your Verification Code"
      lambda_config.#:                                             <computed>
      last_modified_date:                                          <computed>
      mfa_configuration:                                           "OFF"
      name:                                                        "pankajk-security"
      password_policy.#:                                           "1"
      password_policy.0.minimum_length:                            "10"
      password_policy.0.require_lowercase:                         "true"
      password_policy.0.require_numbers:                           "true"
      password_policy.0.require_symbols:                           "true"
      password_policy.0.require_uppercase:                         "true"
      schema.#:                                                    "2"
      schema.1734507539.attribute_data_type:                       "String"
      schema.1734507539.developer_only_attribute:                  "false"
      schema.1734507539.mutable:                                   "true"
      schema.1734507539.name:                                      "email"
      schema.1734507539.number_attribute_constraints.#:            "0"
      schema.1734507539.required:                                  "true"
      schema.1734507539.string_attribute_constraints.#:            "1"
      schema.1734507539.string_attribute_constraints.0.max_length: "256"
      schema.1734507539.string_attribute_constraints.0.min_length: "7"
      schema.3768180960.attribute_data_type:                       "String"
      schema.3768180960.developer_only_attribute:                  "false"
      schema.3768180960.mutable:                                   "true"
      schema.3768180960.name:                                      "oid"
      schema.3768180960.number_attribute_constraints.#:            "1"
      schema.3768180960.number_attribute_constraints.0.max_value:  "256"
      schema.3768180960.number_attribute_constraints.0.min_value:  "1"
      schema.3768180960.required:                                  "false"
      schema.3768180960.string_attribute_constraints.#:            "0"
      verification_message_template.#:                             "1"
      verification_message_template.0.default_email_option:        "CONFIRM_WITH_CODE"
      verification_message_template.0.email_message:               <computed>
      verification_message_template.0.email_message_by_link:       <computed>
      verification_message_template.0.email_subject:               <computed>
      verification_message_template.0.email_subject_by_link:       <computed>
      verification_message_template.0.sms_message:                 <computed>


Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_cognito_user_pool.pankajk_security: Creating...
  admin_create_user_config.#:                                  "" => "<computed>"
  alias_attributes.#:                                          "" => "2"
  alias_attributes.1888159429:                                 "" => "preferred_username"
  alias_attributes.881205744:                                  "" => "email"
  arn:                                                         "" => "<computed>"
  auto_verified_attributes.#:                                  "" => "1"
  auto_verified_attributes.881205744:                          "" => "email"
  creation_date:                                               "" => "<computed>"
  email_verification_message:                                  "" => "Please use the following code: {####}"
  email_verification_subject:                                  "" => "Your Verification Code"
  lambda_config.#:                                             "" => "<computed>"
  last_modified_date:                                          "" => "<computed>"
  mfa_configuration:                                           "" => "OFF"
  name:                                                        "" => "pankajk-security"
  password_policy.#:                                           "" => "1"
  password_policy.0.minimum_length:                            "" => "10"
  password_policy.0.require_lowercase:                         "" => "true"
  password_policy.0.require_numbers:                           "" => "true"
  password_policy.0.require_symbols:                           "" => "true"
  password_policy.0.require_uppercase:                         "" => "true"
  schema.#:                                                    "" => "2"
  schema.1734507539.attribute_data_type:                       "" => "String"
  schema.1734507539.developer_only_attribute:                  "" => "false"
  schema.1734507539.mutable:                                   "" => "true"
  schema.1734507539.name:                                      "" => "email"
  schema.1734507539.number_attribute_constraints.#:            "" => "0"
  schema.1734507539.required:                                  "" => "true"
  schema.1734507539.string_attribute_constraints.#:            "" => "1"
  schema.1734507539.string_attribute_constraints.0.max_length: "" => "256"
  schema.1734507539.string_attribute_constraints.0.min_length: "" => "7"
  schema.3768180960.attribute_data_type:                       "" => "String"
  schema.3768180960.developer_only_attribute:                  "" => "false"
  schema.3768180960.mutable:                                   "" => "true"
  schema.3768180960.name:                                      "" => "oid"
  schema.3768180960.number_attribute_constraints.#:            "" => "1"
  schema.3768180960.number_attribute_constraints.0.max_value:  "" => "256"
  schema.3768180960.number_attribute_constraints.0.min_value:  "" => "1"
  schema.3768180960.required:                                  "" => "false"
  schema.3768180960.string_attribute_constraints.#:            "" => "0"
  verification_message_template.#:                             "" => "1"
  verification_message_template.0.default_email_option:        "" => "CONFIRM_WITH_CODE"
  verification_message_template.0.email_message:               "" => "<computed>"
  verification_message_template.0.email_message_by_link:       "" => "<computed>"
  verification_message_template.0.email_subject:               "" => "<computed>"
  verification_message_template.0.email_subject_by_link:       "" => "<computed>"
  verification_message_template.0.sms_message:                 "" => "<computed>"
aws_cognito_user_pool.pankajk_security: Creation complete after 3s (ID: us-west-2_t6jMrbPx1)

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

$ plan terraform

Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

aws_cognito_user_pool.pankajk_security: Refreshing state... (ID: us-west-2_t6jMrbPx1)

------------------------------------------------------------------------

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

-/+ aws_cognito_user_pool.pankajk_security (new resource required)
      id:                                                          "us-west-2_t6jMrbPx1" => <computed> (forces new resource)
      admin_create_user_config.#:                                  "1" => <computed>
      alias_attributes.#:                                          "2" => "2"
      alias_attributes.1888159429:                                 "preferred_username" => "preferred_username"
      alias_attributes.881205744:                                  "email" => "email"
      arn:                                                         "arn:aws:cognito-idp:us-west-2:166326852216:userpool/us-west-2_t6jMrbPx1" => <computed>
      auto_verified_attributes.#:                                  "1" => "1"
      auto_verified_attributes.881205744:                          "email" => "email"
      creation_date:                                               "2018-04-18T18:11:08Z" => <computed>
      email_verification_message:                                  "Please use the following code: {####}" => "Please use the following code: {####}"
      email_verification_subject:                                  "Your Verification Code" => "Your Verification Code"
      lambda_config.#:                                             "0" => <computed>
      last_modified_date:                                          "2018-04-18T18:11:08Z" => <computed>
      mfa_configuration:                                           "OFF" => "OFF"
      name:                                                        "pankajk-security" => "pankajk-security"
      password_policy.#:                                           "1" => "1"
      password_policy.0.minimum_length:                            "10" => "10"
      password_policy.0.require_lowercase:                         "true" => "true"
      password_policy.0.require_numbers:                           "true" => "true"
      password_policy.0.require_symbols:                           "true" => "true"
      password_policy.0.require_uppercase:                         "true" => "true"
      schema.#:                                                    "2" => "2"
      schema.1734507539.attribute_data_type:                       "String" => "String"
      schema.1734507539.developer_only_attribute:                  "false" => "false"
      schema.1734507539.mutable:                                   "true" => "true"
      schema.1734507539.name:                                      "email" => "email"
      schema.1734507539.number_attribute_constraints.#:            "0" => "0"
      schema.1734507539.required:                                  "true" => "true"
      schema.1734507539.string_attribute_constraints.#:            "1" => "1"
      schema.1734507539.string_attribute_constraints.0.max_length: "256" => "256"
      schema.1734507539.string_attribute_constraints.0.min_length: "7" => "7"
      schema.3768180960.attribute_data_type:                       "" => "String" (forces new resource)
      schema.3768180960.developer_only_attribute:                  "" => "false" (forces new resource)
      schema.3768180960.mutable:                                   "" => "true" (forces new resource)
      schema.3768180960.name:                                      "" => "oid" (forces new resource)
      schema.3768180960.number_attribute_constraints.#:            "" => "1" (forces new resource)
      schema.3768180960.number_attribute_constraints.0.max_value:  "" => "256" (forces new resource)
      schema.3768180960.number_attribute_constraints.0.min_value:  "" => "1" (forces new resource)
      schema.3768180960.required:                                  "" => "false" (forces new resource)
      schema.3768180960.string_attribute_constraints.#:            "" => "0"
      schema.383977790.attribute_data_type:                        "String" => "" (forces new resource)
      schema.383977790.developer_only_attribute:                   "false" => "false"
      schema.383977790.mutable:                                    "true" => "false" (forces new resource)
      schema.383977790.name:                                       "oid" => "" (forces new resource)
      schema.383977790.number_attribute_constraints.#:             "0" => "0"
      schema.383977790.required:                                   "false" => "false"
      schema.383977790.string_attribute_constraints.#:             "1" => "0" (forces new resource)
      schema.383977790.string_attribute_constraints.0.max_length:  "" => ""
      schema.383977790.string_attribute_constraints.0.min_length:  "" => ""
      verification_message_template.#:                             "1" => "1"
      verification_message_template.0.default_email_option:        "CONFIRM_WITH_CODE" => "CONFIRM_WITH_CODE"
      verification_message_template.0.email_message:               "Please use the following code: {####}" => <computed>
      verification_message_template.0.email_message_by_link:       "" => <computed>
      verification_message_template.0.email_subject:               "Your Verification Code" => <computed>
      verification_message_template.0.email_subject_by_link:       "" => <computed>
      verification_message_template.0.sms_message:                 "" => <computed>


Plan: 1 to add, 0 to change, 1 to destroy.

------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

@pankajku El problema al que se enfrenta es diferente. Sin embargo, en mi humilde opinión terraform debería poder detectar tales errores.

Hay un error en su configuración. Para oid , especifica attribute_data_type = "String" pero especifica number_attribute_constraints La configuración corregida se muestra a continuación:

variable "region" {
  default = "us-east-1"
}

provider "aws" {
  version               = "1.14.1"
  region                = "${var.region}"
}

resource "aws_cognito_user_pool" "pankajk_security" {
  name                       = "pankajk-security"
  email_verification_subject = "Your Verification Code"
  email_verification_message = "Please use the following code: {####}"
  alias_attributes           = ["email", "preferred_username"]
  auto_verified_attributes   = ["email"]

  verification_message_template {
    default_email_option = "CONFIRM_WITH_CODE"
  }

  password_policy {
    minimum_length    = 10
    require_lowercase = true
    require_numbers   = true
    require_symbols   = true
    require_uppercase = true
  }

  schema {
    attribute_data_type      = "String"
    developer_only_attribute = false
    mutable                  = true
    name                     = "email"
    required                 = true

    string_attribute_constraints {
      min_length = 7
      max_length = 256
    }
  }

  schema {
    attribute_data_type      = "String"
    developer_only_attribute = false
    mutable                  = true
    name                     = "oid"
    required                 = false

    string_attribute_constraints {
      min_length = 1
      max_length = 256
    }
  }
}

@ Puneeth-n, Gracias por detectar el problema en mi configuración. Lo cambié según su sugerencia y ahora terraform actualiza solo los atributos modificados.

Me di cuenta de que después de hacer un cambio simple (como el texto del mensaje de verificación) en el archivo de configuración y ejecutar "terraform apply", la marca de verificación de correo electrónico se desarma.

$ terraform aplicar

aws_cognito_user_pool.pankajk_security: Refreshing state... (ID: us-west-2_LKVhvfWsH)

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  ~ update in-place

Terraform will perform the following actions:

  ~ aws_cognito_user_pool.pankajk_security
      email_verification_subject: "Your verification code" => "Your Verification Code"


Plan: 0 to add, 1 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_cognito_user_pool.pankajk_security: Modifying... (ID: us-west-2_LKVhvfWsH)
  email_verification_subject: "Your verification code" => "Your Verification Code"
aws_cognito_user_pool.pankajk_security: Modifications complete after 1s (ID: us-west-2_LKVhvfWsH)

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

$ plan terraform

Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

aws_cognito_user_pool.pankajk_security: Refreshing state... (ID: us-west-2_LKVhvfWsH)

------------------------------------------------------------------------

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  ~ update in-place

Terraform will perform the following actions:

  ~ aws_cognito_user_pool.pankajk_security
      auto_verified_attributes.#:         "0" => "1"
      auto_verified_attributes.881205744: "" => "email"


Plan: 0 to add, 1 to change, 0 to destroy.

------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

Me pregunto si esto también se debe a algún error en el archivo de configuración o un error.

Esto todavía parece ser un problema y va a causar muchos dolores de cabeza a alguien un día cuando tf abandone el grupo de usuarios y pierda a todos sus usuarios ...

Agregar esto al esquema hace que se destruya el grupo de usuarios, a pesar de poder crearse en la consola / cli sin destruir.

    {
      name                     = "foo"
      attribute_data_type      = "String"
      mutable                  = true
      developer_only_attribute = "false"
      required                 = "false"

      string_attribute_constraints = {
        min_length = 0
        max_length = 256
      }
    },

Sí. Tengo prevent_destroy configurados tanto en pool como en client

Sigo teniendo problemas con la recreación de recursos cuando intento agregar nuevos atributos personalizados.

Versión Terraform
Terraform v0.11.8
provider.aws v1.36.0

Antes de agregar un nuevo atributo personalizado

resource "aws_cognito_user_pool" "pool" {
  name                       = "Test"
  username_attributes        = ["email"]
  auto_verified_attributes   = ["email"]

  schema = [
    {
      attribute_data_type          = "String"
      developer_only_attribute     = false
      mutable                      = false
      name                         = "email"
      required                     = true
      string_attribute_constraints = {
        min_length = 1
        max_length = 256
      }
    },
    {
      attribute_data_type          = "String"
      developer_only_attribute     = false
      mutable                      = true
      name                         = "custom1"
      required                     = false
      string_attribute_constraints = {
        min_length = 0
        max_length = 256
      }
    }
  ]
}

Agregar nuevo atributo personalizado

{
      attribute_data_type          = "String"
      developer_only_attribute     = false
      mutable                      = true
      name                         = "custom2"
      required                     = false
      string_attribute_constraints = {
        min_length = 0
        max_length = 256
      }
    }

Depurar salida

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

-/+ aws_cognito_user_pool.pool (new resource required)
 ...
      lambda_config.#:                                             "0" => <computed>
      last_modified_date:                                          "2018-09-19T03:33:52Z" => <computed>
      mfa_configuration:                                           "OFF" => "OFF"
      name:                                                        "Test" => "Test"
      password_policy.#:                                           "1" => <computed>
      schema.#:                                                    "2" => "3" (forces new resource)
      schema.2766842814.attribute_data_type:                       "" => "String" (forces new resource)
      schema.2766842814.developer_only_attribute:                  "" => "false" (forces new resource)
      schema.2766842814.mutable:                                   "" => "true" (forces new resource)
      schema.2766842814.name:                                      "" => "custom2" (forces new resource)
      schema.2766842814.number_attribute_constraints.#:            "" => "0"
      schema.2766842814.required:                                  "" => "false" (forces new resource)
      schema.2766842814.string_attribute_constraints.#:            "" => "1" (forces new resource)
      schema.2766842814.string_attribute_constraints.0.max_length: "" => "256" (forces new resource)
      schema.2766842814.string_attribute_constraints.0.min_length: "" => "0" (forces new resource)
      schema.3686385984.attribute_data_type:                       "String" => "String"
      schema.3686385984.developer_only_attribute:                  "false" => "false"
      schema.3686385984.mutable:                                   "false" => "false"
      schema.3686385984.name:                                      "email" => "email"
      schema.3686385984.number_attribute_constraints.#:            "0" => "0"
      schema.3686385984.required:                                  "true" => "true"
      schema.3686385984.string_attribute_constraints.#:            "1" => "1"
      schema.3686385984.string_attribute_constraints.0.max_length: "256" => "256"
      schema.3686385984.string_attribute_constraints.0.min_length: "1" => "1"
      schema.893709367.attribute_data_type:                        "String" => "String"
      schema.893709367.developer_only_attribute:                   "false" => "false"
      schema.893709367.mutable:                                    "true" => "true"
      schema.893709367.name:                                       "custom1" => "custom1"
      schema.893709367.number_attribute_constraints.#:             "0" => "0"
      schema.893709367.required:                                   "false" => "false"
      schema.893709367.string_attribute_constraints.#:             "1" => "1"
      schema.893709367.string_attribute_constraints.0.max_length:  "256" => "256"
      schema.893709367.string_attribute_constraints.0.min_length:  "0" => "0"
      username_attributes.#:                                       "1" => "1"
      username_attributes.0:                                       "email" => "email"
      verification_message_template.#:                             "1" => <computed>


Plan: 1 to add, 0 to change, 1 to destroy.

FYI: Hice un atributo personalizado sin string_attribute_constraints , luego enfrenté el mismo error.

  schema {
    name                     = "custom_id"
    required                 = false
    attribute_data_type      = "String"
    developer_only_attribute = false
    mutable                  = true
  }

Después de agregar string_attribute_constraints vacíos, ¡pude evitar este error!

  schema {
    name                     = "custom_id"
    required                 = false
    attribute_data_type      = "String"
    developer_only_attribute = false
    mutable                  = true

    string_attribute_constraints {}
  }

¡Realmente aprecio la solución alternativa de todos!

La solución alternativa no me funciona.

schema {
    attribute_data_type      = "String"
    developer_only_attribute = false
    mutable                  = true
    name                     = "parent_id"
    required                 = false

    string_attribute_constraints {
      min_length = 1
      max_length = 256
    }
  }

Plan:

schema.#:                                                    "10" => "11" (forces new resource)
schema.2272806367.attribute_data_type:                       "" => "String" (forces new resource)
schema.2272806367.developer_only_attribute:                  "" => "false" (forces new resource)
schema.2272806367.mutable:                                   "" => "false" (forces new resource)
schema.2272806367.name:                                      "" => "parent_id" (forces new resource)
schema.2272806367.number_attribute_constraints.#:            "" => "0"
schema.2272806367.required:                                  "" => "false" (forces new resource)
schema.2272806367.string_attribute_constraints.#:            "" => "1" (forces new resource)
schema.2272806367.string_attribute_constraints.0.max_length: "" => "256" (forces new resource)
schema.2272806367.string_attribute_constraints.0.min_length: "" => "1" (forces new resource)

Versiones:

Terraform v0.11.11
+ provider.archive v1.1.0
+ provider.aws v1.52.0

Este es un gran problema para cualquiera que esté desarrollando nuevas aplicaciones y necesite agregar / experimentar con atributos personalizados. Tuvimos nuestra piscina destruida más de 10 veces debido a esto.

¿Algún progreso en esto? Ustedes nos están obligando a destruir un recurso que implica pedirle al cliente que restablezca sus contraseñas (asumiendo que incluso tenemos datos de respaldo para importar en primer lugar), o para mí, configuro un ciclo de vida ignore_changes * y espero que alguien finalmente se mueva para arreglar esto antes de que necesite otro cambio.

El hecho de que esto haya estado ahí durante 9 meses me hace preguntarme seriamente si debería confiar en la infraestructura crítica a Terraform.

La solución alternativa tampoco me funciona. Siempre recrea el grupo incluso si no hay cambios en las plantillas.

> terraform --version
Terraform v0.11.11
+ provider.archive v1.1.0
+ provider.aws v1.54.0

sigue siendo un problema

Terraform v0.11.11
+ provider.aws v1.57.0

Y todavía...

Terraform v0.11.11
+ provider.aws v1.59.0

También me afecta esto, ninguna de las soluciones me ha funcionado.

Terraform v0.11.11
+ provider.aws v1.60.0

El hecho de que esto haya estado ahí durante 9 meses me hace preguntarme seriamente si debería confiar en la infraestructura crítica a Terraform.

Me hago la misma pregunta. Hay muchos errores críticos que no se manejan durante más de un año, algunos, durante más de dos años. Para muchos de estos errores, hay relaciones públicas listas que también permanecen sin aterrizar durante más de un año.

También recientemente llené un informe de error para una función seria pero en jsonencode: se negaron a fiz. La respuesta fue: está arreglado en la versión 12, que se lanzará en algún momento desconocido en el futuro y no nos importa la versión 11.

Por cierto, el problema de este tema no es el único que tiene el grupo de usuarios de cognito. Callback_urls debe ordenarse exactamente como AWS hace esto, de lo contrario terraform constantemente tratando de cambiar el orden.

@voroniys Mi

Sigue siendo un problema.

He estado investigando esto y encontrando una manera de "arreglarlo".

Una mejor manera de permitir la administración de atributos personalizados es convertir un atributo personalizado en un recurso separado, por ejemplo, aws_cognito_user_pool_schema_custom_attribute .

En Terraform, un recurso se define mediante un esquema, junto con las devoluciones de llamada de las funciones Crear, Leer, Actualizar y Eliminar. Core Terraform calcula la diferencia entre el estado actual y lo que definió en su código de Terraform. Queremos confiar tanto como sea posible en que TF haga lo correcto.

Si elimina el atributo de esquema como un recurso separado, uno tiene un control más detallado sobre el cálculo de la diferencia: agregar un nuevo recurso de atributo de esquema personalizado hace que Terraform invoque la función Crear del recurso separado, en lugar de la secuencia Destruir / Crear del piscina. En la función Crear del recurso de atributo de esquema, podemos invocar la llamada a la API de AWS Cognito AddCustomAttributes .

Un cambio en las propiedades del atributo de esquema también podría manejarse de manera más granular, pero eso debe ser probado.

Cuando borra (accidentalmente) su recurso de atributo de esquema personalizado de su código Terraform, TF invocaría la función Eliminar del recurso de atributo. Podríamos producir un error al indicar que no se admite la eliminación y que es necesario restaurar su código TF.

Comentarios

@bflad , ¿sabes quién podría ayudar a diseñar los cambios?

Gracias @ringods por tu trabajo y sugerencia. ¡Este podría ser el camino correcto para abordar este problema!

Aún validando el problema mientras usa las últimas versiones a día de hoy:

Terraform v0.12.3
+ provider.aws v2.18.0 

Resumen rápido:

resource "aws_cognito_user_pool" "pool" {
  name = "mypooltest2"
  }

Luego agregue cualquier atributo:

resource "aws_cognito_user_pool" "pool" {
  name = "mypooltest2"

  schema {
  attribute_data_type = "String"
  name = "email" 
  required = true
  }
}

En lugar de simplemente hacer la actualización incremental como debería hacer, Terraform destruye y luego agrega el recurso nuevamente:

Plan: 1 to add, 0 to change, 1 to destroy.

Estamos atascados para implementar una nueva función en nuestro entorno de producción, necesitamos un nuevo atributo personalizado, si lo agregamos a través de cli, estropeará toda la configuración de terraform, que también tiene muchos otros recursos.

La sugerencia de @ringods podría funcionar para nosotros, sin interrumpir la configuración de tf existente. de ahí que trate de contribuir a esa solución.
Aquí está el primer borrador de mi código. Pude probarlo con éxito apuntando a terraform-provider-aws construido localmente. Ahora estoy escribiendo las pruebas de aceptación. ¡Se agradecen las sugerencias / comentarios sobre las relaciones públicas!

Agregamos atributos a cognito sin perder nuestro grupo de usuarios de la siguiente manera:

  1. Use CLI para agregar atributos al esquema existente: aws cognito-idp --region ... add-custom-attributes --user-pool-id ... --custom-attributes Name=...,AttributeDataType=Boolean,DeveloperOnlyAttribute=false, Mutable=true,Required=false
  2. Elimine el estado actual de cognito para importar el recurso actualizado. terraform state rm aws_cognito_user_pool.main
  3. Importar recurso actualizado. terraform import aws_cognito_user_pool.main ...

En nuestro caso, nuestro recurso, estado y archivo main.tf ahora coinciden. Sugiero probar primero un dev env, espero que ayude.

¡Por favor arregle esto! Hacer el trabajo de ePoromaa es ridículo para tener que administrar el estado manualmente.

¿Todavía hay algún progreso en esto? Estamos esperando ansiosamente una solución que no requiera manipulaciones manuales en el estado de terraform. :-)

ping también. Administrar manualmente el estado es ... ridículo

Chicos, ¿alguna actualización? Estamos en 2020 ahora ...

Sí, sigue siendo un problema ...

Espero que esto ayude a todos los demás, de una manera más fácil que la solución anterior y potencialmente menos complicada que jugar con el estado de terraformación y las importaciones.

De manera similar a ePoromaa, deberá ejecutar el cmd aws cli manualmente para agregar un atributo personalizado al grupo de usuarios cognito.
aws cognito-idp add-custom-attributes --user-pool-id us-west-2_aaaaaaaaa --custom-attributes Name="CustomAttr1",AttributeDataType="String",DeveloperOnlyAttribute=false,Required=false,StringAttributeConstraints="{MinLength=1,MaxLength=15}"
Se puede encontrar más información sobre los atributos disponibles: https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/add-custom-attributes.html

Una vez que haya agregado el atributo personalizado a través de aws cli, ahora deberá agregar el bloque de esquema en su código de grupo de usuarios de terraform cognito. Por ejemplo

schema { name = "CustomAttr1" attribute_data_type = "String" required = false developer_only_attribute = false string_attribute_constraints { min_length = 1 max_length = 15 } }

Una vez que el bloque de esquema se agrega a terraform, terraform no detecta cambios. También consideraría seguro hacerlo en producción.

Terraform v0.12.26

  • provider.aws v2.56.0

Todavía tengo el problema ...

Hola a todos, ¿alguna actualización aquí?

¡Solucione este problema!

Esto sigue siendo un problema con

Terraform v0.12.28
+ provider.aws v2.67.0

Por favor, diríjase.

Solución alternativa para evitar la destrucción del grupo de usuarios:
1) Agregue un atributo personalizado a través de la consola o cli.
2) Agregue un bloque de esquema a la plantilla de terraform IDÉNTICO EN CUALQUIER MANERA al atributo que acaba de crear.
3) Ejecute terraform refresh. Debería actualizar el archivo de estado para reflejar el esquema.
4) Ejecute el plan terraform para asegurarse de que el grupo de usuarios ya no se destruya.

Hola, también nos enfrentamos a este problema. ¿Alguna actualización? ¡Gracias!

¿Alguien de HashiCorp por ahí? Hola ...

Frente a esto también:

Terraform v0.12.29

Terraform v0.13.3

  • proveedor registro.terraform.io/hashicorp/aws v2.70.0

Aún enfrentando el problema

¡Hola a todos! : wave: Solo quería dirigirlo a nuestra hoja de

Debido al gran interés de la comunidad en resolver este problema, pronto analizaremos la posibilidad de fusionar las contribuciones existentes.

Agradecemos todas las contribuciones y comentarios hasta ahora.

¿Fue útil esta página
0 / 5 - 0 calificaciones