Skip to content

Implementa suporte a campos bool com default value#22

Merged
lukerops merged 24 commits into
mainfrom
feat/implementa-default-value-boolean
Aug 25, 2025
Merged

Implementa suporte a campos bool com default value#22
lukerops merged 24 commits into
mainfrom
feat/implementa-default-value-boolean

Conversation

@daltonmatos
Copy link
Copy Markdown
Collaborator

@daltonmatos daltonmatos commented Oct 15, 2024

Implementa suporte a default values para camposs boolean.

ref: #16

Tarefas

  • Adicionar validação para confirmar que o valor que foi escolhido como default é compatível com o tipo do campo. Exemplo: Não podemos fazer default: 42 para um campo type: bool
  • Confirmar se vamos validar a possibilidade de passarmos default: null para um campo type: bool

@daltonmatos daltonmatos requested a review from lukerops October 15, 2024 20:53
output "schema" {
value = {
type = "object"
version = "v1"
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Porque você está adicionando versões diferentes para o object se apenas a lógica do bool será alterada nesse PR? Você fez isso para os outros tipos também.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O que observei foi o seguinte:

A implementação do object/v0 não permite que um campo não exista no var.manifest que está chegando, pois ele faz esse check com o local.missing_properties. Já o object/v1 é mais frouxo nessa validação e permite que alguns campos não existam no manifest, pois sabe que alguins deles terão seus valores preenchidos com um valor padão.
Depois que tivermos todos os tipos de campos podendo ter default values, as duas implementações voltarão a ser iguals e poderemos unificar novamente. Acho inclusive que poderemos remover completamente a lógica do local.missing_properties.

Comment thread CustomResourceDefinition/v1alpha2/bool/main.tf
@daltonmatos daltonmatos marked this pull request as ready for review October 28, 2024 13:24
@daltonmatos daltonmatos requested a review from lukerops October 29, 2024 11:38
Comment thread CustomResourceDefinition/v1alpha2/bool/main.tf
Comment on lines +18 to +20
condition = !(
local.declared_default_field && try(var.manifest.default, null) == null
)
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aqui não deveria ser tem declaração do default e o default for diferente de null ou não tem declaração do default (condition = (local.declared_default_field && try(var.manifest.default, null) != null) || !local.declared_default_field ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Se colocarmos essa validação (a parte final depois do ||), quando o campo default não for declarado teremos um erro, certo?

Se de fato isso acontecer estaremos tornando a presença do campo default obrigatória, mas declarar ou não um valor default para um campo deveria ser opcional.

A ideia da validação como ela está agora é: "Se um valor default tiver sido declarado, ele não pode ser ``"null".
Faz sentido?

(Posso tentar escrever um teste pra confirmar esse meu pensamento depois)

Outro ponto: Se tirarmos a parte final do "or" nossas expressões são equivalente (eu acho). O que eu geralmente faço, pois acho mais simples de entender, é colocar entre parentes a condição que não podemos ter, e depois faço a negação disso. A negação existe pois o teste falha quando a condition é false e não true.

Comment thread schemaValidation/bool/v1/main.tf Outdated
Comment thread schemaValidation/bool/v1/main.tf Outdated
Comment on lines +28 to +31
#condition = local.has_default_value || var.manifest != null
condition = !(
!local.has_default_value && var.manifest == null
)
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Faltou remover o comentário.
Aqui não deveria ser tem o default ou não tem default e o manifest é diferente de null (condition = local.has_default_value || (!local.has_default_value && var.manifest != null)`)?

Copy link
Copy Markdown
Collaborator Author

@daltonmatos daltonmatos Aug 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feito. 4eab358

Sobre a condição, elas são equivalentes, apenas uma está negada e outra não. O que faço aqui é, ter entre parenteses, a condição que representa o erro e depois eu faço a negação de tudo. Faço isso para que fique mais claro a condição que não queremos ter, e a negação final existe pela forma como o teste terraform funciona (quebrando quando a condition é false).

subItem = null
validations = {
has_default_value = can(var.manifest.default) ? true : false
default_value = try(var.manifest.default, null)
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O schema deveria carregar o campo já em seu valor final. Com isso em mente, a validação se o campo default possui um valor válido, deveria estar aqui.

Suggested change
default_value = try(var.manifest.default, null)
default_value = try(tobool(var.manifest.default), null)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread schemaValidation/bool/v1/main.tf Outdated
Comment on lines +48 to +56
precondition {
condition = local.has_compatible_default_value
error_message = <<-EOT
Invalid resource manifest!
The default value of the property "${var.field_path}" must be compatible with type bool.
Current default value: ${format("%v", var.schema.validations.default_value)}
(metadata.name: "${var.metadata_name}"; path: "${var.path}")
EOT
}
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Essa validação deveria estar no processamento do CRD e não no processamento do manifesto final.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feito. 7e3f2a6

Comment thread schemaValidation/bool/v1/main.tf Outdated
Comment on lines +1 to +11
locals {
has_default_value = var.schema.validations.has_default_value
has_compatible_default_value = can(tobool(var.schema.validations.default_value))

default_value = local.has_compatible_default_value ? tobool(var.schema.validations.default_value) : false

has_valid_value = var.manifest != null && can(tobool(var.manifest))
final_default_value = local.has_compatible_default_value ? local.default_value : try(tobool(var.manifest), null)


}
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Se o schema vier com o campo default já validado e transformado em seu valor final, essa lógica inteira se faz desnecessária, ficando bem mais simples de saber o valor final.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feito. 7e3f2a6

@daltonmatos daltonmatos requested a review from lukerops August 18, 2025 17:32
Copy link
Copy Markdown
Owner

@lukerops lukerops left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Só ajuste da mensagem de erro. Mas de resto, acho que está OK.

Comment on lines +24 to +25
The default value a bool field can't be null;
The filed ${var.field_path} has it's default value set to null.
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
The default value a bool field can't be null;
The filed ${var.field_path} has it's default value set to null.
The default value of a bool field can't be null;
The field "${var.field_path}" has it's default value set to null.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feito. d7a7eff

@daltonmatos daltonmatos requested a review from lukerops August 25, 2025 14:07
@lukerops lukerops merged commit 4330f15 into main Aug 25, 2025
4 checks passed
@lukerops lukerops deleted the feat/implementa-default-value-boolean branch August 25, 2025 18:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants