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

Adds support for waiting for default service account in ns resource #2119

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
3 changes: 3 additions & 0 deletions .changelog/2119.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:feature
`kubernetes/resource_kubernetes_namespace.go`: Add attribute `wait_for_default_service_account` to namespaces which will force Terraform to wait until the default service account has been created by Kubernetes on namespace creation.
```
26 changes: 26 additions & 0 deletions kubernetes/resource_kubernetes_namespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ func resourceKubernetesNamespace() *schema.Resource {

Schema: map[string]*schema.Schema{
"metadata": metadataSchema("namespace", true),
"wait_for_default_service_account": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Terraform will wait for the default service account to be created.",
},
},
Timeouts: &schema.ResourceTimeout{
Delete: schema.DefaultTimeout(5 * time.Minute),
Expand All @@ -56,6 +62,26 @@ func resourceKubernetesNamespaceCreate(ctx context.Context, d *schema.ResourceDa
log.Printf("[INFO] Submitted new namespace: %#v", out)
d.SetId(out.Name)

if d.Get("wait_for_default_service_account").(bool) {
log.Printf("[DEBUG] Waiting for default service account to be created")
err = resource.RetryContext(ctx, d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
_, err := conn.CoreV1().ServiceAccounts(out.Name).Get(ctx, "default", metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
log.Printf("[INFO] Default service account does not exist, will retry: %s", metadata.Namespace)
return resource.RetryableError(err)
}

return resource.NonRetryableError(err)
}

log.Printf("[INFO] Default service account exists: %s", metadata.Namespace)
return nil
})
if err != nil {
return diag.FromErr(err)
}
}
return resourceKubernetesNamespaceRead(ctx, d, meta)
}

Expand Down
72 changes: 70 additions & 2 deletions kubernetes/resource_kubernetes_namespace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func TestAccKubernetesNamespace_basic(t *testing.T) {
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"metadata.0.resource_version"},
ImportStateVerifyIgnore: []string{"metadata.0.resource_version", "wait_for_default_service_account"},
},
{
Config: testAccKubernetesNamespaceConfig_addAnnotations(nsName),
Expand Down Expand Up @@ -109,6 +109,35 @@ func TestAccKubernetesNamespace_basic(t *testing.T) {
})
}

func TestAccKubernetesNamespace_default_service_account(t *testing.T) {
var nsConf api.Namespace
var saConf api.ServiceAccount
nsName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
resourceName := "kubernetes_namespace.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: resourceName,
ProviderFactories: testAccProviderFactories,
CheckDestroy: testAccCheckKubernetesNamespaceDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesNamespaceConfig_wait_for_default_service_acccount(nsName),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesNamespaceExists("kubernetes_namespace.test", &nsConf),
testAccCheckKubernetesDefaultServiceAccountExists(resourceName, &saConf),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"metadata.0.resource_version", "wait_for_default_service_account"},
},
},
})
}

func TestAccKubernetesNamespace_generatedName(t *testing.T) {
var conf api.Namespace
prefix := "tf-acc-test-gen-"
Expand Down Expand Up @@ -138,7 +167,7 @@ func TestAccKubernetesNamespace_generatedName(t *testing.T) {
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"metadata.0.resource_version"},
ImportStateVerifyIgnore: []string{"metadata.0.resource_version", "wait_for_default_service_account"},
},
},
})
Expand Down Expand Up @@ -363,3 +392,42 @@ func testAccKubernetesNamespaceConfig_deleteTimeout(nsName string) string {
}
`, nsName)
}

func testAccKubernetesNamespaceConfig_wait_for_default_service_acccount(nsName string) string {
return fmt.Sprintf(`resource "kubernetes_namespace" "test" {
metadata {
name = "%s"
}
wait_for_default_service_account = "true"
}
`, nsName)
}

func testAccCheckKubernetesDefaultServiceAccountExists(n string,
obj *api.ServiceAccount) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}

conn, err := testAccProvider.Meta().(KubeClientsets).MainClientset()
if err != nil {
return err
}
ctx := context.TODO()

namespace, _, err := idParts(rs.Primary.ID + "/")
if err != nil {
return err
}

out, err := conn.CoreV1().ServiceAccounts(namespace).Get(ctx, "default", metav1.GetOptions{})
if err != nil {
return err
}

*obj = *out
return nil
}
}
8 changes: 8 additions & 0 deletions website/docs/d/namespace.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,11 @@ The following arguments are supported:
#### Attributes

* `finalizers` - An opaque list of values that must be empty to permanently remove object from storage. For more info: https://kubernetes.io/docs/tasks/administer-cluster/namespaces/

## Attribute Reference

* `wait_for_default_service_account` - (Optional) When set to `true` Terraform will wait until the
default service account has been asynchronously created by Kubernetes when creating the namespace resource.
This has the equivalent effect of creating a `resource_kubernetes_default_service_account` resource for dependent resources
but allows a user to consume the "default" service account directly.
The default behaviour (`false`) does not wait for the default service account to exist.