Skip to content
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

Data pagerduty automation actions runner #1

Merged
merged 22 commits into from
Dec 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@ require (
google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb // indirect
google.golang.org/grpc v1.33.2 // indirect
)

replace github.com/heimweh/go-pagerduty => github.com/mrdubr/go-pagerduty v0.0.0-20221207010513-91b73ec9ea69
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,8 @@ github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
github.com/montanaflynn/stats v0.6.6 h1:Duep6KMIDpY4Yo11iFsvyqJDyfzLF9+sndUKT+v64GQ=
github.com/montanaflynn/stats v0.6.6/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
github.com/mrdubr/go-pagerduty v0.0.0-20221207010513-91b73ec9ea69 h1:xNq1ArQXzUwNoWuUw3I4hIxCe52eXJOZ3o1XrubwT4s=
github.com/mrdubr/go-pagerduty v0.0.0-20221207010513-91b73ec9ea69/go.mod h1:t9vftsO1IjYHGdgJXeemZtomCWnxi2SRgu0PRcRb2oY=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/nsf/jsondiff v0.0.0-20200515183724-f29ed568f4ce h1:RPclfga2SEJmgMmz2k+Mg7cowZ8yv4Trqw9UsJby758=
github.com/nsf/jsondiff v0.0.0-20200515183724-f29ed568f4ce/go.mod h1:uFMI8w+ref4v2r9jz+c9i1IfIttS/OkmLfrk1jne5hs=
Expand Down
39 changes: 38 additions & 1 deletion pagerduty/data_source_pagerduty_automation_actions_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func dataSourcePagerdutyAutomationActionsRunner() *schema.Resource {
func dataSourcePagerDutyAutomationActionsRunner() *schema.Resource {
return &schema.Resource{
Read: dataSourcePagerDutyAutomationActionsRunnerRead,

Expand All @@ -25,6 +25,29 @@ func dataSourcePagerdutyAutomationActionsRunner() *schema.Resource {
Type: schema.TypeString,
Computed: true,
},
"runner_type": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"last_seen": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"runbook_base_uri": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
},
}
}
Expand All @@ -49,6 +72,20 @@ func dataSourcePagerDutyAutomationActionsRunnerRead(d *schema.ResourceData, meta
d.SetId(runner.ID)
d.Set("name", runner.Name)
d.Set("type", runner.Type)
d.Set("runner_type", runner.RunnerType)
d.Set("creation_time", runner.CreationTime)

if runner.Description != nil {
d.Set("description", &runner.Description)
}

if runner.RunbookBaseUri != nil {
d.Set("runbook_base_uri", &runner.RunbookBaseUri)
}

if runner.LastSeenTime != nil {
d.Set("last_seen", &runner.LastSeenTime)
}

return nil
})
Expand Down
41 changes: 32 additions & 9 deletions pagerduty/data_source_pagerduty_automation_actions_runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,45 +4,68 @@ import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccDataSourcePagerDutyAutomationActionsRunner_Basic(t *testing.T) {
name := fmt.Sprintf("tf-%s", acctest.RandString(5))

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccDataSourcePagerDutyAutomationActionsRunnerConfig("01DCTHG8L7X4BDEQG3OQO2HZCN"),
Config: testAccDataSourcePagerDutyAutomationActionsRunnerConfig(name),
Check: resource.ComposeTestCheckFunc(
testAccCheckPagerdutyAutomationActionsRunnerExists("data.pagerduty_automation_actions_runner.foo"),
testAccDataSourcePagerdutyAutomationActionsRunner("pagerduty_automation_actions_runner.test", "data.pagerduty_automation_actions_runner.foo"),
),
},
},
})
}

func testAccCheckPagerdutyAutomationActionsRunnerExists(n string) resource.TestCheckFunc {
func testAccDataSourcePagerdutyAutomationActionsRunner(src, n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
// client, _ := testAccProvider.Meta().(*Config).Client()

rs, ok := s.RootModule().Resources[n]
srcR := s.RootModule().Resources[src]
srcA := srcR.Primary.Attributes

ds, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
dsA := ds.Primary.Attributes

if dsA["id"] == "" {
return fmt.Errorf("No Runner ID is set")
}

testAtts := []string{"id", "name", "type", "runner_type", "creation_time", "last_seen", "description", "runbook_base_uri"}

for _, att := range testAtts {
if dsA[att] != srcA[att] {
return fmt.Errorf("Expected the runner %s to be: %s, but got: %s", att, srcA[att], dsA[att])
}
}

return nil
}
}

func testAccDataSourcePagerDutyAutomationActionsRunnerConfig(id string) string {
func testAccDataSourcePagerDutyAutomationActionsRunnerConfig(name string) string {
return fmt.Sprintf(`
resource "pagerduty_automation_actions_runner" "test" {
name = "%s"
description = "Runner created by TF"
runner_type = "runbook"
runbook_base_uri = "cat-cat"
runbook_api_key = "secret"
}

data "pagerduty_automation_actions_runner" "foo" {
id = "%s"
id = pagerduty_automation_actions_runner.test.id
}
`, id)
`, name)
}
30 changes: 30 additions & 0 deletions pagerduty/import_pagerduty_automation_actions_runner_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package pagerduty

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccPagerDutyAutomationActionsRunner_import(t *testing.T) {
runnerName := fmt.Sprintf("tf-%s", acctest.RandString(5))

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckPagerDutyAutomationActionsRunnerDestroy,
Steps: []resource.TestStep{
{
Config: testAccCheckPagerDutyAutomationActionsRunnerConfig(runnerName),
},
{
ResourceName: "pagerduty_automation_actions_runner.foo",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"runbook_api_key"},
},
},
})
}
3 changes: 2 additions & 1 deletion pagerduty/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func Provider() *schema.Provider {
"pagerduty_ruleset": dataSourcePagerDutyRuleset(),
"pagerduty_tag": dataSourcePagerDutyTag(),
"pagerduty_event_orchestration": dataSourcePagerDutyEventOrchestration(),
"pagerduty_automation_actions_runner": dataSourcePagerdutyAutomationActionsRunner(),
"pagerduty_automation_actions_runner": dataSourcePagerDutyAutomationActionsRunner(),
},

ResourcesMap: map[string]*schema.Resource{
Expand Down Expand Up @@ -94,6 +94,7 @@ func Provider() *schema.Provider {
"pagerduty_event_orchestration_router": resourcePagerDutyEventOrchestrationPathRouter(),
"pagerduty_event_orchestration_unrouted": resourcePagerDutyEventOrchestrationPathUnrouted(),
"pagerduty_event_orchestration_service": resourcePagerDutyEventOrchestrationPathService(),
"pagerduty_automation_actions_runner": resourcePagerDutyAutomationActionsRunner(),
},
}

Expand Down
196 changes: 196 additions & 0 deletions pagerduty/resource_pagerduty_automation_actions_runner.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
package pagerduty

import (
"errors"
"log"
"time"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/heimweh/go-pagerduty/pagerduty"
)

func resourcePagerDutyAutomationActionsRunner() *schema.Resource {
return &schema.Resource{
Create: resourcePagerDutyAutomationActionsRunnerCreate,
Read: resourcePagerDutyAutomationActionsRunnerRead,
Delete: resourcePagerDutyAutomationActionsRunnerDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true, // Requires creation of new resource while support for update is not implemented
},
"runner_type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateValueFunc([]string{
"sidecar",
"runbook",
}),
ForceNew: true, // Requires creation of new resource while support for update is not implemented
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true, // Requires creation of new resource while support for update is not implemented
},
"runbook_base_uri": {
Type: schema.TypeString,
Optional: true,
ForceNew: true, // Requires creation of new resource while support for update is not implemented
},
"runbook_api_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true, // Requires creation of new resource while support for update is not implemented
Sensitive: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"creation_time": {
Type: schema.TypeString,
Computed: true,
},
"last_seen": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
},
}
}

func buildAutomationActionsRunnerStruct(d *schema.ResourceData) (*pagerduty.AutomationActionsRunner, error) {

automationActionsRunner := pagerduty.AutomationActionsRunner{
Name: d.Get("name").(string),
RunnerType: d.Get("runner_type").(string),
}

if automationActionsRunner.RunnerType != "runbook" {
return nil, errors.New("only runners of runner_type runbook can be created")
}

// The API does not allow new runners without a description, but legacy runners without a description exist
if attr, ok := d.GetOk("description"); ok {
val := attr.(string)
automationActionsRunner.Description = &val
} else {
return nil, errors.New("runner description must be specified when creating a runbook runner")
}

if attr, ok := d.GetOk("runbook_base_uri"); ok {
val := attr.(string)
automationActionsRunner.RunbookBaseUri = &val
} else {
return nil, errors.New("runbook_base_uri must be specified when creating a runbook runner")
}

if attr, ok := d.GetOk("runbook_api_key"); ok {
val := attr.(string)
automationActionsRunner.RunbookApiKey = &val
} else {
return nil, errors.New("runbook_api_key must be specified when creating a runbook runner")
}

return &automationActionsRunner, nil
}

func resourcePagerDutyAutomationActionsRunnerCreate(d *schema.ResourceData, meta interface{}) error {
client, err := meta.(*Config).Client()
if err != nil {
return err
}

automationActionsRunner, err := buildAutomationActionsRunnerStruct(d)
if err != nil {
return err
}

log.Printf("[INFO] Creating PagerDuty AutomationActionsRunner %s", automationActionsRunner.Name)

retryErr := resource.Retry(10*time.Second, func() *resource.RetryError {
if automationActionsRunner, _, err := client.AutomationActionsRunner.Create(automationActionsRunner); err != nil {
if isErrCode(err, 400) || isErrCode(err, 429) {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
}

return resource.NonRetryableError(err)
} else if automationActionsRunner != nil {
d.SetId(automationActionsRunner.ID)
}
return nil
})

if retryErr != nil {
return retryErr
}

return resourcePagerDutyAutomationActionsRunnerRead(d, meta)
}

func resourcePagerDutyAutomationActionsRunnerRead(d *schema.ResourceData, meta interface{}) error {
client, err := meta.(*Config).Client()
if err != nil {
return err
}

log.Printf("[INFO] Reading PagerDuty AutomationActionsRunner %s", d.Id())

return resource.Retry(30*time.Second, func() *resource.RetryError {
if automationActionsRunner, _, err := client.AutomationActionsRunner.Get(d.Id()); err != nil {
time.Sleep(2 * time.Second)
return resource.RetryableError(err)
} else if automationActionsRunner != nil {
d.Set("name", automationActionsRunner.Name)
d.Set("type", automationActionsRunner.Type)
d.Set("runner_type", automationActionsRunner.RunnerType)
d.Set("creation_time", automationActionsRunner.CreationTime)

if automationActionsRunner.Description != nil {
d.Set("description", &automationActionsRunner.Description)
}

if automationActionsRunner.RunbookBaseUri != nil {
d.Set("runbook_base_uri", &automationActionsRunner.RunbookBaseUri)
}

if automationActionsRunner.LastSeenTime != nil {
d.Set("last_seen", &automationActionsRunner.LastSeenTime)
}
}
return nil
})
}

func resourcePagerDutyAutomationActionsRunnerDelete(d *schema.ResourceData, meta interface{}) error {
client, err := meta.(*Config).Client()
if err != nil {
return err
}

log.Printf("[INFO] Deleting PagerDuty AutomationActionsRunner %s", d.Id())

retryErr := resource.Retry(2*time.Minute, func() *resource.RetryError {
if _, err := client.AutomationActionsRunner.Delete(d.Id()); err != nil {
return resource.RetryableError(err)
}
return nil
})
if retryErr != nil {
time.Sleep(2 * time.Second)
return retryErr
}
d.SetId("")

// giving the API time to catchup
time.Sleep(time.Second)
return nil
}
Loading