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

Add DaemonSet and ClusterRole resources #229

Merged
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 kubernetes/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,10 @@ func Provider() terraform.ResourceProvider {
},

ResourcesMap: map[string]*schema.Resource{
"kubernetes_cluster_role": resourceKubernetesClusterRole(),
"kubernetes_cluster_role_binding": resourceKubernetesClusterRoleBinding(),
"kubernetes_config_map": resourceKubernetesConfigMap(),
"kubernetes_daemonset": resourceKubernetesDaemonSet(),
"kubernetes_deployment": resourceKubernetesDeployment(),
"kubernetes_horizontal_pod_autoscaler": resourceKubernetesHorizontalPodAutoscaler(),
"kubernetes_limit_range": resourceKubernetesLimitRange(),
Expand Down
136 changes: 136 additions & 0 deletions kubernetes/resource_kubernetes_cluster_role.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
package kubernetes

import (
"fmt"
"log"

"github.com/hashicorp/terraform/helper/schema"
api "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
pkgApi "k8s.io/apimachinery/pkg/types"
kubernetes "k8s.io/client-go/kubernetes"
)

func resourceKubernetesClusterRole() *schema.Resource {
return &schema.Resource{
Create: resourceKubernetesClusterRoleCreate,
Read: resourceKubernetesClusterRoleRead,
Exists: resourceKubernetesClusterRoleExists,
Update: resourceKubernetesClusterRoleUpdate,
Delete: resourceKubernetesClusterRoleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"metadata": metadataSchema("clusterRole", false),
"rule": {
Type: schema.TypeList,
Description: "List of PolicyRules for this ClusterRole",
Required: true,
MinItems: 1,
Elem: &schema.Resource{
Schema: policyRuleSchema(),
},
},
},
}
}

func resourceKubernetesClusterRoleCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*kubernetes.Clientset)

metadata := expandMetadata(d.Get("metadata").([]interface{}))
cRole := api.ClusterRole{
ObjectMeta: metadata,
Rules: expandClusterRoleRules(d.Get("rule").([]interface{})),
}
log.Printf("[INFO] Creating new cluster role: %#v", cRole)
out, err := conn.RbacV1().ClusterRoles().Create(&cRole)
if err != nil {
return err
}
log.Printf("[INFO] Submitted new cluster role: %#v", out)
d.SetId(out.Name)

return resourceKubernetesClusterRoleRead(d, meta)
}

func resourceKubernetesClusterRoleUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*kubernetes.Clientset)

name := d.Id()
ops := patchMetadata("metadata.0.", "/metadata/", d)
if d.HasChange("rule") {
diffOps := patchRbacRule(d)
ops = append(ops, diffOps...)
}
data, err := ops.MarshalJSON()
if err != nil {
return fmt.Errorf("Failed to marshal update operations: %s", err)
}
log.Printf("[INFO] Updating ClusterRole %q: %v", name, string(data))
out, err := conn.Rbac().ClusterRoles().Patch(name, pkgApi.JSONPatchType, data)
if err != nil {
return fmt.Errorf("Failed to update ClusterRole: %s", err)
}
log.Printf("[INFO] Submitted updated ClusterRole: %#v", out)
d.SetId(out.ObjectMeta.Name)

return resourceKubernetesClusterRoleRead(d, meta)
}

func resourceKubernetesClusterRoleRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*kubernetes.Clientset)

name := d.Id()
log.Printf("[INFO] Reading cluster role %s", name)
cRole, err := conn.RbacV1().ClusterRoles().Get(name, metav1.GetOptions{})
if err != nil {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here, we need more elaborate handling of err.
In particular, in case the error is of a NotFound kind, the ID of the resource should be set to d.SetId("") and no error should be returned. This instructs Terraform to remove the resource from the state.
You can check the type of error returned in err by using these client-go helper functions: https://godoc.org/k8s.io/apimachinery/pkg/api/errors

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

if errors.IsNotFound(err) {
d.SetId("")
return nil
}
log.Printf("[DEBUG] Received error: %#v", err)
return err
}
log.Printf("[INFO] Received cluster role: %#v", cRole)
err = d.Set("metadata", flattenMetadata(cRole.ObjectMeta))
if err != nil {
return err
}
d.Set("rule", flattenClusterRoleRules(cRole.Rules))

return nil
}

func resourceKubernetesClusterRoleDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*kubernetes.Clientset)

name := d.Id()
log.Printf("[INFO] Deleting cluster role: %#v", name)
err := conn.RbacV1().ClusterRoles().Delete(name, &metav1.DeleteOptions{})
if err != nil {
return err
}

log.Printf("[INFO] cluster role %s deleted", name)

return nil
}

func resourceKubernetesClusterRoleExists(d *schema.ResourceData, meta interface{}) (bool, error) {
conn := meta.(*kubernetes.Clientset)

name := d.Id()
log.Printf("[INFO] Checking cluster role %s", name)
_, err := conn.RbacV1().ClusterRoles().Get(name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
return false, nil
}
log.Printf("[DEBUG] Received error: %#v", err)
}
return true, err
}
150 changes: 150 additions & 0 deletions kubernetes/resource_kubernetes_cluster_role_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
package kubernetes

import (
"fmt"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
api "k8s.io/api/rbac/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kubernetes "k8s.io/client-go/kubernetes"
"testing"
)

func TestAccKubernetesClusterRole_basic(t *testing.T) {
var conf api.ClusterRole
name := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
IDRefreshName: "kubernetes_cluster_role.test",
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesClusterRoleDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesClusterRoleConfig_basic(name),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesClusterRoleExists("kubernetes_cluster_role.test", &conf),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.#", "1"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.0.resources.#", "2"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.0.resources.0", "pods"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.0.resources.1", "pods/log"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.0.verbs.#", "2"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.0.verbs.0", "get"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.0.verbs.1", "list"),
),
},
{
Config: testAccKubernetesClusterRoleConfig_modified(name),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckKubernetesClusterRoleExists("kubernetes_cluster_role.test", &conf),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.#", "2"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.0.verbs.#", "3"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.0.verbs.2", "watch"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.1.api_groups.#", "1"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.1.resources.#", "1"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.1.resources.0", "deployments"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.1.verbs.#", "2"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.1.verbs.0", "get"),
resource.TestCheckResourceAttr("kubernetes_cluster_role.test", "rule.1.verbs.1", "list"),
),
},
},
})
}
func TestAccKubernetesClusterRole_importBasic(t *testing.T) {
resourceName := "kubernetes_cluster_role.test"
name := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckKubernetesClusterRoleDestroy,
Steps: []resource.TestStep{
{
Config: testAccKubernetesClusterRoleConfig_basic(name),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"metadata.0.resource_version"},
},
},
})
}
func testAccCheckKubernetesClusterRoleDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*kubernetes.Clientset)
for _, rs := range s.RootModule().Resources {
if rs.Type != "kubernetes_cluster_role" {
continue
}
resp, err := conn.RbacV1().ClusterRoles().Get(rs.Primary.ID, meta_v1.GetOptions{})
if err == nil {
if resp.Name == rs.Primary.ID {
return fmt.Errorf("Cluster Role still exists: %s", rs.Primary.ID)
}
}
}
return nil
}
func testAccCheckKubernetesClusterRoleExists(n string, obj *api.ClusterRole) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
conn := testAccProvider.Meta().(*kubernetes.Clientset)
out, err := conn.RbacV1().ClusterRoles().Get(rs.Primary.ID, meta_v1.GetOptions{})
if err != nil {
return err
}
*obj = *out
return nil
}
}
func testAccKubernetesClusterRoleConfig_basic(name string) string {
return fmt.Sprintf(`
resource "kubernetes_cluster_role" "test" {
metadata {
labels {
TestLabelOne = "one"
TestLabelTwo = "two"
TestLabelThree = "three"
}

name = "%s"
}

rule {
api_groups = [""]
resources = ["pods", "pods/log"]
verbs = ["get", "list"]
}
}
`, name)
}
func testAccKubernetesClusterRoleConfig_modified(name string) string {
return fmt.Sprintf(`
resource "kubernetes_cluster_role" "test" {
metadata {
labels {
TestLabelOne = "one"
TestLabelThree = "three"
}

name = "%s"
}

rule {
api_groups = [""]
resources = ["pods", "pods/log"]
verbs = ["get", "list", "watch"]
}

rule {
api_groups = [""]
resources = ["deployments"]
verbs = ["get", "list"]
}
}
`, name)
}
Loading