Skip to content

Commit a11b175

Browse files
Cloud Stack: Allow importing by slug (#859)
This will be useful for Crossplane where we'll be able to provide the slug and it will either create a new stack OR bring an existing one into management
1 parent 24d7863 commit a11b175

File tree

4 files changed

+25
-3
lines changed

4 files changed

+25
-3
lines changed

docs/resources/cloud_stack.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,5 +73,6 @@ available at “https://<stack_slug>.grafana.net".
7373
Import is supported using the following syntax:
7474

7575
```shell
76-
terraform import grafana_cloud_stack.stack_name {{stack_id}}
76+
terraform import grafana_cloud_stack.stack_name {{stack_id}} // import by numerical ID
77+
terraform import grafana_cloud_stack.stack_name {{stack_slug}} // or import by slug
7778
```
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
terraform import grafana_cloud_stack.stack_name {{stack_id}}
1+
terraform import grafana_cloud_stack.stack_name {{stack_id}} // import by numerical ID
2+
terraform import grafana_cloud_stack.stack_name {{stack_slug}} // or import by slug

internal/resources/cloud/resource_cloud_stack.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,21 @@ func ResourceStack() *schema.Resource {
3737
DeleteContext: DeleteStack,
3838
ReadContext: ReadStack,
3939

40+
// Import either by ID or slug
4041
Importer: &schema.ResourceImporter{
41-
StateContext: schema.ImportStatePassthroughContext,
42+
StateContext: func(c context.Context, rd *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
43+
_, err := strconv.ParseInt(rd.Id(), 10, 64)
44+
if err != nil {
45+
// If the ID is not a number, then it may be a slug
46+
client := meta.(*common.Client).GrafanaCloudAPI
47+
stack, err := client.StackBySlug(rd.Id())
48+
if err != nil {
49+
return nil, fmt.Errorf("failed to find stack by ID or slug '%s': %w", rd.Id(), err)
50+
}
51+
rd.SetId(strconv.FormatInt(stack.ID, 10))
52+
}
53+
return []*schema.ResourceData{rd}, nil
54+
},
4255
},
4356

4457
Schema: map[string]*schema.Schema{

internal/resources/cloud/resource_cloud_stack_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,13 @@ func TestResourceStack_Basic(t *testing.T) {
7979
ImportState: true,
8080
ImportStateVerify: true,
8181
},
82+
// Test import from slug
83+
{
84+
ResourceName: "grafana_cloud_stack.test",
85+
ImportStateId: resourceName,
86+
ImportState: true,
87+
ImportStateVerify: true,
88+
},
8289
},
8390
})
8491
}

0 commit comments

Comments
 (0)