From ee66cdaabbc2a182685a4915d2b3892baf0ef60b Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Sat, 10 Feb 2018 19:34:03 +0100 Subject: [PATCH 01/17] Add kubernetes_network_policy resource --- kubernetes/provider.go | 1 + .../resource_kubernetes_network_policy.go | 232 +++++++++++++++ ...resource_kubernetes_network_policy_test.go | 272 ++++++++++++++++++ kubernetes/structure_network_policy.go | 159 ++++++++++ 4 files changed, 664 insertions(+) create mode 100644 kubernetes/resource_kubernetes_network_policy.go create mode 100644 kubernetes/resource_kubernetes_network_policy_test.go create mode 100644 kubernetes/structure_network_policy.go diff --git a/kubernetes/provider.go b/kubernetes/provider.go index 47aa912af0..d4c7efca66 100644 --- a/kubernetes/provider.go +++ b/kubernetes/provider.go @@ -116,6 +116,7 @@ func Provider() terraform.ResourceProvider { "kubernetes_horizontal_pod_autoscaler": resourceKubernetesHorizontalPodAutoscaler(), "kubernetes_limit_range": resourceKubernetesLimitRange(), "kubernetes_namespace": resourceKubernetesNamespace(), + "kubernetes_network_policy": resourceKubernetesNetworkPolicy(), "kubernetes_persistent_volume": resourceKubernetesPersistentVolume(), "kubernetes_persistent_volume_claim": resourceKubernetesPersistentVolumeClaim(), "kubernetes_pod": resourceKubernetesPod(), diff --git a/kubernetes/resource_kubernetes_network_policy.go b/kubernetes/resource_kubernetes_network_policy.go new file mode 100644 index 0000000000..5cc8ffd4e7 --- /dev/null +++ b/kubernetes/resource_kubernetes_network_policy.go @@ -0,0 +1,232 @@ +package kubernetes + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" + "k8s.io/apimachinery/pkg/api/errors" + meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + pkgApi "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/kubernetes" + api "k8s.io/client-go/pkg/apis/networking/v1" +) + +// Use generated swagger docs from kubernetes' client-go to avoid copy/pasting them here +var ( + networkPolicySpecDoc = api.NetworkPolicy{}.SwaggerDoc()["spec"] + networkPolicySpecIngressDoc = api.NetworkPolicySpec{}.SwaggerDoc()["ingress"] + networkPolicyIngressRulePortsDoc = api.NetworkPolicyIngressRule{}.SwaggerDoc()["ports"] + networkPolicyPortPortDoc = api.NetworkPolicyPort{}.SwaggerDoc()["port"] + networkPolicyPortProtocolDoc = api.NetworkPolicyPort{}.SwaggerDoc()["protocol"] + networkPolicyIngressRuleFromDoc = api.NetworkPolicyIngressRule{}.SwaggerDoc()["from"] + networkPolicyPeerNamespaceSelectorDoc = api.NetworkPolicyPeer{}.SwaggerDoc()["namespaceSelector"] + networkPolicyPeerPodSelectorDoc = api.NetworkPolicyPeer{}.SwaggerDoc()["podSelector"] + networkPolicySpecPodSelectorDoc = api.NetworkPolicySpec{}.SwaggerDoc()["podSelector"] +) + +func resourceKubernetesNetworkPolicy() *schema.Resource { + return &schema.Resource{ + Create: resourceKubernetesNetworkPolicyCreate, + Read: resourceKubernetesNetworkPolicyRead, + Exists: resourceKubernetesNetworkPolicyExists, + Update: resourceKubernetesNetworkPolicyUpdate, + Delete: resourceKubernetesNetworkPolicyDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "metadata": namespacedMetadataSchema("network policy", true), + "spec": { + Type: schema.TypeList, + Description: networkPolicySpecDoc, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ingress": { + Type: schema.TypeList, + Description: networkPolicySpecIngressDoc, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ports": { + Type: schema.TypeList, + Description: networkPolicyIngressRulePortsDoc, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "port": { + Type: schema.TypeString, + Description: networkPolicyPortPortDoc, + Optional: true, + }, + "protocol": { + Type: schema.TypeString, + Description: networkPolicyPortProtocolDoc, + Optional: true, + }, + }, + }, + }, + "from": { + Type: schema.TypeList, + Description: networkPolicyIngressRuleFromDoc, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "namespace_selector": { + Type: schema.TypeList, + Description: networkPolicyPeerNamespaceSelectorDoc, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: labelSelectorFields(), + }, + }, + "pod_selector": { + Type: schema.TypeList, + Description: networkPolicyPeerPodSelectorDoc, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: labelSelectorFields(), + }, + }, + }, + }, + }, + }, + }, + }, + "pod_selector": { + Type: schema.TypeList, + Description: networkPolicySpecPodSelectorDoc, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: labelSelectorFields(), + }, + }, + }, + }, + }, + }, + } +} + +func resourceKubernetesNetworkPolicyCreate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + metadata := expandMetadata(d.Get("metadata").([]interface{})) + svc := api.NetworkPolicy{ + ObjectMeta: metadata, + Spec: expandNetworkPolicySpec(d.Get("spec").([]interface{})), + } + log.Printf("[INFO] Creating new network policy: %#v", svc) + out, err := conn.NetworkingV1().NetworkPolicies(metadata.Namespace).Create(&svc) + if err != nil { + return err + } + + log.Printf("[INFO] Submitted new network policy: %#v", out) + d.SetId(buildId(out.ObjectMeta)) + + return resourceKubernetesNetworkPolicyRead(d, meta) +} + +func resourceKubernetesNetworkPolicyRead(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name, err := idParts(d.Id()) + if err != nil { + return err + } + log.Printf("[INFO] Reading network policy %s", name) + svc, err := conn.NetworkingV1().NetworkPolicies(namespace).Get(name, meta_v1.GetOptions{}) + if err != nil { + log.Printf("[DEBUG] Received error: %#v", err) + return err + } + log.Printf("[INFO] Received network policy: %#v", svc) + err = d.Set("metadata", flattenMetadata(svc.ObjectMeta)) + if err != nil { + return err + } + + flattened := flattenNetworkPolicySpec(svc.Spec) + log.Printf("[DEBUG] Flattened network policy spec: %#v", flattened) + err = d.Set("spec", flattened) + if err != nil { + return err + } + + return nil +} + +func resourceKubernetesNetworkPolicyUpdate(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name, err := idParts(d.Id()) + if err != nil { + return err + } + + ops := patchMetadata("metadata.0.", "/metadata/", d) + if d.HasChange("spec") { + diffOps := patchNetworkPolicySpec("spec.0.", "/spec", 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 network policy %q: %v", name, string(data)) + out, err := conn.NetworkingV1().NetworkPolicies(namespace).Patch(name, pkgApi.JSONPatchType, data) + if err != nil { + return fmt.Errorf("Failed to update network policy: %s", err) + } + log.Printf("[INFO] Submitted updated network policy: %#v", out) + d.SetId(buildId(out.ObjectMeta)) + + return resourceKubernetesNetworkPolicyRead(d, meta) +} + +func resourceKubernetesNetworkPolicyDelete(d *schema.ResourceData, meta interface{}) error { + conn := meta.(*kubernetes.Clientset) + + namespace, name, err := idParts(d.Id()) + if err != nil { + return err + } + log.Printf("[INFO] Deleting network policy: %#v", name) + err = conn.NetworkingV1().NetworkPolicies(namespace).Delete(name, &meta_v1.DeleteOptions{}) + if err != nil { + return err + } + + log.Printf("[INFO] Network Policy %s deleted", name) + + d.SetId("") + return nil +} + +func resourceKubernetesNetworkPolicyExists(d *schema.ResourceData, meta interface{}) (bool, error) { + conn := meta.(*kubernetes.Clientset) + + namespace, name, err := idParts(d.Id()) + if err != nil { + return false, err + } + + log.Printf("[INFO] Checking network policy %s", name) + _, err = conn.NetworkingV1().NetworkPolicies(namespace).Get(name, meta_v1.GetOptions{}) + if err != nil { + if statusErr, ok := err.(*errors.StatusError); ok && statusErr.ErrStatus.Code == 404 { + return false, nil + } + log.Printf("[DEBUG] Received error: %#v", err) + } + return true, err +} diff --git a/kubernetes/resource_kubernetes_network_policy_test.go b/kubernetes/resource_kubernetes_network_policy_test.go new file mode 100644 index 0000000000..d132a4bed8 --- /dev/null +++ b/kubernetes/resource_kubernetes_network_policy_test.go @@ -0,0 +1,272 @@ +package kubernetes + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + kubernetes "k8s.io/client-go/kubernetes" + api "k8s.io/client-go/pkg/apis/networking/v1" +) + +func TestAccKubernetesNetworkPolicy_basic(t *testing.T) { + var conf api.NetworkPolicy + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_network_policy.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesNetworkPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesNetworkPolicyConfig_basic(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesNetworkPolicyExists("kubernetes_network_policy.test", &conf), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.annotations.%", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.annotations.TestAnnotationOne", "one"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one"}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.%", "3"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.TestLabelThree", "three"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.TestLabelFour", "four"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelThree": "three", "TestLabelFour": "four"}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.#", "0"), + ), + }, + { + Config: testAccKubernetesNetworkPolicyConfig_metaModified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesNetworkPolicyExists("kubernetes_network_policy.test", &conf), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.annotations.%", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.annotations.TestAnnotationOne", "one"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.annotations.TestAnnotationTwo", "two"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{"TestAnnotationOne": "one", "TestAnnotationTwo": "two"}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.%", "3"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.TestLabelOne", "one"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.TestLabelTwo", "two"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.TestLabelThree", "three"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{"TestLabelOne": "one", "TestLabelTwo": "two", "TestLabelThree": "three"}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.#", "0"), + ), + }, + { + Config: testAccKubernetesNetworkPolicyConfig_specModified(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesNetworkPolicyExists("kubernetes_network_policy.test", &conf), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.key", "name"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.operator", "In"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.1742479128", "webfront"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.2902841359", "api"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.0.port", "http"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.0.protocol", "TCP"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.port", "8125"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.protocol", "UDP"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.namespace_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.namespace_selector.0.match_labels.name", "default"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.#", "0"), + ), + }, + }, + }) +} + +func TestAccKubernetesNetworkPolicy_importBasic(t *testing.T) { + resourceName := "kubernetes_network_policy.test" + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesNetworkPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesNetworkPolicyConfig_basic(name), + }, + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccCheckKubernetesNetworkPolicyDestroy(s *terraform.State) error { + conn := testAccProvider.Meta().(*kubernetes.Clientset) + + for _, rs := range s.RootModule().Resources { + if rs.Type != "kubernetes_network_policy" { + continue + } + + namespace, name, err := idParts(rs.Primary.ID) + if err != nil { + return err + } + + resp, err := conn.NetworkingV1().NetworkPolicies(namespace).Get(name, meta_v1.GetOptions{}) + if err == nil { + if resp.Namespace == namespace && resp.Name == name { + return fmt.Errorf("Network Policy still exists: %s", rs.Primary.ID) + } + } + } + + return nil +} + +func testAccCheckKubernetesNetworkPolicyExists(n string, obj *api.NetworkPolicy) 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) + + namespace, name, err := idParts(rs.Primary.ID) + if err != nil { + return err + } + + out, err := conn.NetworkingV1().NetworkPolicies(namespace).Get(name, meta_v1.GetOptions{}) + if err != nil { + return err + } + + *obj = *out + return nil + } +} + +func testAccKubernetesNetworkPolicyConfig_basic(name string) string { + return fmt.Sprintf(` +resource "kubernetes_network_policy" "test" { + metadata { + name = "%s" + namespace = "default" + + annotations { + TestAnnotationOne = "one" + } + + labels { + TestLabelOne = "one" + TestLabelThree = "three" + TestLabelFour = "four" + } + } + + spec { + pod_selector {} + } +} +`, name) +} + +func testAccKubernetesNetworkPolicyConfig_metaModified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_network_policy" "test" { + metadata { + name = "%s" + namespace = "default" + + annotations { + TestAnnotationOne = "one" + TestAnnotationTwo = "two" + } + + labels { + TestLabelOne = "one" + TestLabelTwo = "two" + TestLabelThree = "three" + } + } + + spec { + pod_selector = {} + ingress = [] + } +} +`, name) +} + +func testAccKubernetesNetworkPolicyConfig_specModified(name string) string { + return fmt.Sprintf(` +resource "kubernetes_network_policy" "test" { + metadata { + name = "%s" + namespace = "default" + } + + spec { + pod_selector { + match_expressions { + key = "name" + operator = "In" + values = ["webfront", "api"] + } + } + + ingress = [ + { + ports = [ + { + port = "http" + protocol = "TCP" + }, + { + port = "8125" + protocol = "UDP" + }, + ] + + from = [ + { + namespace_selector { + match_labels = { + name = "default" + } + } + }, + ] + }, + ] + } +} + `, name) +} diff --git a/kubernetes/structure_network_policy.go b/kubernetes/structure_network_policy.go new file mode 100644 index 0000000000..441f7afbbe --- /dev/null +++ b/kubernetes/structure_network_policy.go @@ -0,0 +1,159 @@ +package kubernetes + +import ( + "github.com/hashicorp/terraform/helper/schema" + "k8s.io/apimachinery/pkg/util/intstr" + api "k8s.io/client-go/pkg/api/v1" + "k8s.io/client-go/pkg/apis/networking/v1" + "strconv" +) + +// Flatteners + +func flattenNetworkPolicySpec(in v1.NetworkPolicySpec) []interface{} { + att := make(map[string]interface{}) + att["ingress"] = flattenNetworkPolicyIngress(in.Ingress) + if len(in.PodSelector.MatchExpressions) > 0 || len(in.PodSelector.MatchLabels) > 0 { + att["pod_selector"] = flattenLabelSelector(&in.PodSelector) + } else { + att["pod_selector"] = []interface{}{make(map[string]interface{})} + } + return []interface{}{att} +} + +func flattenNetworkPolicyIngress(in []v1.NetworkPolicyIngressRule) []interface{} { + att := make([]interface{}, len(in), len(in)) + for i, ingress := range in { + m := make(map[string]interface{}) + if ingress.Ports != nil && len(ingress.Ports) > 0 { + m["ports"] = flattenNetworkPolicyIngressPorts(ingress.Ports) + } + if ingress.From != nil && len(ingress.From) > 0 { + m["from"] = flattenNetworkPolicyIngressFrom(ingress.From) + } + att[i] = m + } + return att +} + +func flattenNetworkPolicyIngressPorts(in []v1.NetworkPolicyPort) []interface{} { + att := make([]interface{}, len(in), len(in)) + for i, port := range in { + m := make(map[string]interface{}) + if port.Port != nil { + if (*port.Port).Type == intstr.Int { + m["port"] = strconv.Itoa(int((*port.Port).IntVal)) + } else { + m["port"] = (*port.Port).StrVal + } + } + if port.Protocol != nil { + m["protocol"] = *port.Protocol + } + att[i] = m + } + return att +} + +func flattenNetworkPolicyIngressFrom(in []v1.NetworkPolicyPeer) []interface{} { + att := make([]interface{}, len(in), len(in)) + for i, from := range in { + m := make(map[string]interface{}) + if from.NamespaceSelector != nil { + m["namespace_selector"] = flattenLabelSelector(from.NamespaceSelector) + } + if from.PodSelector != nil { + m["pod_selector"] = flattenLabelSelector(from.PodSelector) + } + att[i] = m + } + return att +} + +// Expanders + +func expandNetworkPolicySpec(l []interface{}) v1.NetworkPolicySpec { + // There must be exactly one spec element + obj := v1.NetworkPolicySpec{} + for _, spec := range l { + in := spec.(map[string]interface{}) + obj.PodSelector = *expandLabelSelector(in["pod_selector"].([]interface{})) + if v, ok := in["ingress"].([]interface{}); ok && len(v) > 0 { + obj.Ingress = expandNetworkPolicyIngress(v) + } + } + return obj +} + +func expandNetworkPolicyIngress(l []interface{}) []v1.NetworkPolicyIngressRule { + obj := make([]v1.NetworkPolicyIngressRule, len(l), len(l)) + for i, ingress := range l { + if ingress != nil { + in := ingress.(map[string]interface{}) + obj[i] = v1.NetworkPolicyIngressRule{} + if v, ok := in["ports"].([]interface{}); ok && len(v) > 0 { + obj[i].Ports = expandNetworkPolicyIngressPorts(v) + } + if v, ok := in["from"].([]interface{}); ok && len(v) > 0 { + obj[i].From = expandNetworkPolicyIngressFrom(v) + } + } + } + return obj +} + +func expandNetworkPolicyIngressPorts(l []interface{}) []v1.NetworkPolicyPort { + obj := make([]v1.NetworkPolicyPort, len(l), len(l)) + for i, port := range l { + in := port.(map[string]interface{}) + if in["port"] != nil && in["port"] != "" { + portStr := in["port"].(string) + if portInt, err := strconv.Atoi(portStr); err == nil && strconv.Itoa(portInt) == portStr { + v := intstr.FromInt(portInt) + obj[i].Port = &v + } else { + v := intstr.FromString(portStr) + obj[i].Port = &v + } + } + if in["protocol"] != nil && in["protocol"] != "" { + v := api.Protocol(in["protocol"].(string)) + obj[i].Protocol = &v + + } + } + return obj +} + +func expandNetworkPolicyIngressFrom(l []interface{}) []v1.NetworkPolicyPeer { + obj := make([]v1.NetworkPolicyPeer, len(l), len(l)) + for i, from := range l { + in := from.(map[string]interface{}) + if v, ok := in["namespace_selector"].([]interface{}); ok && len(v) > 0 { + obj[i].NamespaceSelector = expandLabelSelector(v) + } + if v, ok := in["pod_selector"].([]interface{}); ok && len(v) > 0 { + obj[i].NamespaceSelector = expandLabelSelector(v) + } + } + return obj +} + +// Patchers + +func patchNetworkPolicySpec(keyPrefix, pathPrefix string, d *schema.ResourceData) PatchOperations { + ops := make([]PatchOperation, 0, 0) + if d.HasChange(keyPrefix + "ingress") { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "ingress", + Value: expandLabelSelector(d.Get(keyPrefix + "ingress").([]interface{})), + }) + } + if d.HasChange(keyPrefix + "pod_selector") { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "podSelector", + Value: expandLabelSelector(d.Get(keyPrefix + "pod_selector").([]interface{})), + }) + } + return ops +} From 71188f9da17b3fe214bc6554b075b8e230943984 Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Mon, 12 Feb 2018 11:20:14 +0100 Subject: [PATCH 02/17] Cast Protocol to string and add unit tests to ensure flatten/expand symmetric behavior --- kubernetes/structure_network_policy.go | 2 +- kubernetes/structure_network_policy_test.go | 135 ++++++++++++++++++++ 2 files changed, 136 insertions(+), 1 deletion(-) create mode 100644 kubernetes/structure_network_policy_test.go diff --git a/kubernetes/structure_network_policy.go b/kubernetes/structure_network_policy.go index 441f7afbbe..fad33d5706 100644 --- a/kubernetes/structure_network_policy.go +++ b/kubernetes/structure_network_policy.go @@ -48,7 +48,7 @@ func flattenNetworkPolicyIngressPorts(in []v1.NetworkPolicyPort) []interface{} { } } if port.Protocol != nil { - m["protocol"] = *port.Protocol + m["protocol"] = string(*port.Protocol) } att[i] = m } diff --git a/kubernetes/structure_network_policy_test.go b/kubernetes/structure_network_policy_test.go new file mode 100644 index 0000000000..8a4f35df7f --- /dev/null +++ b/kubernetes/structure_network_policy_test.go @@ -0,0 +1,135 @@ +package kubernetes + +import ( + api "k8s.io/client-go/pkg/api/v1" + "k8s.io/client-go/pkg/apis/networking/v1" + + "k8s.io/apimachinery/pkg/util/intstr" + "reflect" + "testing" +) + +var ( + protoTcp = api.ProtocolTCP + protoUdp = api.ProtocolUDP + portName = intstr.FromString("http") + portNumerical = intstr.FromInt(8125) +) + +func TestFlattenNetworkPolicyIngressPorts(t *testing.T) { + + cases := []struct { + Input []v1.NetworkPolicyPort + ExpectedOutput []interface{} + }{ + { + []v1.NetworkPolicyPort{{ + Port: &portName, + Protocol: &protoTcp, + }}, + []interface{}{ + map[string]interface{}{ + "port": "http", + "protocol": "TCP", + }, + }, + }, + { + []v1.NetworkPolicyPort{{ + Port: &portName, + }}, + []interface{}{ + map[string]interface{}{ + "port": "http", + }, + }, + }, + { + []v1.NetworkPolicyPort{{ + Port: &portNumerical, + Protocol: &protoUdp, + }}, + []interface{}{ + map[string]interface{}{ + "port": "8125", + "protocol": "UDP", + }, + }, + }, + { + []v1.NetworkPolicyPort{{}}, + []interface{}{map[string]interface{}{}}, + }, + { + []v1.NetworkPolicyPort{}, + []interface{}{}, + }, + } + + for _, tc := range cases { + output := flattenNetworkPolicyIngressPorts(tc.Input) + if !reflect.DeepEqual(output, tc.ExpectedOutput) { + t.Fatalf("Unexpected output from flattener.\nExpected: %#v\nGiven: %#v", + tc.ExpectedOutput, output) + } + } +} + +func TestExpandNetworkPolicyIngressPorts(t *testing.T) { + + cases := []struct { + Input []interface{} + ExpectedOutput []v1.NetworkPolicyPort + }{ + { + []interface{}{ + map[string]interface{}{ + "port": "http", + "protocol": "TCP", + }, + }, + []v1.NetworkPolicyPort{{ + Port: &portName, + Protocol: &protoTcp, + }}, + }, + { + []interface{}{ + map[string]interface{}{ + "port": "http", + }, + }, + []v1.NetworkPolicyPort{{ + Port: &portName, + }}, + }, + { + []interface{}{ + map[string]interface{}{ + "port": "8125", + "protocol": "UDP", + }, + }, + []v1.NetworkPolicyPort{{ + Port: &portNumerical, + Protocol: &protoUdp, + }}, + }, + { + []interface{}{map[string]interface{}{}}, + []v1.NetworkPolicyPort{{}}, + }, + { + []interface{}{}, + []v1.NetworkPolicyPort{}, + }, + } + + for _, tc := range cases { + output := expandNetworkPolicyIngressPorts(tc.Input) + if !reflect.DeepEqual(output, tc.ExpectedOutput) { + t.Fatalf("Unexpected output from flattener.\nExpected: %#v\nGiven: %#v", + tc.ExpectedOutput, output) + } + } +} From 6dc7e6d2c8b7a2e49babb737b54e55b5b32f5ee7 Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Mon, 12 Feb 2018 13:02:23 +0100 Subject: [PATCH 03/17] Fix network policy resource update --- ...resource_kubernetes_network_policy_test.go | 79 +++++++++++++++++++ kubernetes/structure_network_policy.go | 6 +- 2 files changed, 82 insertions(+), 3 deletions(-) diff --git a/kubernetes/resource_kubernetes_network_policy_test.go b/kubernetes/resource_kubernetes_network_policy_test.go index d132a4bed8..9e6d366977 100644 --- a/kubernetes/resource_kubernetes_network_policy_test.go +++ b/kubernetes/resource_kubernetes_network_policy_test.go @@ -100,6 +100,39 @@ func TestAccKubernetesNetworkPolicy_basic(t *testing.T) { resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.#", "0"), ), }, + { + Config: testAccKubernetesNetworkPolicyConfig_specModified2(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesNetworkPolicyExists("kubernetes_network_policy.test", &conf), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.key", "name"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.operator", "In"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.1742479128", "webfront"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.2902841359", "api"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.0.port", "http"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.0.protocol", "TCP"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.port", "statsd"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.protocol", "UDP"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.namespace_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.namespace_selector.0.match_labels.name", "default"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.#", "0"), + ), + }, }, }) } @@ -270,3 +303,49 @@ resource "kubernetes_network_policy" "test" { } `, name) } + +func testAccKubernetesNetworkPolicyConfig_specModified2(name string) string { + return fmt.Sprintf(` +resource "kubernetes_network_policy" "test" { + metadata { + name = "%s" + namespace = "default" + } + + spec { + pod_selector { + match_expressions { + key = "name" + operator = "In" + values = ["webfront", "api"] + } + } + + ingress = [ + { + ports = [ + { + port = "http" + protocol = "TCP" + }, + { + port = "statsd" + protocol = "UDP" + }, + ] + + from = [ + { + namespace_selector { + match_labels = { + name = "default" + } + } + }, + ] + }, + ] + } +} + `, name) +} diff --git a/kubernetes/structure_network_policy.go b/kubernetes/structure_network_policy.go index fad33d5706..d267304ffd 100644 --- a/kubernetes/structure_network_policy.go +++ b/kubernetes/structure_network_policy.go @@ -145,13 +145,13 @@ func patchNetworkPolicySpec(keyPrefix, pathPrefix string, d *schema.ResourceData ops := make([]PatchOperation, 0, 0) if d.HasChange(keyPrefix + "ingress") { ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "ingress", - Value: expandLabelSelector(d.Get(keyPrefix + "ingress").([]interface{})), + Path: pathPrefix + "/ingress", + Value: expandNetworkPolicyIngress(d.Get(keyPrefix + "ingress").([]interface{})), }) } if d.HasChange(keyPrefix + "pod_selector") { ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "podSelector", + Path: pathPrefix + "/podSelector", Value: expandLabelSelector(d.Get(keyPrefix + "pod_selector").([]interface{})), }) } From 70efd9120139e221210655608881b218dd1fecab Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Mon, 12 Feb 2018 15:06:01 +0100 Subject: [PATCH 04/17] Add network policy documentation --- website/docs/r/network_policy.html.markdown | 150 ++++++++++++++++++++ website/kubernetes.erb | 3 + 2 files changed, 153 insertions(+) create mode 100644 website/docs/r/network_policy.html.markdown diff --git a/website/docs/r/network_policy.html.markdown b/website/docs/r/network_policy.html.markdown new file mode 100644 index 0000000000..e81f44487e --- /dev/null +++ b/website/docs/r/network_policy.html.markdown @@ -0,0 +1,150 @@ +--- +layout: "kubernetes" +page_title: "Kubernetes: kubernetes_network_policy" +sidebar_current: "docs-kubernetes-resource-network-policy" +description: |- + Kubernetes supports network policies to specificy of how groups of pods are allowed to communicate with each other and other network endpoints. + NetworkPolicy resources use labels to select pods and define rules which specify what traffic is allowed to the selected pods. +--- + +# kubernetes_network_policy + +Kubernetes supports network policies to specificy of how groups of pods are allowed to communicate with each other and other network endpoints. +NetworkPolicy resources use labels to select pods and define rules which specify what traffic is allowed to the selected pods. +Read more about network policies at https://kubernetes.io/docs/concepts/services-networking/network-policies/ + +## Example Usage + +```hcl +resource "kubernetes_network_policy" "example" { + metadata { + name = "terraform-example-network-policy" + namespace = "default" + } + + spec { + pod_selector { + match_expressions { + key = "name" + operator = "In" + values = ["webfront", "api"] + } + } + + ingress = [ + { + ports = [ + { + port = "http" + protocol = "TCP" + }, + { + port = "8125" + protocol = "UDP" + }, + ] + + from = [ + { + namespace_selector { + match_labels = { + name = "default" + } + } + }, + ] + }, + ] + } +} +``` + +## Argument Reference + +The following arguments are supported: + +* `metadata` - (Required) Standard network policy's [metadata](https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#metadata). + +## Nested Blocks + +### `metadata` + +#### Arguments + +* `annotations` - (Optional) An unstructured key value map stored with the network policy that may be used to store arbitrary metadata. More info: http://kubernetes.io/docs/user-guide/annotations +* `generate_name` - (Optional) Prefix, used by the server, to generate a unique name ONLY IF the `name` field has not been provided. This value will also be combined with a unique suffix. Read more about [name idempotency](https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#idempotency). +* `labels` - (Optional) Map of string keys and values that can be used to organize and categorize (scope and select) network policies. May match selectors of replication controllers and services. More info: http://kubernetes.io/docs/user-guide/labels +* `name` - (Optional) Name of the network policy, must be unique. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names + +#### Attributes + +* `generation` - A sequence number representing a specific generation of the desired state. +* `resource_version` - An opaque value that represents the internal version of this network policy that can be used by clients to determine when network policies have changed. Read more about [concurrency control and consistency](https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#concurrency-control-and-consistency). +* `self_link` - A URL representing this network policy. +* `uid` - The unique in time and space value for this network policy. More info: http://kubernetes.io/docs/user-guide/identifiers#uids + + +### `spec` + +#### Arguments + +* `ingress` - (Optional) List of ingress rules to be applied to the selected pods. Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic source is the pod's local node, OR if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy does not allow any traffic (and serves solely to ensure that the pods it selects are isolated by default). +* `pod_selector` - (Required) Selects the pods to which this NetworkPolicy object applies. The array of ingress rules is applied to any pods selected by this field. Multiple network policies can select the same set of pods. In this case, the ingress rules for each are combined additively. This field is NOT optional and follows standard label selector semantics. An empty podSelector matches all pods in this namespace. + + +### `ingress` + +#### Arguments + +* `from` - (Optional) List of sources which should be able to access the pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all sources (traffic not restricted by source). If this field is present and contains at least on item, this rule allows traffic only if the traffic matches at least one item in the from list. +* `ports` - (Optional) List of ports which should be made accessible on the pods selected for this rule. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. + + +### `from` + +#### Arguments + +* `namespace_selector` - (Optional) Selects Namespaces using cluster scoped-labels. This matches all pods in all namespaces selected by this label selector. This field follows standard label selector semantics. If present but empty, this selector selects all namespaces. +* `pod_selector` - (Optional) This is a label selector which selects Pods in this namespace. This field follows standard label selector semantics. If present but empty, this selector selects all pods in this namespace. + + +### `ports` + +#### Arguments + +* `port` - (Optional) The port on the given protocol. This can either be a numerical or named port on a pod. If this field is not provided, this matches all port names and numbers. +* `protocol` - (Optional) The protocol (TCP or UDP) which traffic must match. If not specified, this field defaults to TCP. + + +### `namespace_selector` + +#### Arguments + +* `match_expressions` - (Optional) A list of label selector requirements. The requirements are ANDed. +* `match_labels` - (Optional) A map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of `match_expressions`, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. + + +### `pod_selector` + +#### Arguments + +* `match_expressions` - (Optional) A list of label selector requirements. The requirements are ANDed. +* `match_labels` - (Optional) A map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of `match_expressions`, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed. + + +### `match_expressions` + +#### Arguments + +* `key` - (Optional) The label key that the selector applies to. +* `operator` - (Optional) A key's relationship to a set of values. Valid operators ard `In`, `NotIn`, `Exists` and `DoesNotExist`. +* `values` - (Optional) An array of string values. If the operator is `In` or `NotIn`, the values array must be non-empty. If the operator is `Exists` or `DoesNotExist`, the values array must be empty. This array is replaced during a strategic merge patch. + + +## Import + +Network policies can be imported using their identifier consisting of `/`, e.g.: + +``` +$ terraform import kubernetes_network_policy.example default/terraform-example-network-policy +``` diff --git a/website/kubernetes.erb b/website/kubernetes.erb index 18d8dd8657..c6ca49b200 100644 --- a/website/kubernetes.erb +++ b/website/kubernetes.erb @@ -49,6 +49,9 @@ > kubernetes_namespace + > + kubernetes_network_policy + > kubernetes_persistent_volume From 9a006be8eb5d16237d9c386b11bb6258bfb00144 Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Mon, 12 Feb 2018 19:26:53 +0100 Subject: [PATCH 05/17] Network policy ingress ports default to TCP protocol --- kubernetes/resource_kubernetes_network_policy.go | 1 + kubernetes/resource_kubernetes_network_policy_test.go | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/kubernetes/resource_kubernetes_network_policy.go b/kubernetes/resource_kubernetes_network_policy.go index 5cc8ffd4e7..3b63472c2e 100644 --- a/kubernetes/resource_kubernetes_network_policy.go +++ b/kubernetes/resource_kubernetes_network_policy.go @@ -66,6 +66,7 @@ func resourceKubernetesNetworkPolicy() *schema.Resource { Type: schema.TypeString, Description: networkPolicyPortProtocolDoc, Optional: true, + Default: "TCP", }, }, }, diff --git a/kubernetes/resource_kubernetes_network_policy_test.go b/kubernetes/resource_kubernetes_network_policy_test.go index 9e6d366977..b39952ca27 100644 --- a/kubernetes/resource_kubernetes_network_policy_test.go +++ b/kubernetes/resource_kubernetes_network_policy_test.go @@ -280,7 +280,6 @@ resource "kubernetes_network_policy" "test" { ports = [ { port = "http" - protocol = "TCP" }, { port = "8125" From 78fbd3f29d8df9bd0b58eb3a109dc14acea8029a Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Tue, 13 Feb 2018 00:18:50 +0100 Subject: [PATCH 06/17] Fix network policy ingress pod selector update --- kubernetes/resource_kubernetes_network_policy_test.go | 10 +++++----- kubernetes/structure_network_policy.go | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/kubernetes/resource_kubernetes_network_policy_test.go b/kubernetes/resource_kubernetes_network_policy_test.go index b39952ca27..24c4c4ace8 100644 --- a/kubernetes/resource_kubernetes_network_policy_test.go +++ b/kubernetes/resource_kubernetes_network_policy_test.go @@ -128,9 +128,9 @@ func TestAccKubernetesNetworkPolicy_basic(t *testing.T) { resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.port", "statsd"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.protocol", "UDP"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.#", "1"), - resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.namespace_selector.#", "1"), - resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.namespace_selector.0.match_labels.name", "default"), - resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.namespace_selector.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.0.match_labels.app", "myapp"), ), }, }, @@ -335,9 +335,9 @@ resource "kubernetes_network_policy" "test" { from = [ { - namespace_selector { + pod_selector { match_labels = { - name = "default" + app = "myapp" } } }, diff --git a/kubernetes/structure_network_policy.go b/kubernetes/structure_network_policy.go index d267304ffd..66b8bc6118 100644 --- a/kubernetes/structure_network_policy.go +++ b/kubernetes/structure_network_policy.go @@ -133,7 +133,7 @@ func expandNetworkPolicyIngressFrom(l []interface{}) []v1.NetworkPolicyPeer { obj[i].NamespaceSelector = expandLabelSelector(v) } if v, ok := in["pod_selector"].([]interface{}); ok && len(v) > 0 { - obj[i].NamespaceSelector = expandLabelSelector(v) + obj[i].PodSelector = expandLabelSelector(v) } } return obj From 3713aa52398166ef2bd711287326bdf4587b3121 Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Wed, 14 Feb 2018 01:09:39 +0100 Subject: [PATCH 07/17] Update code to use k8s libs version 1.9.0 --- kubernetes/resource_kubernetes_network_policy.go | 2 +- kubernetes/resource_kubernetes_network_policy_test.go | 2 +- kubernetes/structure_network_policy.go | 4 ++-- kubernetes/structure_network_policy_test.go | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/kubernetes/resource_kubernetes_network_policy.go b/kubernetes/resource_kubernetes_network_policy.go index 3b63472c2e..0520af8e6f 100644 --- a/kubernetes/resource_kubernetes_network_policy.go +++ b/kubernetes/resource_kubernetes_network_policy.go @@ -5,11 +5,11 @@ import ( "log" "github.com/hashicorp/terraform/helper/schema" + api "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/api/errors" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" pkgApi "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes" - api "k8s.io/client-go/pkg/apis/networking/v1" ) // Use generated swagger docs from kubernetes' client-go to avoid copy/pasting them here diff --git a/kubernetes/resource_kubernetes_network_policy_test.go b/kubernetes/resource_kubernetes_network_policy_test.go index 24c4c4ace8..d791681ee4 100644 --- a/kubernetes/resource_kubernetes_network_policy_test.go +++ b/kubernetes/resource_kubernetes_network_policy_test.go @@ -7,9 +7,9 @@ import ( "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" + api "k8s.io/api/networking/v1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" kubernetes "k8s.io/client-go/kubernetes" - api "k8s.io/client-go/pkg/apis/networking/v1" ) func TestAccKubernetesNetworkPolicy_basic(t *testing.T) { diff --git a/kubernetes/structure_network_policy.go b/kubernetes/structure_network_policy.go index 66b8bc6118..d6180c0889 100644 --- a/kubernetes/structure_network_policy.go +++ b/kubernetes/structure_network_policy.go @@ -2,9 +2,9 @@ package kubernetes import ( "github.com/hashicorp/terraform/helper/schema" + api "k8s.io/api/core/v1" + "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/util/intstr" - api "k8s.io/client-go/pkg/api/v1" - "k8s.io/client-go/pkg/apis/networking/v1" "strconv" ) diff --git a/kubernetes/structure_network_policy_test.go b/kubernetes/structure_network_policy_test.go index 8a4f35df7f..6a47b8a2be 100644 --- a/kubernetes/structure_network_policy_test.go +++ b/kubernetes/structure_network_policy_test.go @@ -1,8 +1,8 @@ package kubernetes import ( - api "k8s.io/client-go/pkg/api/v1" - "k8s.io/client-go/pkg/apis/networking/v1" + api "k8s.io/api/core/v1" + "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/util/intstr" "reflect" From 6ca3dbeb168ab4161b38505888802eefa50f34b6 Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Wed, 14 Feb 2018 01:34:30 +0100 Subject: [PATCH 08/17] Add k8s 1.8+ Network Policy fields: egress, ip_block and policy_types --- .../resource_kubernetes_network_policy.go | 115 ++++++++++++- ...resource_kubernetes_network_policy_test.go | 153 +++++++++++++++++- kubernetes/structure_network_policy.go | 136 +++++++++++++--- kubernetes/structure_network_policy_test.go | 4 +- 4 files changed, 382 insertions(+), 26 deletions(-) diff --git a/kubernetes/resource_kubernetes_network_policy.go b/kubernetes/resource_kubernetes_network_policy.go index 0520af8e6f..bf4845f5b8 100644 --- a/kubernetes/resource_kubernetes_network_policy.go +++ b/kubernetes/resource_kubernetes_network_policy.go @@ -17,12 +17,19 @@ var ( networkPolicySpecDoc = api.NetworkPolicy{}.SwaggerDoc()["spec"] networkPolicySpecIngressDoc = api.NetworkPolicySpec{}.SwaggerDoc()["ingress"] networkPolicyIngressRulePortsDoc = api.NetworkPolicyIngressRule{}.SwaggerDoc()["ports"] + networkPolicyIngressRuleFromDoc = api.NetworkPolicyIngressRule{}.SwaggerDoc()["from"] + networkPolicySpecEgressDoc = api.NetworkPolicySpec{}.SwaggerDoc()["egress"] + networkPolicyEgressRulePortsDoc = api.NetworkPolicyEgressRule{}.SwaggerDoc()["ports"] + networkPolicyEgressRuleToDoc = api.NetworkPolicyEgressRule{}.SwaggerDoc()["to"] networkPolicyPortPortDoc = api.NetworkPolicyPort{}.SwaggerDoc()["port"] networkPolicyPortProtocolDoc = api.NetworkPolicyPort{}.SwaggerDoc()["protocol"] - networkPolicyIngressRuleFromDoc = api.NetworkPolicyIngressRule{}.SwaggerDoc()["from"] + networkPolicyPeerIpBlockDoc = api.NetworkPolicyPeer{}.SwaggerDoc()["ipBlock"] + ipBlockCidrDoc = api.IPBlock{}.SwaggerDoc()["cidr"] + ipBlockExceptDoc = api.IPBlock{}.SwaggerDoc()["except"] networkPolicyPeerNamespaceSelectorDoc = api.NetworkPolicyPeer{}.SwaggerDoc()["namespaceSelector"] networkPolicyPeerPodSelectorDoc = api.NetworkPolicyPeer{}.SwaggerDoc()["podSelector"] networkPolicySpecPodSelectorDoc = api.NetworkPolicySpec{}.SwaggerDoc()["podSelector"] + networkPolicySpecPolicyTypesDoc = api.NetworkPolicySpec{}.SwaggerDoc()["policyTypes"] ) func resourceKubernetesNetworkPolicy() *schema.Resource { @@ -77,6 +84,104 @@ func resourceKubernetesNetworkPolicy() *schema.Resource { Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ + "ip_block": { + Type: schema.TypeList, + Description: networkPolicyPeerIpBlockDoc, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cidr": { + Type: schema.TypeString, + Description: ipBlockCidrDoc, + Optional: true, + }, + "except": { + Type: schema.TypeList, + Description: ipBlockExceptDoc, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + }, + "namespace_selector": { + Type: schema.TypeList, + Description: networkPolicyPeerNamespaceSelectorDoc, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: labelSelectorFields(), + }, + }, + "pod_selector": { + Type: schema.TypeList, + Description: networkPolicyPeerPodSelectorDoc, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: labelSelectorFields(), + }, + }, + }, + }, + }, + }, + }, + }, + "egress": { + Type: schema.TypeList, + Description: networkPolicySpecEgressDoc, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ports": { + Type: schema.TypeList, + Description: networkPolicyEgressRulePortsDoc, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "port": { + Type: schema.TypeString, + Description: networkPolicyPortPortDoc, + Optional: true, + }, + "protocol": { + Type: schema.TypeString, + Description: networkPolicyPortProtocolDoc, + Optional: true, + Default: "TCP", + }, + }, + }, + }, + "to": { + Type: schema.TypeList, + Description: networkPolicyEgressRuleToDoc, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "ip_block": { + Type: schema.TypeList, + Description: networkPolicyPeerIpBlockDoc, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "cidr": { + Type: schema.TypeString, + Description: ipBlockCidrDoc, + Optional: true, + }, + "except": { + Type: schema.TypeList, + Description: ipBlockExceptDoc, + Optional: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + }, "namespace_selector": { Type: schema.TypeList, Description: networkPolicyPeerNamespaceSelectorDoc, @@ -110,6 +215,14 @@ func resourceKubernetesNetworkPolicy() *schema.Resource { Schema: labelSelectorFields(), }, }, + "policy_types": { + Type: schema.TypeList, + Description: networkPolicySpecPolicyTypesDoc, + Optional: true, + MaxItems: 2, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, + }, }, }, }, diff --git a/kubernetes/resource_kubernetes_network_policy_test.go b/kubernetes/resource_kubernetes_network_policy_test.go index d791681ee4..57c3591792 100644 --- a/kubernetes/resource_kubernetes_network_policy_test.go +++ b/kubernetes/resource_kubernetes_network_policy_test.go @@ -127,10 +127,68 @@ func TestAccKubernetesNetworkPolicy_basic(t *testing.T) { resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.0.protocol", "TCP"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.port", "statsd"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.protocol", "UDP"), - resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.#", "1"), - resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.namespace_selector.#", "0"), - resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.#", "1"), - resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.0.match_labels.app", "myapp"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.cidr", "10.0.0.0/8"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.except.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.except.0", "10.0.0.0/24"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.except.1", "10.0.1.0/24"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.ip_block.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.namespace_selector.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.pod_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.pod_selector.0.match_labels.app", "myapp"), + ), + }, + { + Config: testAccKubernetesNetworkPolicyConfig_specModified3(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesNetworkPolicyExists("kubernetes_network_policy.test", &conf), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.key", "name"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.operator", "In"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.1742479128", "webfront"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.2902841359", "api"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.0.port", "http"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.0.protocol", "TCP"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.port", "statsd"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.protocol", "UDP"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.cidr", "10.0.0.0/8"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.except.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.except.0", "10.0.0.0/24"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.except.1", "10.0.1.0/24"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.ip_block.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.namespace_selector.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.pod_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.pod_selector.0.match_labels.app", "myapp"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.ports.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.ports.0.port", "statsd"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.ports.0.protocol", "UDP"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.cidr", "10.0.0.0/8"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.except.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.except.0", "10.0.0.0/24"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.except.1", "10.0.1.0/24"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.pod_selector.#", "0"), ), }, }, @@ -334,6 +392,15 @@ resource "kubernetes_network_policy" "test" { ] from = [ + { + ip_block { + cidr = "10.0.0.0/8" + except = [ + "10.0.0.0/24", + "10.0.1.0/24", + ] + } + }, { pod_selector { match_labels = { @@ -348,3 +415,81 @@ resource "kubernetes_network_policy" "test" { } `, name) } + +func testAccKubernetesNetworkPolicyConfig_specModified3(name string) string { + return fmt.Sprintf(` +resource "kubernetes_network_policy" "test" { + metadata { + name = "%s" + namespace = "default" + } + + spec { + pod_selector { + match_expressions { + key = "name" + operator = "In" + values = ["webfront", "api"] + } + } + + ingress = [ + { + ports = [ + { + port = "http" + protocol = "TCP" + }, + { + port = "statsd" + protocol = "UDP" + }, + ] + + from = [ + { + ip_block { + cidr = "10.0.0.0/8" + except = [ + "10.0.0.0/24", + "10.0.1.0/24", + ] + } + }, + { + pod_selector { + match_labels = { + app = "myapp" + } + } + }, + ] + }, + ] + + egress = [ + { + ports = [ + { + port = "statsd" + protocol = "UDP" + }, + ] + + to = [ + { + ip_block { + cidr = "10.0.0.0/8" + except = [ + "10.0.0.0/24", + "10.0.1.0/24", + ] + } + }, + ] + }, + ] + } +} + `, name) +} diff --git a/kubernetes/structure_network_policy.go b/kubernetes/structure_network_policy.go index d6180c0889..eb66aea942 100644 --- a/kubernetes/structure_network_policy.go +++ b/kubernetes/structure_network_policy.go @@ -13,11 +13,15 @@ import ( func flattenNetworkPolicySpec(in v1.NetworkPolicySpec) []interface{} { att := make(map[string]interface{}) att["ingress"] = flattenNetworkPolicyIngress(in.Ingress) + att["egress"] = flattenNetworkPolicyEgress(in.Egress) if len(in.PodSelector.MatchExpressions) > 0 || len(in.PodSelector.MatchLabels) > 0 { att["pod_selector"] = flattenLabelSelector(&in.PodSelector) } else { att["pod_selector"] = []interface{}{make(map[string]interface{})} } + if len(in.PolicyTypes) > 0 { + att["policy_types"] = in.PolicyTypes + } return []interface{}{att} } @@ -26,17 +30,32 @@ func flattenNetworkPolicyIngress(in []v1.NetworkPolicyIngressRule) []interface{} for i, ingress := range in { m := make(map[string]interface{}) if ingress.Ports != nil && len(ingress.Ports) > 0 { - m["ports"] = flattenNetworkPolicyIngressPorts(ingress.Ports) + m["ports"] = flattenNetworkPolicyPorts(ingress.Ports) } if ingress.From != nil && len(ingress.From) > 0 { - m["from"] = flattenNetworkPolicyIngressFrom(ingress.From) + m["from"] = flattenNetworkPolicyPeer(ingress.From) } att[i] = m } return att } -func flattenNetworkPolicyIngressPorts(in []v1.NetworkPolicyPort) []interface{} { +func flattenNetworkPolicyEgress(in []v1.NetworkPolicyEgressRule) []interface{} { + att := make([]interface{}, len(in), len(in)) + for i, egress := range in { + m := make(map[string]interface{}) + if egress.Ports != nil && len(egress.Ports) > 0 { + m["ports"] = flattenNetworkPolicyPorts(egress.Ports) + } + if egress.To != nil && len(egress.To) > 0 { + m["to"] = flattenNetworkPolicyPeer(egress.To) + } + att[i] = m + } + return att +} + +func flattenNetworkPolicyPorts(in []v1.NetworkPolicyPort) []interface{} { att := make([]interface{}, len(in), len(in)) for i, port := range in { m := make(map[string]interface{}) @@ -55,21 +74,35 @@ func flattenNetworkPolicyIngressPorts(in []v1.NetworkPolicyPort) []interface{} { return att } -func flattenNetworkPolicyIngressFrom(in []v1.NetworkPolicyPeer) []interface{} { +func flattenNetworkPolicyPeer(in []v1.NetworkPolicyPeer) []interface{} { att := make([]interface{}, len(in), len(in)) - for i, from := range in { + for i, peer := range in { m := make(map[string]interface{}) - if from.NamespaceSelector != nil { - m["namespace_selector"] = flattenLabelSelector(from.NamespaceSelector) + if peer.IPBlock != nil { + m["ip_block"] = flattenIPBlock(peer.IPBlock) + } + if peer.NamespaceSelector != nil { + m["namespace_selector"] = flattenLabelSelector(peer.NamespaceSelector) } - if from.PodSelector != nil { - m["pod_selector"] = flattenLabelSelector(from.PodSelector) + if peer.PodSelector != nil { + m["pod_selector"] = flattenLabelSelector(peer.PodSelector) } att[i] = m } return att } +func flattenIPBlock(in *v1.IPBlock) []interface{} { + att := make(map[string]interface{}) + if in.CIDR != "" { + att["cidr"] = in.CIDR + } + if len(in.Except) > 0 { + att["except"] = in.Except + } + return []interface{}{att} +} + // Expanders func expandNetworkPolicySpec(l []interface{}) v1.NetworkPolicySpec { @@ -92,17 +125,34 @@ func expandNetworkPolicyIngress(l []interface{}) []v1.NetworkPolicyIngressRule { in := ingress.(map[string]interface{}) obj[i] = v1.NetworkPolicyIngressRule{} if v, ok := in["ports"].([]interface{}); ok && len(v) > 0 { - obj[i].Ports = expandNetworkPolicyIngressPorts(v) + obj[i].Ports = expandNetworkPolicyPorts(v) } if v, ok := in["from"].([]interface{}); ok && len(v) > 0 { - obj[i].From = expandNetworkPolicyIngressFrom(v) + obj[i].From = expandNetworkPolicyPeer(v) } } } return obj } -func expandNetworkPolicyIngressPorts(l []interface{}) []v1.NetworkPolicyPort { +func expandNetworkPolicyEgress(l []interface{}) []v1.NetworkPolicyEgressRule { + obj := make([]v1.NetworkPolicyEgressRule, len(l), len(l)) + for i, ingress := range l { + if ingress != nil { + in := ingress.(map[string]interface{}) + obj[i] = v1.NetworkPolicyEgressRule{} + if v, ok := in["ports"].([]interface{}); ok && len(v) > 0 { + obj[i].Ports = expandNetworkPolicyPorts(v) + } + if v, ok := in["to"].([]interface{}); ok && len(v) > 0 { + obj[i].To = expandNetworkPolicyPeer(v) + } + } + } + return obj +} + +func expandNetworkPolicyPorts(l []interface{}) []v1.NetworkPolicyPort { obj := make([]v1.NetworkPolicyPort, len(l), len(l)) for i, port := range l { in := port.(map[string]interface{}) @@ -125,10 +175,13 @@ func expandNetworkPolicyIngressPorts(l []interface{}) []v1.NetworkPolicyPort { return obj } -func expandNetworkPolicyIngressFrom(l []interface{}) []v1.NetworkPolicyPeer { +func expandNetworkPolicyPeer(l []interface{}) []v1.NetworkPolicyPeer { obj := make([]v1.NetworkPolicyPeer, len(l), len(l)) - for i, from := range l { - in := from.(map[string]interface{}) + for i, peer := range l { + in := peer.(map[string]interface{}) + if v, ok := in["ip_block"].([]interface{}); ok && len(v) > 0 { + obj[i].IPBlock = expandIPBlock(v) + } if v, ok := in["namespace_selector"].([]interface{}); ok && len(v) > 0 { obj[i].NamespaceSelector = expandLabelSelector(v) } @@ -139,15 +192,54 @@ func expandNetworkPolicyIngressFrom(l []interface{}) []v1.NetworkPolicyPeer { return obj } +func expandIPBlock(l []interface{}) *v1.IPBlock { + obj := &v1.IPBlock{} + if len(l) == 0 || l[0] == nil { + return &v1.IPBlock{} + } + in := l[0].(map[string]interface{}) + if v, ok := in["cidr"].(string); ok && v != "" { + obj.CIDR = v + } + if v, ok := in["except"].([]interface{}); ok && len(v) > 0 { + obj.Except = expandStringSlice(v) + } + return obj +} + // Patchers func patchNetworkPolicySpec(keyPrefix, pathPrefix string, d *schema.ResourceData) PatchOperations { ops := make([]PatchOperation, 0, 0) if d.HasChange(keyPrefix + "ingress") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/ingress", - Value: expandNetworkPolicyIngress(d.Get(keyPrefix + "ingress").([]interface{})), - }) + oldV, _ := d.GetChange(keyPrefix + "ingress") + ingress := expandNetworkPolicyIngress(d.Get(keyPrefix + "ingress").([]interface{})) + if len(oldV.([]interface{})) == 0 { + ops = append(ops, &AddOperation{ + Path: pathPrefix + "/ingress", + Value: ingress, + }) + } else { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/ingress", + Value: ingress, + }) + } + } + if d.HasChange(keyPrefix + "egress") { + oldV, _ := d.GetChange(keyPrefix + "egress") + egress := expandNetworkPolicyEgress(d.Get(keyPrefix + "egress").([]interface{})) + if len(oldV.([]interface{})) == 0 { + ops = append(ops, &AddOperation{ + Path: pathPrefix + "/egress", + Value: egress, + }) + } else { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/egress", + Value: egress, + }) + } } if d.HasChange(keyPrefix + "pod_selector") { ops = append(ops, &ReplaceOperation{ @@ -155,5 +247,11 @@ func patchNetworkPolicySpec(keyPrefix, pathPrefix string, d *schema.ResourceData Value: expandLabelSelector(d.Get(keyPrefix + "pod_selector").([]interface{})), }) } + if d.HasChange(keyPrefix + "policy_types") { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/policyTypes", + Value: expandStringSlice(d.Get(keyPrefix + "policy_types").([]interface{})), + }) + } return ops } diff --git a/kubernetes/structure_network_policy_test.go b/kubernetes/structure_network_policy_test.go index 6a47b8a2be..0aefec953d 100644 --- a/kubernetes/structure_network_policy_test.go +++ b/kubernetes/structure_network_policy_test.go @@ -67,7 +67,7 @@ func TestFlattenNetworkPolicyIngressPorts(t *testing.T) { } for _, tc := range cases { - output := flattenNetworkPolicyIngressPorts(tc.Input) + output := flattenNetworkPolicyPorts(tc.Input) if !reflect.DeepEqual(output, tc.ExpectedOutput) { t.Fatalf("Unexpected output from flattener.\nExpected: %#v\nGiven: %#v", tc.ExpectedOutput, output) @@ -126,7 +126,7 @@ func TestExpandNetworkPolicyIngressPorts(t *testing.T) { } for _, tc := range cases { - output := expandNetworkPolicyIngressPorts(tc.Input) + output := expandNetworkPolicyPorts(tc.Input) if !reflect.DeepEqual(output, tc.ExpectedOutput) { t.Fatalf("Unexpected output from flattener.\nExpected: %#v\nGiven: %#v", tc.ExpectedOutput, output) From b0de33f09be1d71d2d9db484752edd7ce56f62e9 Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Tue, 15 May 2018 11:22:58 +0200 Subject: [PATCH 09/17] Fix issue when Network Policy has an egress at creation --- ...resource_kubernetes_network_policy_test.go | 69 ++++++++++++++++++- kubernetes/structure_network_policy.go | 3 + 2 files changed, 70 insertions(+), 2 deletions(-) diff --git a/kubernetes/resource_kubernetes_network_policy_test.go b/kubernetes/resource_kubernetes_network_policy_test.go index 57c3591792..165f8e8f38 100644 --- a/kubernetes/resource_kubernetes_network_policy_test.go +++ b/kubernetes/resource_kubernetes_network_policy_test.go @@ -141,7 +141,72 @@ func TestAccKubernetesNetworkPolicy_basic(t *testing.T) { ), }, { - Config: testAccKubernetesNetworkPolicyConfig_specModified3(name), + Config: testAccKubernetesNetworkPolicyConfig_withEgress(name), + Check: resource.ComposeAggregateTestCheckFunc( + testAccCheckKubernetesNetworkPolicyExists("kubernetes_network_policy.test", &conf), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.annotations.%", "0"), + testAccCheckMetaAnnotations(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.labels.%", "0"), + testAccCheckMetaLabels(&conf.ObjectMeta, map[string]string{}), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.name", name), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.generation"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.resource_version"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.self_link"), + resource.TestCheckResourceAttrSet("kubernetes_network_policy.test", "metadata.0.uid"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.key", "name"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.operator", "In"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.1742479128", "webfront"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.0.match_expressions.0.values.2902841359", "api"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.0.port", "http"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.0.protocol", "TCP"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.port", "statsd"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.ports.1.protocol", "UDP"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.cidr", "10.0.0.0/8"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.except.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.except.0", "10.0.0.0/24"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.ip_block.0.except.1", "10.0.1.0/24"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.ip_block.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.namespace_selector.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.pod_selector.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.pod_selector.0.match_labels.app", "myapp"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.ports.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.ports.0.port", "statsd"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.ports.0.protocol", "UDP"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.cidr", "10.0.0.0/8"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.except.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.except.0", "10.0.0.0/24"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.except.1", "10.0.1.0/24"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.pod_selector.#", "0"), + ), + }, + }, + }) +} + +func TestAccKubernetesNetworkPolicy_withEgressAtCreation(t *testing.T) { + var conf api.NetworkPolicy + name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + IDRefreshName: "kubernetes_network_policy.test", + Providers: testAccProviders, + CheckDestroy: testAccCheckKubernetesNetworkPolicyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccKubernetesNetworkPolicyConfig_withEgress(name), Check: resource.ComposeAggregateTestCheckFunc( testAccCheckKubernetesNetworkPolicyExists("kubernetes_network_policy.test", &conf), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "metadata.0.annotations.%", "0"), @@ -416,7 +481,7 @@ resource "kubernetes_network_policy" "test" { `, name) } -func testAccKubernetesNetworkPolicyConfig_specModified3(name string) string { +func testAccKubernetesNetworkPolicyConfig_withEgress(name string) string { return fmt.Sprintf(` resource "kubernetes_network_policy" "test" { metadata { diff --git a/kubernetes/structure_network_policy.go b/kubernetes/structure_network_policy.go index eb66aea942..fcb60b3d5e 100644 --- a/kubernetes/structure_network_policy.go +++ b/kubernetes/structure_network_policy.go @@ -114,6 +114,9 @@ func expandNetworkPolicySpec(l []interface{}) v1.NetworkPolicySpec { if v, ok := in["ingress"].([]interface{}); ok && len(v) > 0 { obj.Ingress = expandNetworkPolicyIngress(v) } + if v, ok := in["egress"].([]interface{}); ok && len(v) > 0 { + obj.Egress = expandNetworkPolicyEgress(v) + } } return obj } From dc1656f275111f122e64822691df6d658acd4901 Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Tue, 15 May 2018 13:38:43 +0200 Subject: [PATCH 10/17] Make policy_types property required because the default value is only evaluated server side on resource creation --- .../resource_kubernetes_network_policy.go | 9 ++++++-- ...resource_kubernetes_network_policy_test.go | 23 +++++++++++++++++++ kubernetes/structure_network_policy.go | 17 ++++++++++---- 3 files changed, 43 insertions(+), 6 deletions(-) diff --git a/kubernetes/resource_kubernetes_network_policy.go b/kubernetes/resource_kubernetes_network_policy.go index bf4845f5b8..8017ab95df 100644 --- a/kubernetes/resource_kubernetes_network_policy.go +++ b/kubernetes/resource_kubernetes_network_policy.go @@ -215,12 +215,17 @@ func resourceKubernetesNetworkPolicy() *schema.Resource { Schema: labelSelectorFields(), }, }, + // The policy_types property is made required because the default value is only evaluated server side on resource creation. + // During the initial creation, a default value is determined and stored, then PolicyTypes is no longer considered unset, + // it will stick to that value on further updates unless explicitly overridden. + // Leaving the policy_types property optional here would prevent further updates adding egress rules after the initial resource creation + // without egress rules nor policy types from working as expected as PolicyTypes will stick to Ingress server side. "policy_types": { Type: schema.TypeList, Description: networkPolicySpecPolicyTypesDoc, - Optional: true, + Required: true, + MinItems: 1, MaxItems: 2, - Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, }, }, diff --git a/kubernetes/resource_kubernetes_network_policy_test.go b/kubernetes/resource_kubernetes_network_policy_test.go index 165f8e8f38..9f48f80268 100644 --- a/kubernetes/resource_kubernetes_network_policy_test.go +++ b/kubernetes/resource_kubernetes_network_policy_test.go @@ -42,6 +42,8 @@ func TestAccKubernetesNetworkPolicy_basic(t *testing.T) { resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.#", "1"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.#", "1"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.0", "Ingress"), ), }, { @@ -65,6 +67,8 @@ func TestAccKubernetesNetworkPolicy_basic(t *testing.T) { resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.#", "1"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.pod_selector.#", "1"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.0", "Ingress"), ), }, { @@ -98,6 +102,8 @@ func TestAccKubernetesNetworkPolicy_basic(t *testing.T) { resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.namespace_selector.#", "1"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.namespace_selector.0.match_labels.name", "default"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.0.pod_selector.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.0", "Ingress"), ), }, { @@ -138,6 +144,8 @@ func TestAccKubernetesNetworkPolicy_basic(t *testing.T) { resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.namespace_selector.#", "0"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.pod_selector.#", "1"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.ingress.0.from.1.pod_selector.0.match_labels.app", "myapp"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.0", "Ingress"), ), }, { @@ -189,6 +197,9 @@ func TestAccKubernetesNetworkPolicy_basic(t *testing.T) { resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.except.0", "10.0.0.0/24"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.except.1", "10.0.1.0/24"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.pod_selector.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.0", "Ingress"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.1", "Egress"), ), }, }, @@ -254,6 +265,9 @@ func TestAccKubernetesNetworkPolicy_withEgressAtCreation(t *testing.T) { resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.except.0", "10.0.0.0/24"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.ip_block.0.except.1", "10.0.1.0/24"), resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.egress.0.to.0.pod_selector.#", "0"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.#", "2"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.0", "Ingress"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.1", "Egress"), ), }, }, @@ -349,6 +363,8 @@ resource "kubernetes_network_policy" "test" { spec { pod_selector {} + + policy_types = [ "Ingress" ] } } `, name) @@ -376,6 +392,7 @@ resource "kubernetes_network_policy" "test" { spec { pod_selector = {} ingress = [] + policy_types = [ "Ingress" ] } } `, name) @@ -421,6 +438,8 @@ resource "kubernetes_network_policy" "test" { ] }, ] + + policy_types = [ "Ingress" ] } } `, name) @@ -476,6 +495,8 @@ resource "kubernetes_network_policy" "test" { ] }, ] + + policy_types = [ "Ingress" ] } } `, name) @@ -554,6 +575,8 @@ resource "kubernetes_network_policy" "test" { ] }, ] + + policy_types = [ "Ingress", "Egress" ] } } `, name) diff --git a/kubernetes/structure_network_policy.go b/kubernetes/structure_network_policy.go index fcb60b3d5e..aee0823d82 100644 --- a/kubernetes/structure_network_policy.go +++ b/kubernetes/structure_network_policy.go @@ -117,6 +117,7 @@ func expandNetworkPolicySpec(l []interface{}) v1.NetworkPolicySpec { if v, ok := in["egress"].([]interface{}); ok && len(v) > 0 { obj.Egress = expandNetworkPolicyEgress(v) } + obj.PolicyTypes = expandNetworkPolicyTypes(in["policy_types"].([]interface{})) } return obj } @@ -140,9 +141,9 @@ func expandNetworkPolicyIngress(l []interface{}) []v1.NetworkPolicyIngressRule { func expandNetworkPolicyEgress(l []interface{}) []v1.NetworkPolicyEgressRule { obj := make([]v1.NetworkPolicyEgressRule, len(l), len(l)) - for i, ingress := range l { - if ingress != nil { - in := ingress.(map[string]interface{}) + for i, egress := range l { + if egress != nil { + in := egress.(map[string]interface{}) obj[i] = v1.NetworkPolicyEgressRule{} if v, ok := in["ports"].([]interface{}); ok && len(v) > 0 { obj[i].Ports = expandNetworkPolicyPorts(v) @@ -210,6 +211,14 @@ func expandIPBlock(l []interface{}) *v1.IPBlock { return obj } +func expandNetworkPolicyTypes(l []interface{}) []v1.PolicyType { + obj := make([]v1.PolicyType, 0, 0) + for _, policyType := range l { + obj = append(obj, v1.PolicyType(policyType.(string))) + } + return obj +} + // Patchers func patchNetworkPolicySpec(keyPrefix, pathPrefix string, d *schema.ResourceData) PatchOperations { @@ -253,7 +262,7 @@ func patchNetworkPolicySpec(keyPrefix, pathPrefix string, d *schema.ResourceData if d.HasChange(keyPrefix + "policy_types") { ops = append(ops, &ReplaceOperation{ Path: pathPrefix + "/policyTypes", - Value: expandStringSlice(d.Get(keyPrefix + "policy_types").([]interface{})), + Value: expandNetworkPolicyTypes(d.Get(keyPrefix + "policy_types").([]interface{})), }) } return ops From 49ef9c35ee8d8d229775439216205a2fe389e74e Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Fri, 5 Oct 2018 11:20:32 +0200 Subject: [PATCH 11/17] Fix website documentation link to network_policy.html --- website/kubernetes.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/kubernetes.erb b/website/kubernetes.erb index c6ca49b200..9f78133fbf 100644 --- a/website/kubernetes.erb +++ b/website/kubernetes.erb @@ -50,7 +50,7 @@ kubernetes_namespace > - kubernetes_network_policy + kubernetes_network_policy > kubernetes_persistent_volume From 3f0106111659c80a42cd03cc600a9e5c6dc5029d Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Fri, 5 Oct 2018 17:44:09 +0200 Subject: [PATCH 12/17] Fix indentation --- kubernetes/resource_kubernetes_network_policy_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/kubernetes/resource_kubernetes_network_policy_test.go b/kubernetes/resource_kubernetes_network_policy_test.go index 9f48f80268..dc4e2cc05a 100644 --- a/kubernetes/resource_kubernetes_network_policy_test.go +++ b/kubernetes/resource_kubernetes_network_policy_test.go @@ -477,7 +477,7 @@ resource "kubernetes_network_policy" "test" { from = [ { - ip_block { + ip_block { cidr = "10.0.0.0/8" except = [ "10.0.0.0/24", @@ -534,7 +534,7 @@ resource "kubernetes_network_policy" "test" { from = [ { - ip_block { + ip_block { cidr = "10.0.0.0/8" except = [ "10.0.0.0/24", @@ -564,7 +564,7 @@ resource "kubernetes_network_policy" "test" { to = [ { - ip_block { + ip_block { cidr = "10.0.0.0/8" except = [ "10.0.0.0/24", From 9304daac6ccf94d6570865c3f9ac9d77ef99ca94 Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Fri, 5 Oct 2018 17:44:46 +0200 Subject: [PATCH 13/17] Add documentation for kubernetes 1.8+ Network Policy fields --- website/docs/r/network_policy.html.markdown | 38 +++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/website/docs/r/network_policy.html.markdown b/website/docs/r/network_policy.html.markdown index e81f44487e..78cc0054ba 100644 --- a/website/docs/r/network_policy.html.markdown +++ b/website/docs/r/network_policy.html.markdown @@ -52,9 +52,22 @@ resource "kubernetes_network_policy" "example" { } } }, + { + ip_block { + cidr = "10.0.0.0/8" + except = [ + "10.0.0.0/24", + "10.0.1.0/24", + ] + } + }, ] }, ] + + egress = [{}] # single empty rule to allow all egress traffic + + policy_types = ["Ingress", "Egress"] } } ``` @@ -88,9 +101,14 @@ The following arguments are supported: #### Arguments +* `egress` - (Optional) List of egress rules to be applied to the selected pods. Outgoing traffic is allowed if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic matches at least one egress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy limits all outgoing traffic (and serves solely to ensure that the pods it selects are isolated by default). This field is beta-level in 1.8 * `ingress` - (Optional) List of ingress rules to be applied to the selected pods. Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic source is the pod's local node, OR if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy does not allow any traffic (and serves solely to ensure that the pods it selects are isolated by default). * `pod_selector` - (Required) Selects the pods to which this NetworkPolicy object applies. The array of ingress rules is applied to any pods selected by this field. Multiple network policies can select the same set of pods. In this case, the ingress rules for each are combined additively. This field is NOT optional and follows standard label selector semantics. An empty podSelector matches all pods in this namespace. +* `policy_types` (Required) List of rule types that the NetworkPolicy relates to. Valid options are `Ingress`, `Egress`, or `Ingress,Egress`. This field is beta-level in 1.8 +**Note**: the native Kubernetes API allows not to specify the `policy_types` property with the following description: + > If this field is not specified, it will default based on the existence of Ingress or Egress rules; policies that contain an Egress section are assumed to affect Egress, and all policies (whether or not they contain an Ingress section) are assumed to affect Ingress. If you want to write an egress-only policy, you must explicitly specify policyTypes [ "Egress" ]. Likewise, if you want to write a policy that specifies that no egress is allowed, you must specify a policyTypes value that include "Egress" (since such a policy would not include an Egress section and would otherwise default to just [ "Ingress" ]). + Leaving the `policy_types` property optional here would have prevented an `egress` rule added to a Network Policy initially created without any `egress` rule nor `policy_types` from working as expected. Indeed, the PolicyTypes would have stuck to Ingress server side as the default value is only computed server side on resource creation, not on updates. ### `ingress` @@ -99,6 +117,11 @@ The following arguments are supported: * `from` - (Optional) List of sources which should be able to access the pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all sources (traffic not restricted by source). If this field is present and contains at least on item, this rule allows traffic only if the traffic matches at least one item in the from list. * `ports` - (Optional) List of ports which should be made accessible on the pods selected for this rule. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. +### `egress` + +#### Arguments +* `to` - (Optional) List of destinations for outgoing traffic of pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all destinations (traffic not restricted by destination). If this field is present and contains at least one item, this rule allows traffic only if the traffic matches at least one item in the to list. +* `ports` - (Optional) List of destination ports for outgoing traffic. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list. ### `from` @@ -116,6 +139,21 @@ The following arguments are supported: * `protocol` - (Optional) The protocol (TCP or UDP) which traffic must match. If not specified, this field defaults to TCP. +### `to` + +#### Arguments + +* `ip_block` - (Optional) IPBlock defines policy on a particular IPBlock +* `namespace_selector` - (Optional) Selects Namespaces using cluster scoped-labels. This matches all pods in all namespaces selected by this label selector. This field follows standard label selector semantics. If present but empty, this selector selects all namespaces. +* `pod_selector` - (Optional) This is a label selector which selects Pods in this namespace. This field follows standard label selector semantics. If present but empty, this selector selects all pods in this namespace. + +### `ip_block` + +#### Arguments + +* `cidr` - (Optional) CIDR is a string representing the IP Block Valid examples are "192.168.1.1/24" +* `except` - (Optional) Except is a slice of CIDRs that should not be included within an IP Block. Valid examples are "192.168.1.1/24". Except values will be rejected if they are outside the CIDR range. + ### `namespace_selector` #### Arguments From f4c95332d10c840d624dcd2e608c5c1cc820ed2e Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Thu, 6 Dec 2018 15:18:43 +0100 Subject: [PATCH 14/17] Allow label selectors updates on network policies --- kubernetes/resource_kubernetes_network_policy.go | 10 +++++----- kubernetes/schema_label_selector.go | 12 ++++++------ kubernetes/schema_persistent_volume_claim.go | 2 +- kubernetes/schema_stateful_set_spec.go | 2 +- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/kubernetes/resource_kubernetes_network_policy.go b/kubernetes/resource_kubernetes_network_policy.go index 8017ab95df..bec1a174ad 100644 --- a/kubernetes/resource_kubernetes_network_policy.go +++ b/kubernetes/resource_kubernetes_network_policy.go @@ -111,7 +111,7 @@ func resourceKubernetesNetworkPolicy() *schema.Resource { Optional: true, MaxItems: 1, Elem: &schema.Resource{ - Schema: labelSelectorFields(), + Schema: labelSelectorFields(true), }, }, "pod_selector": { @@ -120,7 +120,7 @@ func resourceKubernetesNetworkPolicy() *schema.Resource { Optional: true, MaxItems: 1, Elem: &schema.Resource{ - Schema: labelSelectorFields(), + Schema: labelSelectorFields(true), }, }, }, @@ -188,7 +188,7 @@ func resourceKubernetesNetworkPolicy() *schema.Resource { Optional: true, MaxItems: 1, Elem: &schema.Resource{ - Schema: labelSelectorFields(), + Schema: labelSelectorFields(true), }, }, "pod_selector": { @@ -197,7 +197,7 @@ func resourceKubernetesNetworkPolicy() *schema.Resource { Optional: true, MaxItems: 1, Elem: &schema.Resource{ - Schema: labelSelectorFields(), + Schema: labelSelectorFields(true), }, }, }, @@ -212,7 +212,7 @@ func resourceKubernetesNetworkPolicy() *schema.Resource { Required: true, MaxItems: 1, Elem: &schema.Resource{ - Schema: labelSelectorFields(), + Schema: labelSelectorFields(true), }, }, // The policy_types property is made required because the default value is only evaluated server side on resource creation. diff --git a/kubernetes/schema_label_selector.go b/kubernetes/schema_label_selector.go index ceeee79d75..e8fb11ff1b 100644 --- a/kubernetes/schema_label_selector.go +++ b/kubernetes/schema_label_selector.go @@ -4,32 +4,32 @@ import ( "github.com/hashicorp/terraform/helper/schema" ) -func labelSelectorFields() map[string]*schema.Schema { +func labelSelectorFields(updatable bool) map[string]*schema.Schema { return map[string]*schema.Schema{ "match_expressions": { Type: schema.TypeList, Description: "A list of label selector requirements. The requirements are ANDed.", Optional: true, - ForceNew: true, + ForceNew: !updatable, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "key": { Type: schema.TypeString, Description: "The label key that the selector applies to.", Optional: true, - ForceNew: true, + ForceNew: !updatable, }, "operator": { Type: schema.TypeString, Description: "A key's relationship to a set of values. Valid operators ard `In`, `NotIn`, `Exists` and `DoesNotExist`.", Optional: true, - ForceNew: true, + ForceNew: !updatable, }, "values": { Type: schema.TypeSet, Description: "An array of string values. If the operator is `In` or `NotIn`, the values array must be non-empty. If the operator is `Exists` or `DoesNotExist`, the values array must be empty. This array is replaced during a strategic merge patch.", Optional: true, - ForceNew: true, + ForceNew: !updatable, Elem: &schema.Schema{Type: schema.TypeString}, Set: schema.HashString, }, @@ -40,7 +40,7 @@ func labelSelectorFields() map[string]*schema.Schema { Type: schema.TypeMap, Description: "A map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of `match_expressions`, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.", Optional: true, - ForceNew: true, + ForceNew: !updatable, }, } } diff --git a/kubernetes/schema_persistent_volume_claim.go b/kubernetes/schema_persistent_volume_claim.go index 145d65cad5..5e40cb2ed0 100644 --- a/kubernetes/schema_persistent_volume_claim.go +++ b/kubernetes/schema_persistent_volume_claim.go @@ -68,7 +68,7 @@ func persistentVolumeClaimSpecFields() map[string]*schema.Schema { ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ - Schema: labelSelectorFields(), + Schema: labelSelectorFields(false), }, }, "volume_name": { diff --git a/kubernetes/schema_stateful_set_spec.go b/kubernetes/schema_stateful_set_spec.go index 8ec0f432b7..6dc2c225d9 100644 --- a/kubernetes/schema_stateful_set_spec.go +++ b/kubernetes/schema_stateful_set_spec.go @@ -40,7 +40,7 @@ func statefulSetSpecFields(isUpdatable bool) map[string]*schema.Schema { ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ - Schema: labelSelectorFields(), + Schema: labelSelectorFields(false), }, }, "service_name": { From 79f514aa004a6016cfdd559c11d74062988c2672 Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Thu, 13 Dec 2018 11:01:36 +0100 Subject: [PATCH 15/17] Update changelog for #118 --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b35fa9a9d..a8aa48ba56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ BUG FIXES: * `resource/kubernetes_stateful_set`: Fix updates of stateful set images ([#252](https://github.com/terraform-providers/terraform-provider-kubernetes/issues/252)) +FEATURES: + +* **New Resource:** `kubernetes_network_policy` ([#118](https://github.com/terraform-providers/terraform-provider-kubernetes/issues/118)) + ## 1.4.0 (November 29, 2018) FEATURES: From 5c4514496e0bb87694e33ea53e83a1254f5678c8 Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Thu, 13 Dec 2018 12:14:24 +0100 Subject: [PATCH 16/17] Convert returned types to pointers --- .../resource_kubernetes_network_policy.go | 14 +- kubernetes/structure_network_policy.go | 153 ++++++++++++------ kubernetes/structure_network_policy_test.go | 19 +-- 3 files changed, 121 insertions(+), 65 deletions(-) diff --git a/kubernetes/resource_kubernetes_network_policy.go b/kubernetes/resource_kubernetes_network_policy.go index bec1a174ad..08fbf0a324 100644 --- a/kubernetes/resource_kubernetes_network_policy.go +++ b/kubernetes/resource_kubernetes_network_policy.go @@ -239,9 +239,14 @@ func resourceKubernetesNetworkPolicyCreate(d *schema.ResourceData, meta interfac conn := meta.(*kubernetes.Clientset) metadata := expandMetadata(d.Get("metadata").([]interface{})) + spec, err := expandNetworkPolicySpec(d.Get("spec").([]interface{})) + if err != nil { + return err + } + svc := api.NetworkPolicy{ ObjectMeta: metadata, - Spec: expandNetworkPolicySpec(d.Get("spec").([]interface{})), + Spec: *spec, } log.Printf("[INFO] Creating new network policy: %#v", svc) out, err := conn.NetworkingV1().NetworkPolicies(metadata.Namespace).Create(&svc) @@ -294,8 +299,11 @@ func resourceKubernetesNetworkPolicyUpdate(d *schema.ResourceData, meta interfac ops := patchMetadata("metadata.0.", "/metadata/", d) if d.HasChange("spec") { - diffOps := patchNetworkPolicySpec("spec.0.", "/spec", d) - ops = append(ops, diffOps...) + diffOps, err := patchNetworkPolicySpec("spec.0.", "/spec", d) + if err != nil { + return err + } + ops = append(ops, *diffOps...) } data, err := ops.MarshalJSON() if err != nil { diff --git a/kubernetes/structure_network_policy.go b/kubernetes/structure_network_policy.go index aee0823d82..a54ddacab7 100644 --- a/kubernetes/structure_network_policy.go +++ b/kubernetes/structure_network_policy.go @@ -1,11 +1,13 @@ package kubernetes import ( + "fmt" + "strconv" + "github.com/hashicorp/terraform/helper/schema" api "k8s.io/api/core/v1" "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/util/intstr" - "strconv" ) // Flatteners @@ -105,127 +107,165 @@ func flattenIPBlock(in *v1.IPBlock) []interface{} { // Expanders -func expandNetworkPolicySpec(l []interface{}) v1.NetworkPolicySpec { - // There must be exactly one spec element - obj := v1.NetworkPolicySpec{} - for _, spec := range l { - in := spec.(map[string]interface{}) - obj.PodSelector = *expandLabelSelector(in["pod_selector"].([]interface{})) - if v, ok := in["ingress"].([]interface{}); ok && len(v) > 0 { - obj.Ingress = expandNetworkPolicyIngress(v) +func expandNetworkPolicySpec(in []interface{}) (*v1.NetworkPolicySpec, error) { + spec := v1.NetworkPolicySpec{} + + if len(in) == 0 || in[0] == nil { + return nil, fmt.Errorf("failed to expand NetworkPolicy.Spec: null or empty input") + } + + m := in[0].(map[string]interface{}) + spec.PodSelector = *expandLabelSelector(m["pod_selector"].([]interface{})) + if v, ok := m["ingress"].([]interface{}); ok && len(v) > 0 { + ingress, err := expandNetworkPolicyIngress(v) + if err != nil { + return nil, err } - if v, ok := in["egress"].([]interface{}); ok && len(v) > 0 { - obj.Egress = expandNetworkPolicyEgress(v) + spec.Ingress = *ingress + } + if v, ok := m["egress"].([]interface{}); ok && len(v) > 0 { + egress, err := expandNetworkPolicyEgress(v) + if err != nil { + return nil, err } - obj.PolicyTypes = expandNetworkPolicyTypes(in["policy_types"].([]interface{})) + spec.Egress = *egress } - return obj + policyTypes, err := expandNetworkPolicyTypes(m["policy_types"].([]interface{})) + if err != nil { + return nil, err + } + spec.PolicyTypes = *policyTypes + + return &spec, nil } -func expandNetworkPolicyIngress(l []interface{}) []v1.NetworkPolicyIngressRule { - obj := make([]v1.NetworkPolicyIngressRule, len(l), len(l)) +func expandNetworkPolicyIngress(l []interface{}) (*[]v1.NetworkPolicyIngressRule, error) { + ingresses := make([]v1.NetworkPolicyIngressRule, len(l), len(l)) for i, ingress := range l { if ingress != nil { in := ingress.(map[string]interface{}) - obj[i] = v1.NetworkPolicyIngressRule{} + ingresses[i] = v1.NetworkPolicyIngressRule{} if v, ok := in["ports"].([]interface{}); ok && len(v) > 0 { - obj[i].Ports = expandNetworkPolicyPorts(v) + policyPorts, err := expandNetworkPolicyPorts(v) + if err != nil { + return nil, err + } + ingresses[i].Ports = *policyPorts } if v, ok := in["from"].([]interface{}); ok && len(v) > 0 { - obj[i].From = expandNetworkPolicyPeer(v) + policyPeers, err := expandNetworkPolicyPeer(v) + if err != nil { + return nil, err + } + ingresses[i].From = *policyPeers } } } - return obj + return &ingresses, nil } -func expandNetworkPolicyEgress(l []interface{}) []v1.NetworkPolicyEgressRule { - obj := make([]v1.NetworkPolicyEgressRule, len(l), len(l)) +func expandNetworkPolicyEgress(l []interface{}) (*[]v1.NetworkPolicyEgressRule, error) { + egresses := make([]v1.NetworkPolicyEgressRule, len(l), len(l)) for i, egress := range l { if egress != nil { in := egress.(map[string]interface{}) - obj[i] = v1.NetworkPolicyEgressRule{} + egresses[i] = v1.NetworkPolicyEgressRule{} if v, ok := in["ports"].([]interface{}); ok && len(v) > 0 { - obj[i].Ports = expandNetworkPolicyPorts(v) + policyPorts, err := expandNetworkPolicyPorts(v) + if err != nil { + return nil, err + } + egresses[i].Ports = *policyPorts } if v, ok := in["to"].([]interface{}); ok && len(v) > 0 { - obj[i].To = expandNetworkPolicyPeer(v) + policyPeers, err := expandNetworkPolicyPeer(v) + if err != nil { + return nil, err + } + egresses[i].To = *policyPeers } } } - return obj + return &egresses, nil } -func expandNetworkPolicyPorts(l []interface{}) []v1.NetworkPolicyPort { - obj := make([]v1.NetworkPolicyPort, len(l), len(l)) +func expandNetworkPolicyPorts(l []interface{}) (*[]v1.NetworkPolicyPort, error) { + policyPorts := make([]v1.NetworkPolicyPort, len(l), len(l)) for i, port := range l { in := port.(map[string]interface{}) if in["port"] != nil && in["port"] != "" { portStr := in["port"].(string) if portInt, err := strconv.Atoi(portStr); err == nil && strconv.Itoa(portInt) == portStr { v := intstr.FromInt(portInt) - obj[i].Port = &v + policyPorts[i].Port = &v } else { v := intstr.FromString(portStr) - obj[i].Port = &v + policyPorts[i].Port = &v } } if in["protocol"] != nil && in["protocol"] != "" { v := api.Protocol(in["protocol"].(string)) - obj[i].Protocol = &v + policyPorts[i].Protocol = &v } } - return obj + return &policyPorts, nil } -func expandNetworkPolicyPeer(l []interface{}) []v1.NetworkPolicyPeer { - obj := make([]v1.NetworkPolicyPeer, len(l), len(l)) +func expandNetworkPolicyPeer(l []interface{}) (*[]v1.NetworkPolicyPeer, error) { + policyPeers := make([]v1.NetworkPolicyPeer, len(l), len(l)) for i, peer := range l { in := peer.(map[string]interface{}) if v, ok := in["ip_block"].([]interface{}); ok && len(v) > 0 { - obj[i].IPBlock = expandIPBlock(v) + ipBlock, err := expandIPBlock(v) + if err != nil { + return nil, err + } + policyPeers[i].IPBlock = ipBlock } if v, ok := in["namespace_selector"].([]interface{}); ok && len(v) > 0 { - obj[i].NamespaceSelector = expandLabelSelector(v) + policyPeers[i].NamespaceSelector = expandLabelSelector(v) } if v, ok := in["pod_selector"].([]interface{}); ok && len(v) > 0 { - obj[i].PodSelector = expandLabelSelector(v) + policyPeers[i].PodSelector = expandLabelSelector(v) } } - return obj + return &policyPeers, nil } -func expandIPBlock(l []interface{}) *v1.IPBlock { - obj := &v1.IPBlock{} +func expandIPBlock(l []interface{}) (*v1.IPBlock, error) { + ipBlock := v1.IPBlock{} if len(l) == 0 || l[0] == nil { - return &v1.IPBlock{} + return nil, fmt.Errorf("failed to expand IPBlock: null or empty input") } in := l[0].(map[string]interface{}) if v, ok := in["cidr"].(string); ok && v != "" { - obj.CIDR = v + ipBlock.CIDR = v } if v, ok := in["except"].([]interface{}); ok && len(v) > 0 { - obj.Except = expandStringSlice(v) + ipBlock.Except = expandStringSlice(v) } - return obj + return &ipBlock, nil } -func expandNetworkPolicyTypes(l []interface{}) []v1.PolicyType { - obj := make([]v1.PolicyType, 0, 0) +func expandNetworkPolicyTypes(l []interface{}) (*[]v1.PolicyType, error) { + policyTypes := make([]v1.PolicyType, 0, 0) for _, policyType := range l { - obj = append(obj, v1.PolicyType(policyType.(string))) + policyTypes = append(policyTypes, v1.PolicyType(policyType.(string))) } - return obj + return &policyTypes, nil } // Patchers -func patchNetworkPolicySpec(keyPrefix, pathPrefix string, d *schema.ResourceData) PatchOperations { - ops := make([]PatchOperation, 0, 0) +func patchNetworkPolicySpec(keyPrefix, pathPrefix string, d *schema.ResourceData) (*PatchOperations, error) { + ops := make(PatchOperations, 0, 0) if d.HasChange(keyPrefix + "ingress") { oldV, _ := d.GetChange(keyPrefix + "ingress") - ingress := expandNetworkPolicyIngress(d.Get(keyPrefix + "ingress").([]interface{})) + ingress, err := expandNetworkPolicyIngress(d.Get(keyPrefix + "ingress").([]interface{})) + if err != nil { + return nil, err + } if len(oldV.([]interface{})) == 0 { ops = append(ops, &AddOperation{ Path: pathPrefix + "/ingress", @@ -240,7 +280,10 @@ func patchNetworkPolicySpec(keyPrefix, pathPrefix string, d *schema.ResourceData } if d.HasChange(keyPrefix + "egress") { oldV, _ := d.GetChange(keyPrefix + "egress") - egress := expandNetworkPolicyEgress(d.Get(keyPrefix + "egress").([]interface{})) + egress, err := expandNetworkPolicyEgress(d.Get(keyPrefix + "egress").([]interface{})) + if err != nil { + return nil, err + } if len(oldV.([]interface{})) == 0 { ops = append(ops, &AddOperation{ Path: pathPrefix + "/egress", @@ -260,10 +303,14 @@ func patchNetworkPolicySpec(keyPrefix, pathPrefix string, d *schema.ResourceData }) } if d.HasChange(keyPrefix + "policy_types") { + policyTypes, err := expandNetworkPolicyTypes(d.Get(keyPrefix + "policy_types").([]interface{})) + if err != nil { + return nil, err + } ops = append(ops, &ReplaceOperation{ Path: pathPrefix + "/policyTypes", - Value: expandNetworkPolicyTypes(d.Get(keyPrefix + "policy_types").([]interface{})), + Value: *policyTypes, }) } - return ops + return &ops, nil } diff --git a/kubernetes/structure_network_policy_test.go b/kubernetes/structure_network_policy_test.go index 0aefec953d..ce9b83ff03 100644 --- a/kubernetes/structure_network_policy_test.go +++ b/kubernetes/structure_network_policy_test.go @@ -4,14 +4,15 @@ import ( api "k8s.io/api/core/v1" "k8s.io/api/networking/v1" - "k8s.io/apimachinery/pkg/util/intstr" "reflect" "testing" + + "k8s.io/apimachinery/pkg/util/intstr" ) var ( - protoTcp = api.ProtocolTCP - protoUdp = api.ProtocolUDP + protoTCP = api.ProtocolTCP + protoUDP = api.ProtocolUDP portName = intstr.FromString("http") portNumerical = intstr.FromInt(8125) ) @@ -25,7 +26,7 @@ func TestFlattenNetworkPolicyIngressPorts(t *testing.T) { { []v1.NetworkPolicyPort{{ Port: &portName, - Protocol: &protoTcp, + Protocol: &protoTCP, }}, []interface{}{ map[string]interface{}{ @@ -47,7 +48,7 @@ func TestFlattenNetworkPolicyIngressPorts(t *testing.T) { { []v1.NetworkPolicyPort{{ Port: &portNumerical, - Protocol: &protoUdp, + Protocol: &protoUDP, }}, []interface{}{ map[string]interface{}{ @@ -90,7 +91,7 @@ func TestExpandNetworkPolicyIngressPorts(t *testing.T) { }, []v1.NetworkPolicyPort{{ Port: &portName, - Protocol: &protoTcp, + Protocol: &protoTCP, }}, }, { @@ -112,7 +113,7 @@ func TestExpandNetworkPolicyIngressPorts(t *testing.T) { }, []v1.NetworkPolicyPort{{ Port: &portNumerical, - Protocol: &protoUdp, + Protocol: &protoUDP, }}, }, { @@ -126,8 +127,8 @@ func TestExpandNetworkPolicyIngressPorts(t *testing.T) { } for _, tc := range cases { - output := expandNetworkPolicyPorts(tc.Input) - if !reflect.DeepEqual(output, tc.ExpectedOutput) { + output, _ := expandNetworkPolicyPorts(tc.Input) + if !reflect.DeepEqual(output, &tc.ExpectedOutput) { t.Fatalf("Unexpected output from flattener.\nExpected: %#v\nGiven: %#v", tc.ExpectedOutput, output) } From 2c816702cbd8d55c821ef459f6bcc55227a59eac Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Thu, 10 Jan 2019 14:30:30 +0100 Subject: [PATCH 17/17] Remove `d.SetId("")` --- kubernetes/resource_kubernetes_network_policy.go | 1 - 1 file changed, 1 deletion(-) diff --git a/kubernetes/resource_kubernetes_network_policy.go b/kubernetes/resource_kubernetes_network_policy.go index 08fbf0a324..43bedf9aac 100644 --- a/kubernetes/resource_kubernetes_network_policy.go +++ b/kubernetes/resource_kubernetes_network_policy.go @@ -335,7 +335,6 @@ func resourceKubernetesNetworkPolicyDelete(d *schema.ResourceData, meta interfac log.Printf("[INFO] Network Policy %s deleted", name) - d.SetId("") return nil }