Skip to content

Commit

Permalink
Merge pull request #76 from terraform-providers/maintenance_window
Browse files Browse the repository at this point in the history
Maintenance window rs
  • Loading branch information
PacoDw authored Jan 16, 2020
2 parents 8756d17 + 3632ef5 commit ae2b73f
Show file tree
Hide file tree
Showing 19 changed files with 1,210 additions and 24 deletions.
5 changes: 2 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ go 1.12

require (
github.com/Sectorbob/mlab-ns2 v0.0.0-20171030222938-d3aa0c295a8a
github.com/go-test/deep v1.0.1
github.com/hashicorp/hcl v0.0.0-20180404174102-ef8a98b0bbce // indirect
github.com/hashicorp/terraform v0.12.1
github.com/mongodb/go-client-mongodb-atlas v0.1.2
github.com/mongodb/go-client-mongodb-atlas v0.1.3-0.20200110215223-d0530efb030d
github.com/mwielbut/pointy v1.1.0
github.com/spf13/cast v1.3.0
)

replace github.com/mongodb/go-client-mongodb-atlas v0.1.2 => ../go-client-mongodb-atlas
6 changes: 2 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -265,10 +265,8 @@ github.com/mitchellh/prefixedio v0.0.0-20190213213902-5733675afd51 h1:eD92Am0Qf3
github.com/mitchellh/prefixedio v0.0.0-20190213213902-5733675afd51/go.mod h1:kB1naBgV9ORnkiTVeyJOI1DavaJkG4oNIq0Af6ZVKUo=
github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY=
github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/mongodb/go-client-mongodb-atlas v0.1.2-0.20191219203423-452c38f9f27d h1:ujWegMeDbfZkPH0GxAC/X8UOM39VRMmxGehjOL+fSjQ=
github.com/mongodb/go-client-mongodb-atlas v0.1.2-0.20191219203423-452c38f9f27d/go.mod h1:LS8O0YLkA+sbtOb3fZLF10yY3tJM+1xATXMJ3oU35LU=
github.com/mongodb/go-client-mongodb-atlas v0.1.2 h1:qmUme1TlQBPZupmXMnpD8DxnfGXLVGs3w+0Z17HBiSA=
github.com/mongodb/go-client-mongodb-atlas v0.1.2/go.mod h1:LS8O0YLkA+sbtOb3fZLF10yY3tJM+1xATXMJ3oU35LU=
github.com/mongodb/go-client-mongodb-atlas v0.1.3-0.20200110215223-d0530efb030d h1:M+jxUj2Q20KeXstXElNlbpxg7QVx4ZR1o9vHDS3HEqo=
github.com/mongodb/go-client-mongodb-atlas v0.1.3-0.20200110215223-d0530efb030d/go.mod h1:LS8O0YLkA+sbtOb3fZLF10yY3tJM+1xATXMJ3oU35LU=
github.com/mwielbut/pointy v1.1.0 h1:U5/YEfoIkaGCHv0St3CgjduqXID4FNRoyZgLM1kY9vg=
github.com/mwielbut/pointy v1.1.0/go.mod h1:MvvO+uMFj9T5DMda33HlvogsFBX7pWWKAkFIn4teYwY=
github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo=
Expand Down
1 change: 1 addition & 0 deletions mongodbatlas/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ func Provider() terraform.ResourceProvider {
"mongodbatlas_network_peering": resourceMongoDBAtlasNetworkPeering(),
"mongodbatlas_encryption_at_rest": resourceMongoDBAtlasEncryptionAtRest(),
"mongodbatlas_private_ip_mode": resourceMongoDBAtlasPrivateIPMode(),
"mongodbatlas_maintenance_window": resourceMongoDBAtlasMaintenanceWindow(),
},

ConfigureFunc: providerConfigure,
Expand Down
182 changes: 182 additions & 0 deletions mongodbatlas/resource_mongodbatlas_maintenance_window.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
package mongodbatlas

import (
"context"
"fmt"

"github.com/hashicorp/terraform/helper/schema"
"github.com/mwielbut/pointy"
"github.com/spf13/cast"

matlas "github.com/mongodb/go-client-mongodb-atlas/mongodbatlas"
)

const (
errorMaintenanceCreate = "error creating the MongoDB Atlas Maintenance Window (%s): %s"
errorMaintenanceUpdate = "error updating the MongoDB Atlas Maintenance Window (%s): %s"
errorMaintenanceRead = "error reading the MongoDB Atlas Maintenance Window (%s): %s"
errorMaintenanceDelete = "error deleting the MongoDB Atlas Maintenance Window (%s): %s"
errorMaintenanceDefer = "error deferring the MongoDB Atlas Maintenance Window (%s): %s"
)

func resourceMongoDBAtlasMaintenanceWindow() *schema.Resource {
return &schema.Resource{
Create: resourceMongoDBAtlasMaintenanceWindowCreate,
Read: resourceMongoDBAtlasMaintenanceWindowRead,
Update: resourceMongoDBAtlasMaintenanceWindowUpdate,
Delete: resourceMongoDBAtlasMaintenanceWindowDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"project_id": {
Type: schema.TypeString,
Required: true,
},
"day_of_week": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: func(val interface{}, key string) (warns []string, errs []error) {
v := val.(int)
if v < 1 || v > 7 {
errs = append(errs, fmt.Errorf("%q value should be between 1 and 7, got: %d", key, v))
}
return
},
},
"hour_of_day": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ConflictsWith: []string{"start_asap"},
ValidateFunc: func(val interface{}, key string) (warns []string, errs []error) {
v := val.(int)
if v < 0 || v > 23 {
errs = append(errs, fmt.Errorf("%q value should be between 0 and 23, got: %d", key, v))
}
return
},
},
"start_asap": {
Type: schema.TypeBool,
Computed: true,
},
"number_of_deferrals": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"defer": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
},
}
}

func resourceMongoDBAtlasMaintenanceWindowCreate(d *schema.ResourceData, meta interface{}) error {
//Get the client connection.
conn := meta.(*matlas.Client)

projectID := d.Get("project_id").(string)

if deferValue := d.Get("defer").(bool); deferValue {
_, err := conn.MaintenanceWindows.Defer(context.Background(), projectID)
if err != nil {
return fmt.Errorf(errorMaintenanceDefer, projectID, err)
}
}

maintenanceWindowReq := &matlas.MaintenanceWindow{}
if dayOfWeek, ok := d.GetOk("day_of_week"); ok {
maintenanceWindowReq.DayOfWeek = cast.ToInt(dayOfWeek)
}
if hourOfDay, ok := d.GetOkExists("hour_of_day"); ok {
maintenanceWindowReq.HourOfDay = pointy.Int(cast.ToInt(hourOfDay))
}
if numberOfDeferrals, ok := d.GetOk("number_of_deferrals"); ok {
maintenanceWindowReq.NumberOfDeferrals = cast.ToInt(numberOfDeferrals)
}

_, err := conn.MaintenanceWindows.Update(context.Background(), projectID, maintenanceWindowReq)
if err != nil {
return fmt.Errorf(errorMaintenanceCreate, projectID, err)
}

d.SetId(projectID)

return resourceMongoDBAtlasMaintenanceWindowRead(d, meta)
}

func resourceMongoDBAtlasMaintenanceWindowRead(d *schema.ResourceData, meta interface{}) error {
//Get the client connection.
conn := meta.(*matlas.Client)

maintenanceWindow, _, err := conn.MaintenanceWindows.Get(context.Background(), d.Id())
if err != nil {
return fmt.Errorf(errorMaintenanceRead, d.Id(), err)
}

if err := d.Set("day_of_week", maintenanceWindow.DayOfWeek); err != nil {
return fmt.Errorf(errorMaintenanceRead, d.Id(), err)
}
if err := d.Set("hour_of_day", maintenanceWindow.HourOfDay); err != nil {
return fmt.Errorf(errorMaintenanceRead, d.Id(), err)
}
if err := d.Set("number_of_deferrals", maintenanceWindow.NumberOfDeferrals); err != nil {
return fmt.Errorf(errorMaintenanceRead, d.Id(), err)
}
// start_asap is just display the state of the maintenance,
// and it doesn't able to set it because breacks the Terraform flow
// it can be used via API
if err := d.Set("start_asap", maintenanceWindow.StartASAP); err != nil {
return fmt.Errorf(errorMaintenanceRead, d.Id(), err)
}

return nil
}

func resourceMongoDBAtlasMaintenanceWindowUpdate(d *schema.ResourceData, meta interface{}) error {
//Get the client connection.
conn := meta.(*matlas.Client)

maintenanceWindowReq := &matlas.MaintenanceWindow{}

if d.HasChange("defer") {
_, err := conn.MaintenanceWindows.Defer(context.Background(), d.Id())
if err != nil {
return fmt.Errorf(errorMaintenanceDefer, d.Id(), err)
}
}

if d.HasChange("day_of_week") {
maintenanceWindowReq.DayOfWeek = cast.ToInt(d.Get("day_of_week"))
}
if d.HasChange("hour_of_day") {
maintenanceWindowReq.HourOfDay = pointy.Int(cast.ToInt(d.Get("hour_of_day")))
}
if d.HasChange("number_of_deferrals") {
maintenanceWindowReq.NumberOfDeferrals = cast.ToInt(d.Get("number_of_deferrals"))
}

_, err := conn.MaintenanceWindows.Update(context.Background(), d.Id(), maintenanceWindowReq)
if err != nil {
return fmt.Errorf(errorMaintenanceUpdate, d.Id(), err)
}

return nil
}

func resourceMongoDBAtlasMaintenanceWindowDelete(d *schema.ResourceData, meta interface{}) error {
//Get the client connection.
conn := meta.(*matlas.Client)

_, err := conn.MaintenanceWindows.Reset(context.Background(), d.Id())
if err != nil {
return fmt.Errorf(errorMaintenanceDelete, d.Id(), err)
}

return nil
}
172 changes: 172 additions & 0 deletions mongodbatlas/resource_mongodbatlas_maintenance_window_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
package mongodbatlas

import (
"context"
"fmt"
"log"
"os"
"testing"

"github.com/go-test/deep"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
matlas "github.com/mongodb/go-client-mongodb-atlas/mongodbatlas"
"github.com/spf13/cast"
)

func TestAccResourceMongoDBAtlasMaintenanceWindow_basic(t *testing.T) {
var maintenance matlas.MaintenanceWindow
resourceName := "mongodbatlas_maintenance_window.test"

projectID := os.Getenv("MONGODB_ATLAS_PROJECT_ID")
dayOfWeek := 7
hourOfDay := 3

dayOfWeekUpdated := 4
hourOfDayUpdated := 5

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckMongoDBAtlasMaintenanceWindowDestroy,
Steps: []resource.TestStep{
{
Config: testAccMongoDBAtlasMaintenanceWindowConfig(projectID, dayOfWeek, hourOfDay),
Check: resource.ComposeTestCheckFunc(
testAccCheckMongoDBAtlasMaintenanceWindowExists(resourceName, &maintenance),
resource.TestCheckResourceAttrSet(resourceName, "project_id"),
resource.TestCheckResourceAttrSet(resourceName, "day_of_week"),
resource.TestCheckResourceAttrSet(resourceName, "hour_of_day"),

resource.TestCheckResourceAttr(resourceName, "day_of_week", cast.ToString(dayOfWeek)),
resource.TestCheckResourceAttr(resourceName, "hour_of_day", cast.ToString(hourOfDay)),
resource.TestCheckResourceAttr(resourceName, "number_of_deferrals", "0"),

testAccCheckMongoDBAtlasMaintenanceWindowAttributes("day_of_week", dayOfWeek, &maintenance.DayOfWeek),
),
},
{
Config: testAccMongoDBAtlasMaintenanceWindowConfig(projectID, dayOfWeekUpdated, hourOfDayUpdated),
Check: resource.ComposeTestCheckFunc(
testAccCheckMongoDBAtlasMaintenanceWindowExists(resourceName, &maintenance),
resource.TestCheckResourceAttrSet(resourceName, "project_id"),
resource.TestCheckResourceAttrSet(resourceName, "day_of_week"),
resource.TestCheckResourceAttrSet(resourceName, "hour_of_day"),

resource.TestCheckResourceAttr(resourceName, "day_of_week", cast.ToString(dayOfWeekUpdated)),
resource.TestCheckResourceAttr(resourceName, "hour_of_day", cast.ToString(hourOfDayUpdated)),
resource.TestCheckResourceAttr(resourceName, "number_of_deferrals", "0"),

testAccCheckMongoDBAtlasMaintenanceWindowAttributes("day_of_week", dayOfWeekUpdated, &maintenance.DayOfWeek),
),
},
},
})
}

func TestAccResourceMongoDBAtlasMaintenanceWindow_importBasic(t *testing.T) {
var maintenance matlas.MaintenanceWindow
resourceName := "mongodbatlas_maintenance_window.test"

projectID := os.Getenv("MONGODB_ATLAS_PROJECT_ID")
dayOfWeek := 1
hourOfDay := 3

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckMongoDBAtlasMaintenanceWindowDestroy,
Steps: []resource.TestStep{
{
Config: testAccMongoDBAtlasMaintenanceWindowConfig(projectID, dayOfWeek, hourOfDay),
Check: resource.ComposeTestCheckFunc(
testAccCheckMongoDBAtlasMaintenanceWindowExists(resourceName, &maintenance),
resource.TestCheckResourceAttrSet(resourceName, "project_id"),
resource.TestCheckResourceAttrSet(resourceName, "day_of_week"),
resource.TestCheckResourceAttrSet(resourceName, "hour_of_day"),

resource.TestCheckResourceAttr(resourceName, "day_of_week", cast.ToString(dayOfWeek)),
resource.TestCheckResourceAttr(resourceName, "hour_of_day", cast.ToString(hourOfDay)),
resource.TestCheckResourceAttr(resourceName, "number_of_deferrals", "0"),
resource.TestCheckResourceAttr(resourceName, "start_asap", "false"),

testAccCheckMongoDBAtlasMaintenanceWindowAttributes("day_of_week", dayOfWeek, &maintenance.DayOfWeek),
),
},
{
ResourceName: resourceName,
ImportStateIdFunc: testAccCheckMongoDBAtlasMaintenanceWindowImportStateIDFunc(resourceName),
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"project_id"},
},
},
})
}

func testAccCheckMongoDBAtlasMaintenanceWindowExists(resourceName string, maintenance *matlas.MaintenanceWindow) resource.TestCheckFunc {
return func(s *terraform.State) error {
conn := testAccProvider.Meta().(*matlas.Client)

rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("not found: %s", resourceName)
}
if rs.Primary.ID == "" {
return fmt.Errorf("no ID is set")
}

log.Printf("[DEBUG] projectID: %s", rs.Primary.ID)

maintenanceWindow, _, err := conn.MaintenanceWindows.Get(context.Background(), rs.Primary.ID)
if err != nil {
return fmt.Errorf("Maintenance Window (%s) does not exist", rs.Primary.ID)
}
*maintenance = *maintenanceWindow
return nil
}
}

func testAccCheckMongoDBAtlasMaintenanceWindowAttributes(attr string, expected int, got *int) resource.TestCheckFunc {
return func(s *terraform.State) error {
if diff := deep.Equal(expected, *got); diff != nil {
return fmt.Errorf("Bad %s \n got = %#v\nwant = %#v \ndiff = %#v", attr, expected, *got, diff)
}
return nil
}
}

func testAccCheckMongoDBAtlasMaintenanceWindowDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*matlas.Client)

for _, rs := range s.RootModule().Resources {
if rs.Type != "mongodbatlas_maintenance_window" {
continue
}

_, _, err := conn.MaintenanceWindows.Get(context.Background(), rs.Primary.ID)
if err != nil {
return fmt.Errorf("Maintenance Window (%s) does not exist", rs.Primary.ID)
}
}
return nil
}

func testAccCheckMongoDBAtlasMaintenanceWindowImportStateIDFunc(resourceName string) resource.ImportStateIdFunc {
return func(s *terraform.State) (string, error) {
rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return "", fmt.Errorf("Not found: %s", resourceName)
}
return rs.Primary.ID, nil
}
}

func testAccMongoDBAtlasMaintenanceWindowConfig(projectID string, dayOfWeek, hourOfDay int) string {
return fmt.Sprintf(`
resource "mongodbatlas_maintenance_window" "test" {
project_id = "%s"
day_of_week = %d
hour_of_day = %d
}`, projectID, dayOfWeek, hourOfDay)
}
2 changes: 2 additions & 0 deletions vendor/github.com/go-test/deep/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit ae2b73f

Please sign in to comment.