-
Notifications
You must be signed in to change notification settings - Fork 190
fix: Sets default value for WithDefaultAlertsSettings during state import #3105
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
EspenAlbert
wants to merge
14
commits into
master
Choose a base branch
from
CLOUDP-302586_fix_project_no_plan_change_for_with_default_alert_settings
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
53de463
fix: Sets default value for WithDefaultAlertsSettings during state im…
EspenAlbert 26f7353
chore: Adds release note
EspenAlbert 5e67e14
fix: Removes 'with_default_alerts_settings' from ImportStateVerifyIgn…
EspenAlbert 57ddae6
doc: update changelog message
EspenAlbert 7bc763e
doc: Add back reference based on comments
EspenAlbert de2589d
revert changes of old implementation
EspenAlbert 7934ad0
refactor: Introduce Modifier interface and enhance non-updatable attr…
EspenAlbert af84e38
refactor: Mark with_default_alerts_settings as NonUpdateable
EspenAlbert 66e55e9
refactor:Rename NonUpdatableAttributePlanModifier with CreateOnlyAttr…
EspenAlbert e11fc3f
Merge branch 'master' into CLOUDP-302586_fix_project_no_plan_change_f…
EspenAlbert bd76a93
feat: Implement CreateOnlyAttributePlanModifier with default boolean …
EspenAlbert d0cb772
chore: small fix to planModifier using state value when Unknown in th…
EspenAlbert 57f8e64
test: Support testing plan error after importing
EspenAlbert 4ae2ccc
doc: Update error message in addDiags to clarify import restrictions
EspenAlbert File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
```release-note:bug | ||
resource/mongodbatlas_project: Fixes import when `with_default_alerts_settings` is set | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
package customplanmodifier | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
"github.com/hashicorp/terraform-plugin-framework/attr" | ||
"github.com/hashicorp/terraform-plugin-framework/diag" | ||
"github.com/hashicorp/terraform-plugin-framework/path" | ||
planmodifier "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" | ||
"github.com/hashicorp/terraform-plugin-framework/tfsdk" | ||
"github.com/hashicorp/terraform-plugin-framework/types" | ||
) | ||
|
||
type Modifier interface { | ||
planmodifier.String | ||
planmodifier.Bool | ||
} | ||
|
||
// CreateOnlyAttributePlanModifier returns a plan modifier that ensures that update operations fails when the attribute is changed. | ||
// This is useful for attributes only supported in create and not in update. | ||
// Never use a schema.Default for create only attributes, instead use WithXXXDefault, the default will lead to plan changes that are not expected after import. | ||
// Implement CopyFromPlan if the attribute is not in the API Response. | ||
func CreateOnlyAttributePlanModifier() Modifier { | ||
return &createOnlyAttributePlanModifier{} | ||
} | ||
|
||
func CreateOnlyAttributePlanModifierWithBoolDefault(b bool) Modifier { | ||
return &createOnlyAttributePlanModifier{defaultBool: &b} | ||
} | ||
|
||
type createOnlyAttributePlanModifier struct { | ||
defaultBool *bool | ||
} | ||
|
||
func (d *createOnlyAttributePlanModifier) Description(ctx context.Context) string { | ||
return d.MarkdownDescription(ctx) | ||
} | ||
|
||
func (d *createOnlyAttributePlanModifier) MarkdownDescription(ctx context.Context) string { | ||
return "Ensures the update operation fails when updating an attribute. If the read after import don't equal the configuration value it will also raise an error." | ||
} | ||
|
||
func isCreate(t *tfsdk.State) bool { | ||
return t.Raw.IsNull() | ||
} | ||
|
||
func (d *createOnlyAttributePlanModifier) UseDefault() bool { | ||
return d.defaultBool != nil | ||
} | ||
|
||
func (d *createOnlyAttributePlanModifier) PlanModifyBool(ctx context.Context, req planmodifier.BoolRequest, resp *planmodifier.BoolResponse) { | ||
if isCreate(&req.State) { | ||
if !IsKnown(req.PlanValue) && d.UseDefault() { | ||
resp.PlanValue = types.BoolPointerValue(d.defaultBool) | ||
} | ||
return | ||
} | ||
if isUpdated(req.StateValue, req.PlanValue) { | ||
d.addDiags(&resp.Diagnostics, req.Path, req.StateValue) | ||
} | ||
if !IsKnown(req.PlanValue) { | ||
resp.PlanValue = req.StateValue | ||
} | ||
} | ||
|
||
func (d *createOnlyAttributePlanModifier) PlanModifyString(ctx context.Context, req planmodifier.StringRequest, resp *planmodifier.StringResponse) { | ||
if isCreate(&req.State) { | ||
return | ||
} | ||
if isUpdated(req.StateValue, req.PlanValue) { | ||
d.addDiags(&resp.Diagnostics, req.Path, req.StateValue) | ||
} | ||
if !IsKnown(req.PlanValue) { | ||
resp.PlanValue = req.StateValue | ||
} | ||
} | ||
|
||
func isUpdated(state, plan attr.Value) bool { | ||
if !IsKnown(plan) { | ||
return false | ||
} | ||
return !state.Equal(plan) | ||
} | ||
|
||
func (d *createOnlyAttributePlanModifier) addDiags(diags *diag.Diagnostics, attrPath path.Path, stateValue attr.Value) { | ||
message := fmt.Sprintf("%s cannot be updated or set after import, remove it from the configuration or use state value.", attrPath) | ||
detail := fmt.Sprintf("The current state value is %s", stateValue) | ||
diags.AddError(message, detail) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
package customplanmodifier | ||
|
||
import "github.com/hashicorp/terraform-plugin-framework/attr" | ||
|
||
// IsKnown returns true if the attribute is known (not null or unknown). Note that !IsKnown is not the same as IsUnknown because null is !IsKnown but not IsUnknown. | ||
func IsKnown(attribute attr.Value) bool { | ||
return !attribute.IsNull() && !attribute.IsUnknown() | ||
} |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,6 +22,7 @@ import ( | |
"github.com/mongodb/terraform-provider-mongodbatlas/internal/common/conversion" | ||
"github.com/mongodb/terraform-provider-mongodbatlas/internal/service/project" | ||
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/acc" | ||
"github.com/mongodb/terraform-provider-mongodbatlas/internal/testutil/mig" | ||
) | ||
|
||
var ( | ||
|
@@ -647,9 +648,20 @@ func TestAccGovProject_withProjectOwner(t *testing.T) { | |
|
||
func TestAccProject_withFalseDefaultSettings(t *testing.T) { | ||
var ( | ||
orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") | ||
projectOwnerID = os.Getenv("MONGODB_ATLAS_PROJECT_OWNER_ID") | ||
projectName = acc.RandomProjectName() | ||
orgID = os.Getenv("MONGODB_ATLAS_ORG_ID") | ||
projectOwnerID = os.Getenv("MONGODB_ATLAS_PROJECT_OWNER_ID") | ||
projectName = acc.RandomProjectName() | ||
importResourceName = resourceName + "2" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This test case is a bit different than usual, I tried to add comments, but let me know if anything is unclear. |
||
alertSettingsFalse = configWithDefaultAlertSettings(orgID, projectName, projectOwnerID, false) | ||
alertSettingsTrue = configWithDefaultAlertSettings(orgID, projectName, projectOwnerID, true) | ||
// To test plan behavior after import it is necessary to use a different resource name, otherwise we get: | ||
// Terraform is already managing a remote object for mongodbatlas_project.test. To import to this address you must first remove the existing object from the state. | ||
// This happens because `ImportStatePersist` uses the previous WorkingDirectory where the state from previous steps are saved | ||
// resource "mongodbatlas_project" "test" --> resource "mongodbatlas_project" "test2" | ||
alertSettingsFalseImport = strings.Replace(alertSettingsFalse, "test", "test2", 1) | ||
// Need BOTH mongodbatlas_project.test and mongodbatlas_project.test2, otherwise we get: | ||
// expected empty plan, but mongodbatlas_project.test has planned action(s): [delete] | ||
alertSettingsAbsent = alertSettingsFalse + strings.Replace(configBasic(orgID, projectName, "", false, nil, nil), "test", "test2", 1) | ||
) | ||
|
||
resource.ParallelTest(t, resource.TestCase{ | ||
|
@@ -658,13 +670,32 @@ func TestAccProject_withFalseDefaultSettings(t *testing.T) { | |
CheckDestroy: acc.CheckDestroyProject, | ||
Steps: []resource.TestStep{ | ||
{ | ||
Config: configWithFalseDefaultSettings(orgID, projectName, projectOwnerID), | ||
Config: alertSettingsFalse, | ||
Check: resource.ComposeAggregateTestCheckFunc( | ||
checkExists(resourceName), | ||
resource.TestCheckResourceAttr(resourceName, "name", projectName), | ||
resource.TestCheckResourceAttr(resourceName, "org_id", orgID), | ||
), | ||
}, | ||
{ | ||
Config: alertSettingsTrue, | ||
ExpectError: regexp.MustCompile("with_default_alerts_settings cannot be updated or set after import, remove it from the configuration or use state value"), | ||
}, | ||
{ | ||
Config: alertSettingsFalseImport, | ||
ResourceName: importResourceName, | ||
ImportStateIdFunc: acc.ImportStateProjectIDFunc(resourceName), | ||
ImportState: true, | ||
ImportStatePersist: true, // save the state to use it in the next plan | ||
}, | ||
{ | ||
Config: alertSettingsFalseImport, // when the value is set after import, the first plan will fail since the value cannot be read from API and the plan modifier will detect the change from null --> false | ||
ExpectError: regexp.MustCompile("with_default_alerts_settings cannot be updated or set after import, remove it from the configuration or use state value"), | ||
}, | ||
{ | ||
Config: alertSettingsAbsent, // removing `with_default_alerts_settings` from the configuration should have no plan changes | ||
ConfigPlanChecks: mig.TestStepConfigPlanChecksEmptyPlan(), | ||
}, | ||
}, | ||
}) | ||
} | ||
|
@@ -688,7 +719,7 @@ func TestAccProject_withUpdatedSettings(t *testing.T) { | |
resource.TestCheckResourceAttr(resourceName, "name", projectName), | ||
resource.TestCheckResourceAttr(resourceName, "org_id", orgID), | ||
resource.TestCheckResourceAttr(resourceName, "project_owner_id", projectOwnerID), | ||
resource.TestCheckResourceAttr(resourceName, "with_default_alerts_settings", "false"), | ||
resource.TestCheckResourceAttr(resourceName, "with_default_alerts_settings", "true"), // uses default value | ||
resource.TestCheckResourceAttr(resourceName, "is_collect_database_specifics_statistics_enabled", "false"), | ||
resource.TestCheckResourceAttr(resourceName, "is_data_explorer_enabled", "false"), | ||
resource.TestCheckResourceAttr(resourceName, "is_extended_storage_sizes_enabled", "false"), | ||
|
@@ -701,7 +732,7 @@ func TestAccProject_withUpdatedSettings(t *testing.T) { | |
Config: acc.ConfigProjectWithSettings(projectName, orgID, projectOwnerID, true), | ||
Check: resource.ComposeAggregateTestCheckFunc( | ||
checkExists(resourceName), | ||
resource.TestCheckResourceAttr(resourceName, "with_default_alerts_settings", "true"), | ||
resource.TestCheckResourceAttr(resourceName, "with_default_alerts_settings", "true"), // uses default value | ||
resource.TestCheckResourceAttr(resourceName, "is_collect_database_specifics_statistics_enabled", "true"), | ||
resource.TestCheckResourceAttr(resourceName, "is_data_explorer_enabled", "true"), | ||
resource.TestCheckResourceAttr(resourceName, "is_extended_storage_sizes_enabled", "true"), | ||
|
@@ -714,7 +745,7 @@ func TestAccProject_withUpdatedSettings(t *testing.T) { | |
Config: acc.ConfigProjectWithSettings(projectName, orgID, projectOwnerID, false), | ||
Check: resource.ComposeAggregateTestCheckFunc( | ||
checkExists(resourceName), | ||
resource.TestCheckResourceAttr(resourceName, "with_default_alerts_settings", "false"), | ||
resource.TestCheckResourceAttr(resourceName, "with_default_alerts_settings", "true"), // uses default value | ||
resource.TestCheckResourceAttr(resourceName, "is_collect_database_specifics_statistics_enabled", "false"), | ||
resource.TestCheckResourceAttr(resourceName, "is_data_explorer_enabled", "false"), | ||
resource.TestCheckResourceAttr(resourceName, "is_extended_storage_sizes_enabled", "false"), | ||
|
@@ -1233,15 +1264,15 @@ func configGovWithOwner(orgID, projectName, projectOwnerID string) string { | |
`, orgID, projectName, projectOwnerID) | ||
} | ||
|
||
func configWithFalseDefaultSettings(orgID, projectName, projectOwnerID string) string { | ||
func configWithDefaultAlertSettings(orgID, projectName, projectOwnerID string, withDefaultAlertsSettings bool) string { | ||
return fmt.Sprintf(` | ||
resource "mongodbatlas_project" "test" { | ||
org_id = %[1]q | ||
name = %[2]q | ||
project_owner_id = %[3]q | ||
with_default_alerts_settings = false | ||
with_default_alerts_settings = %[4]t | ||
} | ||
`, orgID, projectName, projectOwnerID) | ||
`, orgID, projectName, projectOwnerID, withDefaultAlertsSettings) | ||
} | ||
|
||
func configWithLimits(orgID, projectName string, limits []*admin.DataFederationLimit) string { | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we add a comment on what this plan modifier does & why it's needed?