diff --git a/pagerduty/data_source_pagerduty_event_orchestration_global_cache_variable.go b/pagerduty/data_source_pagerduty_event_orchestration_global_cache_variable.go new file mode 100644 index 000000000..720fd83f0 --- /dev/null +++ b/pagerduty/data_source_pagerduty_event_orchestration_global_cache_variable.go @@ -0,0 +1,51 @@ +package pagerduty + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/heimweh/go-pagerduty/pagerduty" +) + +func dataSourcePagerDutyEventOrchestrationGlobalCacheVariable() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourcePagerDutyEventOrchestrationGlobalCacheVariableRead, + Schema: map[string]*schema.Schema{ + "event_orchestration": { + Type: schema.TypeString, + Required: true, + }, + "id": { + Type: schema.TypeString, + Optional: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + "condition": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: dataSourceEventOrchestrationCacheVariableConditionSchema, + }, + }, + "configuration": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: dataSourceEventOrchestrationCacheVariableConfigurationSchema, + }, + }, + "disabled": { + Type: schema.TypeBool, + Computed: true, + }, + }, + } +} + +func dataSourcePagerDutyEventOrchestrationGlobalCacheVariableRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return dataSourceEventOrchestrationCacheVariableRead(ctx, d, meta, pagerduty.CacheVariableTypeGlobal) +} diff --git a/pagerduty/data_source_pagerduty_event_orchestration_global_cache_variable_test.go b/pagerduty/data_source_pagerduty_event_orchestration_global_cache_variable_test.go new file mode 100644 index 000000000..b80376c43 --- /dev/null +++ b/pagerduty/data_source_pagerduty_event_orchestration_global_cache_variable_test.go @@ -0,0 +1,272 @@ +package pagerduty + +import ( + "fmt" + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" +) + +func TestAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariable_Basic(t *testing.T) { + on := fmt.Sprintf("tf_orchestration_%s", acctest.RandString(5)) + name := fmt.Sprintf("tf_global_cache_variable_%s", acctest.RandString(5)) + irn := "pagerduty_event_orchestration_global_cache_variable.orch_cv" + n := "data.pagerduty_event_orchestration_global_cache_variable.by_id" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + // find by id + { + Config: testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableByIdConfig(on, name), + Check: resource.ComposeTestCheckFunc( + testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariable(irn, n), + ), + }, + // find by id, ignore name + { + Config: testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableByIdNameConfig(on, name), + Check: resource.ComposeTestCheckFunc( + testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariable(irn, n), + ), + }, + // find by name + { + Config: testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableByNameConfig(on, name), + Check: resource.ComposeTestCheckFunc( + testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariable(irn, n), + ), + }, + // id and name are both not set + { + Config: testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableIdNameNullConfig(on, name), + ExpectError: regexp.MustCompile("Invalid Event Orchestration Cache Variable data source configuration: ID and name cannot both be null"), + }, + // bad event_orchestration + { + Config: testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableBadOrchConfig(on, name), + ExpectError: regexp.MustCompile("Unable to find a Cache Variable with ID '(.+)' on PagerDuty Event Orchestration 'bad-orchestration-id'"), + }, + // bad id + { + Config: testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableBadIdConfig(on, name), + ExpectError: regexp.MustCompile("Unable to find a Cache Variable with ID 'bad-cache-var-id' on PagerDuty Event Orchestration '(.+)'"), + }, + // bad name + { + Config: testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableBadNameConfig(on, name), + ExpectError: regexp.MustCompile("Unable to find a Cache Variable on Event Orchestration '(.+)' with name 'bad-cache-var-name'"), + }, + }, + }) +} + +func testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariable(src, n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + srcR := s.RootModule().Resources[src] + srcA := srcR.Primary.Attributes + + r := s.RootModule().Resources[n] + a := r.Primary.Attributes + + if a["id"] == "" { + return fmt.Errorf("Expected the Event Orchestration Cache Variable ID to be set") + } + + testAtts := []string{ + "id", "name", "configuration.0.type", "configuration.0.ttl_seconds", + } + + for _, att := range testAtts { + if a[att] != srcA[att] { + return fmt.Errorf("Expected the Event Orchestration Cache Variable %s to be: %s, but got: %s", att, srcA[att], a[att]) + } + } + + return nil + } +} + +func testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableBaseConfig(on, name string) string { + return fmt.Sprintf(` + resource "pagerduty_event_orchestration" "orch" { + name = "%s" + } + + resource "pagerduty_event_orchestration_global_cache_variable" "orch_cv" { + event_orchestration = pagerduty_event_orchestration.orch.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + `, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableByIdConfig(on, name string) string { + return fmt.Sprintf(` + resource "pagerduty_event_orchestration" "orch" { + name = "%s" + } + + resource "pagerduty_event_orchestration_global_cache_variable" "orch_cv" { + event_orchestration = pagerduty_event_orchestration.orch.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_global_cache_variable" "by_id" { + event_orchestration = pagerduty_event_orchestration.orch.id + id = pagerduty_event_orchestration_global_cache_variable.orch_cv.id + } + `, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableByIdNameConfig(on, name string) string { + return fmt.Sprintf(` + resource "pagerduty_event_orchestration" "orch" { + name = "%s" + } + + resource "pagerduty_event_orchestration_global_cache_variable" "orch_cv" { + event_orchestration = pagerduty_event_orchestration.orch.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_global_cache_variable" "by_id" { + event_orchestration = pagerduty_event_orchestration.orch.id + id = pagerduty_event_orchestration_global_cache_variable.orch_cv.id + name = "No such name" + } + `, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableByNameConfig(on, name string) string { + return fmt.Sprintf(` + resource "pagerduty_event_orchestration" "orch" { + name = "%[1]s" + } + + resource "pagerduty_event_orchestration_global_cache_variable" "orch_cv" { + event_orchestration = pagerduty_event_orchestration.orch.id + name = "%[2]s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_global_cache_variable" "by_id" { + event_orchestration = pagerduty_event_orchestration.orch.id + name = "%[2]s" + } + `, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableIdNameNullConfig(on, name string) string { + return fmt.Sprintf(` + resource "pagerduty_event_orchestration" "orch" { + name = "%s" + } + + resource "pagerduty_event_orchestration_global_cache_variable" "orch_cv" { + event_orchestration = pagerduty_event_orchestration.orch.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_global_cache_variable" "by_id" { + event_orchestration = pagerduty_event_orchestration.orch.id + } + `, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableBadOrchConfig(on, name string) string { + return fmt.Sprintf(` + resource "pagerduty_event_orchestration" "orch" { + name = "%s" + } + + resource "pagerduty_event_orchestration_global_cache_variable" "orch_cv" { + event_orchestration = pagerduty_event_orchestration.orch.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_global_cache_variable" "by_id" { + event_orchestration = "bad-orchestration-id" + id = pagerduty_event_orchestration_global_cache_variable.orch_cv.id + } + `, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableBadIdConfig(on, name string) string { + return fmt.Sprintf(` + resource "pagerduty_event_orchestration" "orch" { + name = "%s" + } + + resource "pagerduty_event_orchestration_global_cache_variable" "orch_cv" { + event_orchestration = pagerduty_event_orchestration.orch.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_global_cache_variable" "by_id" { + event_orchestration = pagerduty_event_orchestration.orch.id + id = "bad-cache-var-id" + } + `, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationGlobalCacheVariableBadNameConfig(on, name string) string { + return fmt.Sprintf(` + resource "pagerduty_event_orchestration" "orch" { + name = "%s" + } + + resource "pagerduty_event_orchestration_global_cache_variable" "orch_cv" { + event_orchestration = pagerduty_event_orchestration.orch.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_global_cache_variable" "by_id" { + event_orchestration = pagerduty_event_orchestration.orch.id + name = "bad-cache-var-name" + } + `, on, name) +} diff --git a/pagerduty/data_source_pagerduty_event_orchestration_service_cache_variable.go b/pagerduty/data_source_pagerduty_event_orchestration_service_cache_variable.go new file mode 100644 index 000000000..2bdf9694a --- /dev/null +++ b/pagerduty/data_source_pagerduty_event_orchestration_service_cache_variable.go @@ -0,0 +1,51 @@ +package pagerduty + +import ( + "context" + + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/heimweh/go-pagerduty/pagerduty" +) + +func dataSourcePagerDutyEventOrchestrationServiceCacheVariable() *schema.Resource { + return &schema.Resource{ + ReadContext: dataSourcePagerDutyEventOrchestrationServiceCacheVariableRead, + Schema: map[string]*schema.Schema{ + "service": { + Type: schema.TypeString, + Required: true, + }, + "id": { + Type: schema.TypeString, + Optional: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + }, + "condition": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: dataSourceEventOrchestrationCacheVariableConditionSchema, + }, + }, + "configuration": { + Type: schema.TypeList, + Computed: true, + Elem: &schema.Resource{ + Schema: dataSourceEventOrchestrationCacheVariableConfigurationSchema, + }, + }, + "disabled": { + Type: schema.TypeBool, + Computed: true, + }, + }, + } +} + +func dataSourcePagerDutyEventOrchestrationServiceCacheVariableRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return dataSourceEventOrchestrationCacheVariableRead(ctx, d, meta, pagerduty.CacheVariableTypeService) +} diff --git a/pagerduty/data_source_pagerduty_event_orchestration_service_cache_variable_test.go b/pagerduty/data_source_pagerduty_event_orchestration_service_cache_variable_test.go new file mode 100644 index 000000000..6bac4b3be --- /dev/null +++ b/pagerduty/data_source_pagerduty_event_orchestration_service_cache_variable_test.go @@ -0,0 +1,314 @@ +package pagerduty + +import ( + "fmt" + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" +) + +func TestAccDataSourcePagerDutyEventOrchestrationServiceCacheVariable_Basic(t *testing.T) { + on := fmt.Sprintf("tf_orchestration_%s", acctest.RandString(5)) + name := fmt.Sprintf("tf_service_cache_variable_%s", acctest.RandString(5)) + irn := "pagerduty_event_orchestration_service_cache_variable.orch_cv" + n := "data.pagerduty_event_orchestration_service_cache_variable.by_id" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + // find by id + { + Config: testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableByIdConfig(on, name), + Check: resource.ComposeTestCheckFunc( + testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariable(irn, n), + ), + }, + // find by id, ignore name + { + Config: testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableByIdNameConfig(on, name), + Check: resource.ComposeTestCheckFunc( + testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariable(irn, n), + ), + }, + // find by name + { + Config: testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableByNameConfig(on, name), + Check: resource.ComposeTestCheckFunc( + testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariable(irn, n), + ), + }, + // id and name are both not set + { + Config: testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableIdNameNullConfig(on, name), + ExpectError: regexp.MustCompile("Invalid Event Orchestration Cache Variable data source configuration: ID and name cannot both be null"), + }, + // bad event_orchestration + { + Config: testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableBadOrchConfig(on, name), + ExpectError: regexp.MustCompile("Unable to find a Cache Variable with ID '(.+)' on PagerDuty Event Orchestration 'bad-orchestration-id'"), + }, + // bad id + { + Config: testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableBadIdConfig(on, name), + ExpectError: regexp.MustCompile("Unable to find a Cache Variable with ID 'bad-cache-var-id' on PagerDuty Event Orchestration '(.+)'"), + }, + // bad name + { + Config: testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableBadNameConfig(on, name), + ExpectError: regexp.MustCompile("Unable to find a Cache Variable on Event Orchestration '(.+)' with name 'bad-cache-var-name'"), + }, + }, + }) +} + +const EPResources = ` + resource "pagerduty_user" "user" { + email = "user@pagerduty.com" + name = "test user" + } + + resource "pagerduty_escalation_policy" "ep" { + name = "Test EP" + rule { + escalation_delay_in_minutes = 5 + target { + type = "user_reference" + id = pagerduty_user.user.id + } + } + } +` + +func testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariable(src, n string) resource.TestCheckFunc { + return func(s *terraform.State) error { + + srcR := s.RootModule().Resources[src] + srcA := srcR.Primary.Attributes + + r := s.RootModule().Resources[n] + a := r.Primary.Attributes + + if a["id"] == "" { + return fmt.Errorf("Expected the Event Orchestration Cache Variable ID to be set") + } + + testAtts := []string{ + "id", "name", "configuration.0.type", "configuration.0.ttl_seconds", + } + + for _, att := range testAtts { + if a[att] != srcA[att] { + return fmt.Errorf("Expected the Event Orchestration Cache Variable %s to be: %s, but got: %s", att, srcA[att], a[att]) + } + } + + return nil + } +} + +func testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableBaseConfig(on, name string) string { + return fmt.Sprintf(` + %s + + resource "pagerduty_service" "svc" { + name = "%s" + escalation_policy = pagerduty_escalation_policy.ep.id + } + + resource "pagerduty_event_orchestration_service_cache_variable" "orch_cv" { + service = pagerduty_service.svc.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + `, EPResources, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableByIdConfig(on, name string) string { + return fmt.Sprintf(` + %s + + resource "pagerduty_service" "svc" { + name = "%s" + escalation_policy = pagerduty_escalation_policy.ep.id + } + + resource "pagerduty_event_orchestration_service_cache_variable" "orch_cv" { + service = pagerduty_service.svc.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_service_cache_variable" "by_id" { + service = pagerduty_service.svc.id + id = pagerduty_event_orchestration_service_cache_variable.orch_cv.id + } + `, EPResources, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableByIdNameConfig(on, name string) string { + return fmt.Sprintf(` + %s + + resource "pagerduty_service" "svc" { + name = "%s" + escalation_policy = pagerduty_escalation_policy.ep.id + } + + resource "pagerduty_event_orchestration_service_cache_variable" "orch_cv" { + service = pagerduty_service.svc.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_service_cache_variable" "by_id" { + service = pagerduty_service.svc.id + id = pagerduty_event_orchestration_service_cache_variable.orch_cv.id + name = "No such name" + } + `, EPResources, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableByNameConfig(on, name string) string { + return fmt.Sprintf(` + %[1]s + + resource "pagerduty_service" "svc" { + name = "%[2]s" + escalation_policy = pagerduty_escalation_policy.ep.id + } + + resource "pagerduty_event_orchestration_service_cache_variable" "orch_cv" { + service = pagerduty_service.svc.id + name = "%[3]s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_service_cache_variable" "by_id" { + service = pagerduty_service.svc.id + name = "%[3]s" + } + `, EPResources, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableIdNameNullConfig(on, name string) string { + return fmt.Sprintf(` + %s + + resource "pagerduty_service" "svc" { + name = "%s" + escalation_policy = pagerduty_escalation_policy.ep.id + } + + resource "pagerduty_event_orchestration_service_cache_variable" "orch_cv" { + service = pagerduty_service.svc.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_service_cache_variable" "by_id" { + service = pagerduty_service.svc.id + } + `, EPResources, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableBadOrchConfig(on, name string) string { + return fmt.Sprintf(` + %s + + resource "pagerduty_service" "svc" { + name = "%s" + escalation_policy = pagerduty_escalation_policy.ep.id + } + + resource "pagerduty_event_orchestration_service_cache_variable" "orch_cv" { + service = pagerduty_service.svc.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_service_cache_variable" "by_id" { + service = "bad-orchestration-id" + id = pagerduty_event_orchestration_service_cache_variable.orch_cv.id + } + `, EPResources, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableBadIdConfig(on, name string) string { + return fmt.Sprintf(` + %s + + resource "pagerduty_service" "svc" { + name = "%s" + escalation_policy = pagerduty_escalation_policy.ep.id + } + + resource "pagerduty_event_orchestration_service_cache_variable" "orch_cv" { + service = pagerduty_service.svc.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_service_cache_variable" "by_id" { + service = pagerduty_service.svc.id + id = "bad-cache-var-id" + } + `, EPResources, on, name) +} + +func testAccDataSourcePagerDutyEventOrchestrationServiceCacheVariableBadNameConfig(on, name string) string { + return fmt.Sprintf(` + %s + + resource "pagerduty_service" "svc" { + name = "%s" + escalation_policy = pagerduty_escalation_policy.ep.id + } + + resource "pagerduty_event_orchestration_service_cache_variable" "orch_cv" { + service = pagerduty_service.svc.id + name = "%s" + + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + } + + data "pagerduty_event_orchestration_service_cache_variable" "by_id" { + service = pagerduty_service.svc.id + name = "bad-cache-var-name" + } + `, EPResources, on, name) +} diff --git a/pagerduty/event_orchestration_cache_variable_util.go b/pagerduty/event_orchestration_cache_variable_util.go new file mode 100644 index 000000000..bce8ce866 --- /dev/null +++ b/pagerduty/event_orchestration_cache_variable_util.go @@ -0,0 +1,512 @@ +package pagerduty + +import ( + "context" + "fmt" + "log" + "net/http" + "time" + + "github.com/hashicorp/go-cty/cty" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/heimweh/go-pagerduty/pagerduty" +) + +var resourceEventOrchestrationCacheVariableConditionSchema = map[string]*schema.Schema{ + "expression": { + Type: schema.TypeString, + Required: true, + }, +} + +var resourceEventOrchestrationCacheVariableConfigurationSchema = map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Required: true, + ValidateDiagFunc: validateValueDiagFunc([]string{ + "recent_value", + "trigger_event_count", + }), + }, + "regex": { + Type: schema.TypeString, + Optional: true, + }, + "source": { + Type: schema.TypeString, + Optional: true, + }, + "ttl_seconds": { + Type: schema.TypeInt, + Optional: true, + ValidateDiagFunc: func(v interface{}, p cty.Path) diag.Diagnostics { + var diags diag.Diagnostics + min := 1 + max := 84000 + + value := v.(int) + valid := value >= min && value <= max + + if !valid { + diags = append(diags, diag.Diagnostic{ + Severity: diag.Error, + Summary: fmt.Sprintf("%#v is an invalid value. Must be between %#v and %#v (inclusive)", value, min, max), + AttributePath: p, + }) + } + return diags + }, + }, +} + +var dataSourceEventOrchestrationCacheVariableConditionSchema = map[string]*schema.Schema{ + "expression": { + Type: schema.TypeString, + Computed: true, + }, +} + +var dataSourceEventOrchestrationCacheVariableConfigurationSchema = map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Computed: true, + }, + "regex": { + Type: schema.TypeString, + Computed: true, + }, + "source": { + Type: schema.TypeString, + Computed: true, + }, + "ttl_seconds": { + Type: schema.TypeInt, + Computed: true, + }, +} + +func checkConfiguration(context context.Context, diff *schema.ResourceDiff, i interface{}) error { + t := diff.Get("configuration.0.type").(string) + s := diff.Get("configuration.0.source").(string) + r := diff.Get("configuration.0.regex").(string) + ts := diff.Get("configuration.0.ttl_seconds").(int) + + if t == "recent_value" && (r == "" || s == "") { + return fmt.Errorf("Invalid configuration: regex and source cannot be null when type is recent_value") + } + if t == "trigger_event_count" && ts == 0 { + return fmt.Errorf("Invalid configuration: ttl_seconds cannot be null when type is trigger_event_count") + } + if (r != "" || s != "") && ts != 0 { + return fmt.Errorf("Invalid configuration: ttl_seconds cannot be used in conjuction with regex and source") + } + return nil +} + +func getIdentifier(cacheVariableType string) string { + switch cacheVariableType { + case pagerduty.CacheVariableTypeGlobal: + return "event_orchestration" + case pagerduty.CacheVariableTypeService: + return "service" + } + return "" +} + +func setEventOrchestrationCacheVariableProps(d *schema.ResourceData, cv *pagerduty.EventOrchestrationCacheVariable) error { + d.Set("name", cv.Name) + d.Set("disabled", cv.Disabled) + d.Set("configuration", flattenEventOrchestrationCacheVariableConfiguration(cv.Configuration)) + d.Set("condition", flattenEventOrchestrationCacheVariableConditions(cv.Conditions)) + + return nil +} + +func getEventOrchestrationCacheVariablePayloadData(d *schema.ResourceData, cacheVariableType string) (string, *pagerduty.EventOrchestrationCacheVariable) { + orchestrationId := d.Get(getIdentifier(cacheVariableType)).(string) + + cacheVariable := &pagerduty.EventOrchestrationCacheVariable{ + Name: d.Get("name").(string), + Conditions: expandEventOrchestrationCacheVariableConditions(d.Get("condition")), + Configuration: expandEventOrchestrationCacheVariableConfiguration(d.Get("configuration")), + Disabled: d.Get("disabled").(bool), + } + + return orchestrationId, cacheVariable +} + +func fetchPagerDutyEventOrchestrationCacheVariable(ctx context.Context, d *schema.ResourceData, meta interface{}, cacheVariableType string, oid string, id string) (*pagerduty.EventOrchestrationCacheVariable, error) { + client, err := meta.(*Config).Client() + if err != nil { + return nil, err + } + + if cacheVariable, _, err := client.EventOrchestrationCacheVariables.GetContext(ctx, cacheVariableType, oid, id); err != nil { + return nil, err + } else if cacheVariable != nil { + d.SetId(id) + d.Set(getIdentifier(cacheVariableType), oid) + setEventOrchestrationCacheVariableProps(d, cacheVariable) + return cacheVariable, nil + } + + return nil, fmt.Errorf("Reading Cache Variable '%s' for PagerDuty Event Orchestration '%s' returned `nil`.", id, oid) +} + +/* +**** + + Schema expand and flatten helpers + +**** +*/ +func expandEventOrchestrationCacheVariableConditions(v interface{}) []*pagerduty.EventOrchestrationCacheVariableCondition { + conditions := []*pagerduty.EventOrchestrationCacheVariableCondition{} + + for _, cond := range v.([]interface{}) { + c := cond.(map[string]interface{}) + + cx := &pagerduty.EventOrchestrationCacheVariableCondition{ + Expression: c["expression"].(string), + } + + conditions = append(conditions, cx) + } + + return conditions +} + +func expandEventOrchestrationCacheVariableConfiguration(v interface{}) *pagerduty.EventOrchestrationCacheVariableConfiguration { + conf := &pagerduty.EventOrchestrationCacheVariableConfiguration{} + + for _, i := range v.([]interface{}) { + c := i.(map[string]interface{}) + + conf.Type = c["type"].(string) + conf.Regex = c["regex"].(string) + conf.Source = c["source"].(string) + conf.TTLSeconds = c["ttl_seconds"].(int) + } + + return conf +} + +func flattenEventOrchestrationCacheVariableConditions(conds []*pagerduty.EventOrchestrationCacheVariableCondition) []interface{} { + var flattenedConds []interface{} + + for _, cond := range conds { + flattenedCond := map[string]interface{}{ + "expression": cond.Expression, + } + flattenedConds = append(flattenedConds, flattenedCond) + } + + return flattenedConds +} + +func flattenEventOrchestrationCacheVariableConfiguration(conf *pagerduty.EventOrchestrationCacheVariableConfiguration) []interface{} { + result := map[string]interface{}{ + "type": conf.Type, + "regex": conf.Regex, + "source": conf.Source, + "ttl_seconds": conf.TTLSeconds, + } + + return []interface{}{result} +} + +/* +**** + + Resource contexts + +**** +*/ +func resourceEventOrchestrationCacheVariableImport(ctx context.Context, d *schema.ResourceData, meta interface{}, cacheVariableType string) ([]*schema.ResourceData, error) { + oid, id, err := resourcePagerDutyParseColonCompoundID(d.Id()) + if err != nil { + return []*schema.ResourceData{}, err + } + + if oid == "" || id == "" { + return []*schema.ResourceData{}, fmt.Errorf("Error importing cache variable. Expected import ID format: :") + } + + retryErr := retry.RetryContext(ctx, 2*time.Minute, func() *retry.RetryError { + log.Printf("[INFO] Reading Cache Variable '%s' for PagerDuty Event Orchestration: %s", id, oid) + + if _, err := fetchPagerDutyEventOrchestrationCacheVariable(ctx, d, meta, cacheVariableType, oid, id); err != nil { + if isErrCode(err, http.StatusBadRequest) { + return retry.NonRetryableError(err) + } + + return retry.RetryableError(err) + } + return nil + }) + + if retryErr != nil { + return []*schema.ResourceData{}, retryErr + } + + return []*schema.ResourceData{d}, nil +} + +func resourceEventOrchestrationCacheVariableCreate(ctx context.Context, d *schema.ResourceData, meta interface{}, cacheVariableType string) diag.Diagnostics { + client, err := meta.(*Config).Client() + if err != nil { + return diag.FromErr(err) + } + + oid, payload := getEventOrchestrationCacheVariablePayloadData(d, cacheVariableType) + + retryErr := retry.RetryContext(ctx, 2*time.Minute, func() *retry.RetryError { + log.Printf("[INFO] Creating Cache Variable '%s' for PagerDuty Event Orchestration '%s'", payload.Name, oid) + + if cacheVariable, _, err := client.EventOrchestrationCacheVariables.CreateContext(ctx, cacheVariableType, oid, payload); err != nil { + if isErrCode(err, http.StatusBadRequest) || isErrCode(err, http.StatusNotFound) || isErrCode(err, http.StatusForbidden) { + return retry.NonRetryableError(err) + } + return retry.RetryableError(err) + } else if cacheVariable != nil { + // Try reading an cache variable after creation, retry if not found: + if _, readErr := fetchPagerDutyEventOrchestrationCacheVariable(ctx, d, meta, cacheVariableType, oid, cacheVariable.ID); readErr != nil { + log.Printf("[WARN] Cannot locate Cache Variable '%s' on PagerDuty Event Orchestration '%s'. Retrying creation...", cacheVariable.ID, oid) + return retry.RetryableError(readErr) + } + } + return nil + }) + + if retryErr != nil { + time.Sleep(2 * time.Second) + return diag.FromErr(retryErr) + } + + return nil +} + +func resourceEventOrchestrationCacheVariableRead(ctx context.Context, d *schema.ResourceData, meta interface{}, cacheVariableType string) diag.Diagnostics { + id := d.Id() + oid := d.Get(getIdentifier(cacheVariableType)).(string) + + retryErr := retry.RetryContext(ctx, 2*time.Minute, func() *retry.RetryError { + log.Printf("[INFO] Reading Cache Variable '%s' for PagerDuty Event Orchestration: %s", id, oid) + + if _, err := fetchPagerDutyEventOrchestrationCacheVariable(ctx, d, meta, cacheVariableType, oid, id); err != nil { + if isErrCode(err, http.StatusBadRequest) { + return retry.NonRetryableError(err) + } else if isErrCode(err, http.StatusNotFound) { + log.Printf("[WARN] Removing %s because it's gone", d.Id()) + d.SetId("") + return nil + } + + return retry.RetryableError(err) + } + + return nil + }) + + if retryErr != nil { + return diag.FromErr(retryErr) + } + + return nil +} + +func resourceEventOrchestrationCacheVariableUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}, cacheVariableType string) diag.Diagnostics { + client, err := meta.(*Config).Client() + if err != nil { + return diag.FromErr(err) + } + + id := d.Id() + oid, payload := getEventOrchestrationCacheVariablePayloadData(d, cacheVariableType) + + retryErr := retry.RetryContext(ctx, 2*time.Minute, func() *retry.RetryError { + log.Printf("[INFO] Updating Cache Variable '%s' for PagerDuty Event Orchestration: %s", id, oid) + if cacheVariable, _, err := client.EventOrchestrationCacheVariables.UpdateContext(ctx, cacheVariableType, oid, id, payload); err != nil { + if isErrCode(err, http.StatusBadRequest) || isErrCode(err, http.StatusNotFound) || isErrCode(err, http.StatusForbidden) { + return retry.NonRetryableError(err) + } + + return retry.RetryableError(err) + } else if cacheVariable != nil { + d.SetId(cacheVariable.ID) + setEventOrchestrationCacheVariableProps(d, cacheVariable) + } + return nil + }) + + if retryErr != nil { + return diag.FromErr(retryErr) + } + + return nil +} + +func resourceEventOrchestrationCacheVariableDelete(ctx context.Context, d *schema.ResourceData, meta interface{}, cacheVariableType string) diag.Diagnostics { + client, err := meta.(*Config).Client() + if err != nil { + return diag.FromErr(err) + } + + id := d.Id() + oid, _ := getEventOrchestrationCacheVariablePayloadData(d, cacheVariableType) + + retryErr := retry.RetryContext(ctx, 2*time.Minute, func() *retry.RetryError { + log.Printf("[INFO] Deleting Cache Variable '%s' for PagerDuty Event Orchestration: %s", id, oid) + if _, err := client.EventOrchestrationCacheVariables.DeleteContext(ctx, cacheVariableType, oid, id); err != nil { + if isErrCode(err, http.StatusBadRequest) || isErrCode(err, http.StatusNotFound) || isErrCode(err, http.StatusForbidden) { + return retry.NonRetryableError(err) + } + + return retry.RetryableError(err) + } else { + // Try reading an cache variable after deletion, retry if still found: + if cacheVariable, _, readErr := client.EventOrchestrationCacheVariables.GetContext(ctx, cacheVariableType, oid, id); readErr == nil && cacheVariable != nil { + log.Printf("[WARN] Cache Variable '%s' still exists on PagerDuty Event Orchestration '%s'. Retrying deletion...", id, oid) + return retry.RetryableError(fmt.Errorf("Cache Variable '%s' still exists on PagerDuty Event Orchestration '%s'.", id, oid)) + } + } + return nil + }) + + if retryErr != nil { + time.Sleep(2 * time.Second) + return diag.FromErr(retryErr) + } + + d.SetId("") + + return nil +} + +/* +**** + + Data Source context and helpers + +**** +*/ + +func dataSourceEventOrchestrationCacheVariableRead(ctx context.Context, d *schema.ResourceData, meta interface{}, cacheVariableType string) diag.Diagnostics { + var diags diag.Diagnostics + + id := d.Get("id").(string) + name := d.Get("name").(string) + + if id == "" && name == "" { + return diag.FromErr(fmt.Errorf("Invalid Event Orchestration Cache Variable data source configuration: ID and name cannot both be null")) + } + + oid := d.Get(getIdentifier(cacheVariableType)).(string) + + if id != "" && name != "" { + diag := diag.Diagnostic{ + Severity: diag.Warning, + Summary: fmt.Sprintf("Event Orchestration Cache Variable data source has both the ID and name attributes configured. Using ID '%s' to read data.", id), + } + diags = append(diags, diag) + } + + if id != "" { + return getEventOrchestrationCacheVariableById(ctx, d, meta, diags, cacheVariableType, oid, id) + } + + return getEventOrchestrationCacheVariableByName(ctx, d, meta, diags, cacheVariableType, oid, name) +} + +func getEventOrchestrationCacheVariableById(ctx context.Context, d *schema.ResourceData, meta interface{}, diags diag.Diagnostics, cacheVariableType string, oid, id string) diag.Diagnostics { + client, err := meta.(*Config).Client() + if err != nil { + return diag.FromErr(err) + } + + retryErr := retry.RetryContext(ctx, 2*time.Minute, func() *retry.RetryError { + log.Printf("[INFO] Reading Cache Variable data source by ID '%s' for PagerDuty Event Orchestration '%s'", id, oid) + + if cacheVariable, _, err := client.EventOrchestrationCacheVariables.GetContext(ctx, cacheVariableType, oid, id); err != nil { + if isErrCode(err, http.StatusBadRequest) { + return retry.NonRetryableError(err) + } + + time.Sleep(30 * time.Second) + return retry.RetryableError(err) + } else if cacheVariable != nil { + d.SetId(cacheVariable.ID) + setEventOrchestrationCacheVariableProps(d, cacheVariable) + } + return nil + }) + + if retryErr != nil { + diag := diag.Diagnostic{ + Severity: diag.Error, + Summary: fmt.Sprintf("Unable to find a Cache Variable with ID '%s' on PagerDuty Event Orchestration '%s'", id, oid), + } + return append(diags, diag) + } + + return diags +} + +func getEventOrchestrationCacheVariableByName(ctx context.Context, d *schema.ResourceData, meta interface{}, diags diag.Diagnostics, cacheVariableType string, oid, name string) diag.Diagnostics { + client, err := meta.(*Config).Client() + if err != nil { + return diag.FromErr(err) + } + + retryErr := retry.RetryContext(ctx, 2*time.Minute, func() *retry.RetryError { + log.Printf("[INFO] Reading Cache Variable data source by name '%s' for PagerDuty Event Orchestration '%s'", name, oid) + + resp, _, err := client.EventOrchestrationCacheVariables.ListContext(ctx, cacheVariableType, oid) + if err != nil { + if isErrCode(err, http.StatusBadRequest) { + return retry.NonRetryableError(err) + } + + time.Sleep(30 * time.Second) + return retry.RetryableError(err) + } + + var matches []*pagerduty.EventOrchestrationCacheVariable + + for _, i := range resp.CacheVariables { + if i.Name == name { + matches = append(matches, i) + } + } + + count := len(matches) + + if count == 0 { + return retry.NonRetryableError( + fmt.Errorf("Unable to find a Cache Variable on Event Orchestration '%s' with name '%s'", oid, name), + ) + } + + // This case should theoretically be impossible since Cache Variables must have + // unique names per Event Orchestration + if count > 1 { + return retry.NonRetryableError( + fmt.Errorf("Ambiguous Cache Variable name: '%s'. Found %v Cache Variables with this name on Event Orchestration '%s'. Please use the Cache Variable ID instead or make Cache Variable names unique within Event Orchestration.", name, count, oid), + ) + } + + found := matches[0] + d.SetId(found.ID) + setEventOrchestrationCacheVariableProps(d, found) + + return nil + }) + + if retryErr != nil { + return diag.FromErr(retryErr) + } + + return diags +} diff --git a/pagerduty/import_pagerduty_event_orchestration_global_cache_variable_test.go b/pagerduty/import_pagerduty_event_orchestration_global_cache_variable_test.go new file mode 100644 index 000000000..2bf27005d --- /dev/null +++ b/pagerduty/import_pagerduty_event_orchestration_global_cache_variable_test.go @@ -0,0 +1,44 @@ +package pagerduty + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" +) + +func TestAccPagerDutyEventOrchestrationGlobalCacheVariable_import(t *testing.T) { + orch := fmt.Sprintf("tf_orchestration_%s", acctest.RandString(5)) + name := fmt.Sprintf("tf_global_cache_variable_%s", acctest.RandString(5)) + disabled := "false" + config := ` + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + ` + cond := "" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableConfig(orch, name, "orch_1", disabled, config, cond), + }, + { + ResourceName: "pagerduty_event_orchestration_global_cache_variable.cv_1", + ImportStateIdFunc: testAccPagerDutyEventOrchestrationGlobalCacheVariableImportID, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccPagerDutyEventOrchestrationGlobalCacheVariableImportID(s *terraform.State) (string, error) { + return fmt.Sprintf("%v:%v", s.RootModule().Resources["pagerduty_event_orchestration.orch_1"].Primary.ID, s.RootModule().Resources["pagerduty_event_orchestration_global_cache_variable.cv_1"].Primary.ID), nil +} diff --git a/pagerduty/import_pagerduty_event_orchestration_service_cache_variable_test.go b/pagerduty/import_pagerduty_event_orchestration_service_cache_variable_test.go new file mode 100644 index 000000000..05583d943 --- /dev/null +++ b/pagerduty/import_pagerduty_event_orchestration_service_cache_variable_test.go @@ -0,0 +1,44 @@ +package pagerduty + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" +) + +func TestAccPagerDutyEventOrchestrationServiceCacheVariable_import(t *testing.T) { + svc := fmt.Sprintf("tf_service_%s", acctest.RandString(5)) + name := fmt.Sprintf("tf_service_cache_variable_%s", acctest.RandString(5)) + disabled := "false" + config := ` + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + ` + cond := "" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckPagerDutyEventOrchestrationServiceCacheVariableDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckPagerDutyEventOrchestrationServiceCacheVariableConfig(svc, name, "svc_1", disabled, config, cond), + }, + { + ResourceName: "pagerduty_event_orchestration_service_cache_variable.cv_1", + ImportStateIdFunc: testAccPagerDutyEventOrchestrationServiceCacheVariableImportID, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccPagerDutyEventOrchestrationServiceCacheVariableImportID(s *terraform.State) (string, error) { + return fmt.Sprintf("%v:%v", s.RootModule().Resources["pagerduty_service.svc_1"].Primary.ID, s.RootModule().Resources["pagerduty_event_orchestration_service_cache_variable.cv_1"].Primary.ID), nil +} diff --git a/pagerduty/provider.go b/pagerduty/provider.go index 02f89190b..876b6784b 100644 --- a/pagerduty/provider.go +++ b/pagerduty/provider.go @@ -75,30 +75,32 @@ func Provider() *schema.Provider { }, DataSourcesMap: map[string]*schema.Resource{ - "pagerduty_escalation_policy": dataSourcePagerDutyEscalationPolicy(), - "pagerduty_schedule": dataSourcePagerDutySchedule(), - "pagerduty_user": dataSourcePagerDutyUser(), - "pagerduty_users": dataSourcePagerDutyUsers(), - "pagerduty_license": dataSourcePagerDutyLicense(), - "pagerduty_licenses": dataSourcePagerDutyLicenses(), - "pagerduty_user_contact_method": dataSourcePagerDutyUserContactMethod(), - "pagerduty_team": dataSourcePagerDutyTeam(), - "pagerduty_vendor": dataSourcePagerDutyVendor(), - "pagerduty_extension_schema": dataSourcePagerDutyExtensionSchema(), - "pagerduty_service": dataSourcePagerDutyService(), - "pagerduty_service_integration": dataSourcePagerDutyServiceIntegration(), - "pagerduty_business_service": dataSourcePagerDutyBusinessService(), - "pagerduty_priority": dataSourcePagerDutyPriority(), - "pagerduty_ruleset": dataSourcePagerDutyRuleset(), - "pagerduty_tag": dataSourcePagerDutyTag(), - "pagerduty_event_orchestration": dataSourcePagerDutyEventOrchestration(), - "pagerduty_event_orchestrations": dataSourcePagerDutyEventOrchestrations(), - "pagerduty_event_orchestration_integration": dataSourcePagerDutyEventOrchestrationIntegration(), - "pagerduty_automation_actions_runner": dataSourcePagerDutyAutomationActionsRunner(), - "pagerduty_automation_actions_action": dataSourcePagerDutyAutomationActionsAction(), - "pagerduty_incident_workflow": dataSourcePagerDutyIncidentWorkflow(), - "pagerduty_incident_custom_field": dataSourcePagerDutyIncidentCustomField(), - "pagerduty_team_members": dataSourcePagerDutyTeamMembers(), + "pagerduty_escalation_policy": dataSourcePagerDutyEscalationPolicy(), + "pagerduty_schedule": dataSourcePagerDutySchedule(), + "pagerduty_user": dataSourcePagerDutyUser(), + "pagerduty_users": dataSourcePagerDutyUsers(), + "pagerduty_license": dataSourcePagerDutyLicense(), + "pagerduty_licenses": dataSourcePagerDutyLicenses(), + "pagerduty_user_contact_method": dataSourcePagerDutyUserContactMethod(), + "pagerduty_team": dataSourcePagerDutyTeam(), + "pagerduty_vendor": dataSourcePagerDutyVendor(), + "pagerduty_extension_schema": dataSourcePagerDutyExtensionSchema(), + "pagerduty_service": dataSourcePagerDutyService(), + "pagerduty_service_integration": dataSourcePagerDutyServiceIntegration(), + "pagerduty_business_service": dataSourcePagerDutyBusinessService(), + "pagerduty_priority": dataSourcePagerDutyPriority(), + "pagerduty_ruleset": dataSourcePagerDutyRuleset(), + "pagerduty_tag": dataSourcePagerDutyTag(), + "pagerduty_event_orchestration": dataSourcePagerDutyEventOrchestration(), + "pagerduty_event_orchestrations": dataSourcePagerDutyEventOrchestrations(), + "pagerduty_event_orchestration_integration": dataSourcePagerDutyEventOrchestrationIntegration(), + "pagerduty_event_orchestration_global_cache_variable": dataSourcePagerDutyEventOrchestrationGlobalCacheVariable(), + "pagerduty_event_orchestration_service_cache_variable": dataSourcePagerDutyEventOrchestrationServiceCacheVariable(), + "pagerduty_automation_actions_runner": dataSourcePagerDutyAutomationActionsRunner(), + "pagerduty_automation_actions_action": dataSourcePagerDutyAutomationActionsAction(), + "pagerduty_incident_workflow": dataSourcePagerDutyIncidentWorkflow(), + "pagerduty_incident_custom_field": dataSourcePagerDutyIncidentCustomField(), + "pagerduty_team_members": dataSourcePagerDutyTeamMembers(), }, ResourcesMap: map[string]*schema.Resource{ @@ -133,6 +135,8 @@ func Provider() *schema.Provider { "pagerduty_event_orchestration_router": resourcePagerDutyEventOrchestrationPathRouter(), "pagerduty_event_orchestration_unrouted": resourcePagerDutyEventOrchestrationPathUnrouted(), "pagerduty_event_orchestration_service": resourcePagerDutyEventOrchestrationPathService(), + "pagerduty_event_orchestration_global_cache_variable": resourcePagerDutyEventOrchestrationGlobalCacheVariable(), + "pagerduty_event_orchestration_service_cache_variable": resourcePagerDutyEventOrchestrationServiceCacheVariable(), "pagerduty_automation_actions_runner": resourcePagerDutyAutomationActionsRunner(), "pagerduty_automation_actions_action": resourcePagerDutyAutomationActionsAction(), "pagerduty_automation_actions_action_team_association": resourcePagerDutyAutomationActionsActionTeamAssociation(), diff --git a/pagerduty/resource_pagerduty_event_orchestration_global_cache_variable.go b/pagerduty/resource_pagerduty_event_orchestration_global_cache_variable.go new file mode 100644 index 000000000..a830d7975 --- /dev/null +++ b/pagerduty/resource_pagerduty_event_orchestration_global_cache_variable.go @@ -0,0 +1,72 @@ +package pagerduty + +import ( + "context" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/heimweh/go-pagerduty/pagerduty" +) + +func resourcePagerDutyEventOrchestrationGlobalCacheVariable() *schema.Resource { + return &schema.Resource{ + CreateContext: resourcePagerDutyEventOrchestrationGlobalCacheVariableCreate, + ReadContext: resourcePagerDutyEventOrchestrationGlobalCacheVariableRead, + UpdateContext: resourcePagerDutyEventOrchestrationGlobalCacheVariableUpdate, + DeleteContext: resourcePagerDutyEventOrchestrationGlobalCacheVariableDelete, + Importer: &schema.ResourceImporter{ + StateContext: resourcePagerDutyEventOrchestrationGlobalCacheVariableImport, + }, + CustomizeDiff: checkConfiguration, + Schema: map[string]*schema.Schema{ + "event_orchestration": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "id": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + }, + "condition": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: resourceEventOrchestrationCacheVariableConditionSchema, + }, + }, + "configuration": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: resourceEventOrchestrationCacheVariableConfigurationSchema, + }, + }, + "disabled": { + Type: schema.TypeBool, + Optional: true, + }, + }, + } +} + +func resourcePagerDutyEventOrchestrationGlobalCacheVariableImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + return resourceEventOrchestrationCacheVariableImport(ctx, d, meta, pagerduty.CacheVariableTypeGlobal) +} + +func resourcePagerDutyEventOrchestrationGlobalCacheVariableCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return resourceEventOrchestrationCacheVariableCreate(ctx, d, meta, pagerduty.CacheVariableTypeGlobal) +} +func resourcePagerDutyEventOrchestrationGlobalCacheVariableRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return resourceEventOrchestrationCacheVariableRead(ctx, d, meta, pagerduty.CacheVariableTypeGlobal) +} +func resourcePagerDutyEventOrchestrationGlobalCacheVariableUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return resourceEventOrchestrationCacheVariableUpdate(ctx, d, meta, pagerduty.CacheVariableTypeGlobal) +} +func resourcePagerDutyEventOrchestrationGlobalCacheVariableDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return resourceEventOrchestrationCacheVariableDelete(ctx, d, meta, pagerduty.CacheVariableTypeGlobal) +} diff --git a/pagerduty/resource_pagerduty_event_orchestration_global_cache_variable_test.go b/pagerduty/resource_pagerduty_event_orchestration_global_cache_variable_test.go new file mode 100644 index 000000000..08e3a2267 --- /dev/null +++ b/pagerduty/resource_pagerduty_event_orchestration_global_cache_variable_test.go @@ -0,0 +1,197 @@ +package pagerduty + +import ( + "context" + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/heimweh/go-pagerduty/pagerduty" +) + +func init() { + resource.AddTestSweepers("pagerduty_event_orchestration_global_cache_variable", &resource.Sweeper{ + Name: "pagerduty_event_orchestration_global_cache_variable", + F: testSweepEventOrchestration, + }) +} + +func TestAccPagerDutyEventOrchestrationGlobalCacheVariable_Basic(t *testing.T) { + orch := fmt.Sprintf("tf_orchestration_%s", acctest.RandString(5)) + cv := "pagerduty_event_orchestration_global_cache_variable.cv_1" + + name1 := fmt.Sprintf("tf_global_cache_variable_%s", acctest.RandString(5)) + orchn1 := "orch_1" + name2 := fmt.Sprintf("tf_global_cache_variable_updated_%s", acctest.RandString(5)) + orchn2 := "orch_2" + + config1 := ` + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + ` + config2 := ` + configuration { + type = "recent_value" + source = "event.summary" + regex = ".*" + } + ` + cond1 := `` + cond2 := ` + condition { + expression = "event.source exists" + } + ` + disabled1 := "false" + disabled2 := "true" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableConfig(orch, name1, orchn1, disabled1, config1, cond1), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableID(cv, orchn1), + resource.TestCheckResourceAttr(cv, "name", name1), + ), + }, + // update name and disabled state: + { + Config: testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableConfig(orch, name2, orchn1, disabled2, config1, cond1), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableID(cv, orchn1), + resource.TestCheckResourceAttr(cv, "name", name2), + resource.TestCheckResourceAttr(cv, "disabled", disabled2), + ), + }, + // update config: + { + Config: testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableConfig(orch, name1, orchn1, disabled1, config2, cond1), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableID(cv, orchn1), + resource.TestCheckResourceAttr(cv, "configuration.0.type", "recent_value"), + resource.TestCheckResourceAttr(cv, "configuration.0.source", "event.summary"), + resource.TestCheckResourceAttr(cv, "configuration.0.regex", ".*"), + ), + }, + // update condition: + { + Config: testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableConfig(orch, name1, orchn1, disabled1, config1, cond2), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableID(cv, orchn1), + resource.TestCheckResourceAttr(cv, "condition.0.expression", "event.source exists"), + ), + }, + // update parent event orchestration: + { + Config: testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableConfig(orch, name1, orchn2, disabled1, config1, cond1), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableID(cv, orchn2), + ), + }, + // delete cache variable: + { + Config: testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableDeletedConfig(orch), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableExistsNot(cv), + ), + }, + }, + }) +} + +func testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableDestroy(s *terraform.State) error { + client, _ := testAccProvider.Meta().(*Config).Client() + for _, r := range s.RootModule().Resources { + if r.Type != "pagerduty_event_orchestration_global_cache_variable" { + continue + } + if _, _, err := client.EventOrchestrationCacheVariables.GetContext(context.Background(), pagerduty.CacheVariableTypeGlobal, r.Primary.Attributes["event_orchestration"], r.Primary.ID); err == nil { + return fmt.Errorf("Event Orchestration Cache Variables still exist") + } + } + return nil +} + +func testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableExistsNot(cv string) resource.TestCheckFunc { + return func(s *terraform.State) error { + _, ok := s.RootModule().Resources[cv] + if ok { + return fmt.Errorf("Event Orchestration Cache Variable is not deleted from the state: %s", cv) + } + + return nil + } +} + +func testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableID(cv, orchn string) resource.TestCheckFunc { + return func(s *terraform.State) error { + ir, ok := s.RootModule().Resources[cv] + eor, _ := s.RootModule().Resources[fmt.Sprintf("pagerduty_event_orchestration.%s", orchn)] + + if !ok { + return fmt.Errorf("Event Orchestration Cache Variable resource not found in the state: %s", cv) + } + + oid := ir.Primary.Attributes["event_orchestration"] + id := ir.Primary.ID + + client, _ := testAccProvider.Meta().(*Config).Client() + i, _, err := client.EventOrchestrationCacheVariables.GetContext(context.Background(), pagerduty.CacheVariableTypeGlobal, oid, id) + eo, _, _ := client.EventOrchestrations.Get(eor.Primary.ID) + + if err != nil { + return err + } + + if i.ID != id { + return fmt.Errorf("Event Orchestration Cache Variable ID does not match the resource ID: %v - %v", i.ID, id) + } + + if eo.ID != oid { + return fmt.Errorf("Event Orchestration Cache Variable's parent ID does not match the resource event_orchestration attr: %v - %v", eo.ID, oid) + } + + return nil + } +} + +func testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableConfig(orch, name, orchn string, disabled string, config string, cond string) string { + return fmt.Sprintf(` + resource "pagerduty_event_orchestration" "orch_1" { + name = "%s-1" + } + + resource "pagerduty_event_orchestration" "orch_2" { + name = "%s-2" + } + + resource "pagerduty_event_orchestration_global_cache_variable" "cv_1" { + name = "%s" + event_orchestration = pagerduty_event_orchestration.%s.id + disabled = %s + + %s + + %s + } + `, orch, orch, name, orchn, disabled, config, cond) +} + +func testAccCheckPagerDutyEventOrchestrationGlobalCacheVariableDeletedConfig(orch string) string { + return fmt.Sprintf(` + resource "pagerduty_event_orchestration" "orch_1" { + name = "%s-1" + } + + resource "pagerduty_event_orchestration" "orch_2" { + name = "%s-2" + } + `, orch, orch) +} diff --git a/pagerduty/resource_pagerduty_event_orchestration_service_cache_variable.go b/pagerduty/resource_pagerduty_event_orchestration_service_cache_variable.go new file mode 100644 index 000000000..8be92d645 --- /dev/null +++ b/pagerduty/resource_pagerduty_event_orchestration_service_cache_variable.go @@ -0,0 +1,72 @@ +package pagerduty + +import ( + "context" + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/heimweh/go-pagerduty/pagerduty" +) + +func resourcePagerDutyEventOrchestrationServiceCacheVariable() *schema.Resource { + return &schema.Resource{ + CreateContext: resourcePagerDutyEventOrchestrationServiceCacheVariableCreate, + ReadContext: resourcePagerDutyEventOrchestrationServiceCacheVariableRead, + UpdateContext: resourcePagerDutyEventOrchestrationServiceCacheVariableUpdate, + DeleteContext: resourcePagerDutyEventOrchestrationServiceCacheVariableDelete, + Importer: &schema.ResourceImporter{ + StateContext: resourcePagerDutyEventOrchestrationServiceCacheVariableImport, + }, + CustomizeDiff: checkConfiguration, + Schema: map[string]*schema.Schema{ + "service": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "id": { + Type: schema.TypeString, + Computed: true, + }, + "name": { + Type: schema.TypeString, + Required: true, + }, + "condition": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: resourceEventOrchestrationCacheVariableConditionSchema, + }, + }, + "configuration": { + Type: schema.TypeList, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: resourceEventOrchestrationCacheVariableConfigurationSchema, + }, + }, + "disabled": { + Type: schema.TypeBool, + Optional: true, + }, + }, + } +} + +func resourcePagerDutyEventOrchestrationServiceCacheVariableImport(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + return resourceEventOrchestrationCacheVariableImport(ctx, d, meta, pagerduty.CacheVariableTypeService) +} + +func resourcePagerDutyEventOrchestrationServiceCacheVariableCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return resourceEventOrchestrationCacheVariableCreate(ctx, d, meta, pagerduty.CacheVariableTypeService) +} +func resourcePagerDutyEventOrchestrationServiceCacheVariableRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return resourceEventOrchestrationCacheVariableRead(ctx, d, meta, pagerduty.CacheVariableTypeService) +} +func resourcePagerDutyEventOrchestrationServiceCacheVariableUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return resourceEventOrchestrationCacheVariableUpdate(ctx, d, meta, pagerduty.CacheVariableTypeService) +} +func resourcePagerDutyEventOrchestrationServiceCacheVariableDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { + return resourceEventOrchestrationCacheVariableDelete(ctx, d, meta, pagerduty.CacheVariableTypeService) +} diff --git a/pagerduty/resource_pagerduty_event_orchestration_service_cache_variable_test.go b/pagerduty/resource_pagerduty_event_orchestration_service_cache_variable_test.go new file mode 100644 index 000000000..597701ef9 --- /dev/null +++ b/pagerduty/resource_pagerduty_event_orchestration_service_cache_variable_test.go @@ -0,0 +1,233 @@ +package pagerduty + +import ( + "context" + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/helper/acctest" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/terraform" + "github.com/heimweh/go-pagerduty/pagerduty" +) + +func init() { + resource.AddTestSweepers("pagerduty_event_orchestration_service_cache_variable", &resource.Sweeper{ + Name: "pagerduty_event_orchestration_service_cache_variable", + F: testSweepEventOrchestration, + }) +} + +func TestAccPagerDutyEventOrchestrationServiceCacheVariable_Basic(t *testing.T) { + svc := fmt.Sprintf("tf_service_%s", acctest.RandString(5)) + cv := "pagerduty_event_orchestration_service_cache_variable.cv_1" + + name1 := fmt.Sprintf("tf_service_cache_variable_%s", acctest.RandString(5)) + svcn1 := "svc_1" + name2 := fmt.Sprintf("tf_service_cache_variable_updated_%s", acctest.RandString(5)) + svcn2 := "svc_2" + + config1 := ` + configuration { + type = "trigger_event_count" + ttl_seconds = 60 + } + ` + config2 := ` + configuration { + type = "recent_value" + source = "event.summary" + regex = ".*" + } + ` + cond1 := `` + cond2 := ` + condition { + expression = "event.source exists" + } + ` + disabled1 := "false" + disabled2 := "true" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckPagerDutyEventOrchestrationServiceCacheVariableDestroy, + Steps: []resource.TestStep{ + { + Config: testAccCheckPagerDutyEventOrchestrationServiceCacheVariableConfig(svc, name1, svcn1, disabled1, config1, cond1), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationServiceCacheVariableID(cv, svcn1), + resource.TestCheckResourceAttr(cv, "name", name1), + ), + }, + // update name and disabled state: + { + Config: testAccCheckPagerDutyEventOrchestrationServiceCacheVariableConfig(svc, name2, svcn1, disabled2, config1, cond1), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationServiceCacheVariableID(cv, svcn1), + resource.TestCheckResourceAttr(cv, "name", name2), + resource.TestCheckResourceAttr(cv, "disabled", disabled2), + ), + }, + // update config: + { + Config: testAccCheckPagerDutyEventOrchestrationServiceCacheVariableConfig(svc, name1, svcn1, disabled1, config2, cond1), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationServiceCacheVariableID(cv, svcn1), + resource.TestCheckResourceAttr(cv, "configuration.0.type", "recent_value"), + resource.TestCheckResourceAttr(cv, "configuration.0.source", "event.summary"), + resource.TestCheckResourceAttr(cv, "configuration.0.regex", ".*"), + ), + }, + // update condition: + { + Config: testAccCheckPagerDutyEventOrchestrationServiceCacheVariableConfig(svc, name1, svcn1, disabled1, config1, cond2), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationServiceCacheVariableID(cv, svcn1), + resource.TestCheckResourceAttr(cv, "condition.0.expression", "event.source exists"), + ), + }, + // update parent event orchestration: + { + Config: testAccCheckPagerDutyEventOrchestrationServiceCacheVariableConfig(svc, name1, svcn2, disabled1, config1, cond1), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationServiceCacheVariableID(cv, svcn2), + ), + }, + // delete cache variable: + { + Config: testAccCheckPagerDutyEventOrchestrationServiceCacheVariableDeletedConfig(svc), + Check: resource.ComposeTestCheckFunc( + testAccCheckPagerDutyEventOrchestrationServiceCacheVariableExistsNot(cv), + ), + }, + }, + }) +} + +func testAccCheckPagerDutyEventOrchestrationServiceCacheVariableDestroy(s *terraform.State) error { + client, _ := testAccProvider.Meta().(*Config).Client() + for _, r := range s.RootModule().Resources { + if r.Type != "pagerduty_event_orchestration_service_cache_variable" { + continue + } + if _, _, err := client.EventOrchestrationCacheVariables.GetContext(context.Background(), pagerduty.CacheVariableTypeService, r.Primary.Attributes["event_orchestration"], r.Primary.ID); err == nil { + return fmt.Errorf("Event Orchestration Cache Variables still exist") + } + } + return nil +} + +func testAccCheckPagerDutyEventOrchestrationServiceCacheVariableExistsNot(cv string) resource.TestCheckFunc { + return func(s *terraform.State) error { + _, ok := s.RootModule().Resources[cv] + if ok { + return fmt.Errorf("Event Orchestration Cache Variable is not deleted from the state: %s", cv) + } + + return nil + } +} + +func testAccCheckPagerDutyEventOrchestrationServiceCacheVariableID(cv, svcn string) resource.TestCheckFunc { + return func(s *terraform.State) error { + ir, ok := s.RootModule().Resources[cv] + svcr, _ := s.RootModule().Resources[fmt.Sprintf("pagerduty_service.%s", svcn)] + + if !ok { + return fmt.Errorf("Event Orchestration Cache Variable resource not found in the state: %s", cv) + } + + sid := ir.Primary.Attributes["service"] + id := ir.Primary.ID + + client, _ := testAccProvider.Meta().(*Config).Client() + i, _, err := client.EventOrchestrationCacheVariables.GetContext(context.Background(), pagerduty.CacheVariableTypeService, sid, id) + svc, _, _ := client.Services.Get(svcr.Primary.ID, &pagerduty.GetServiceOptions{}) + + if err != nil { + return err + } + + if i.ID != id { + return fmt.Errorf("Event Orchestration Cache Variable ID does not match the resource ID: %v - %v", i.ID, id) + } + + if svc.ID != sid { + return fmt.Errorf("Event Orchestration Cache Variable's parent ID does not match the resource service attr: %v - %v", svc.ID, sid) + } + + return nil + } +} + +func testAccCheckPagerDutyEventOrchestrationServiceCacheVariableConfig(svc, name, svcn string, disabled string, config string, cond string) string { + return fmt.Sprintf(` + resource "pagerduty_user" "user" { + email = "user@pagerduty.com" + name = "test user" + } + + resource "pagerduty_escalation_policy" "ep" { + name = "Test EP" + rule { + escalation_delay_in_minutes = 5 + target { + type = "user_reference" + id = pagerduty_user.user.id + } + } + } + + resource "pagerduty_service" "svc_1" { + name = "%s-1" + escalation_policy = pagerduty_escalation_policy.ep.id + } + + resource "pagerduty_service" "svc_2" { + name = "%s-2" + escalation_policy = pagerduty_escalation_policy.ep.id + } + + resource "pagerduty_event_orchestration_service_cache_variable" "cv_1" { + name = "%s" + service = pagerduty_service.%s.id + disabled = %s + + %s + + %s + } + `, svc, svc, name, svcn, disabled, config, cond) +} + +func testAccCheckPagerDutyEventOrchestrationServiceCacheVariableDeletedConfig(svc string) string { + return fmt.Sprintf(` + resource "pagerduty_user" "user" { + email = "user@pagerduty.com" + name = "test user" + } + + resource "pagerduty_escalation_policy" "ep" { + name = "Test EP" + rule { + escalation_delay_in_minutes = 5 + target { + type = "user_reference" + id = pagerduty_user.user.id + } + } + } + + resource "pagerduty_service" "svc_1" { + name = "%s-1" + escalation_policy = pagerduty_escalation_policy.ep.id + } + + resource "pagerduty_service" "svc_2" { + name = "%s-2" + escalation_policy = pagerduty_escalation_policy.ep.id + } + `, svc, svc) +}