From bd7821f40b3d1501312e8b9fb61daf3fdddef6dc Mon Sep 17 00:00:00 2001 From: Patrick Decat Date: Thu, 10 Jan 2019 14:38:20 +0100 Subject: [PATCH] Add network policy resource with support for 1.8+ fields (#118) Add kubernetes_network_policy resource --- CHANGELOG.md | 4 + kubernetes/provider.go | 1 + .../resource_kubernetes_network_policy.go | 358 +++++++++++ ...resource_kubernetes_network_policy_test.go | 583 ++++++++++++++++++ kubernetes/schema_label_selector.go | 12 +- kubernetes/schema_persistent_volume_claim.go | 2 +- kubernetes/schema_stateful_set_spec.go | 2 +- kubernetes/structure_network_policy.go | 316 ++++++++++ kubernetes/structure_network_policy_test.go | 136 ++++ website/docs/r/network_policy.html.markdown | 188 ++++++ website/kubernetes.erb | 3 + 11 files changed, 1597 insertions(+), 8 deletions(-) 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 create mode 100644 kubernetes/structure_network_policy_test.go create mode 100644 website/docs/r/network_policy.html.markdown 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: 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..43bedf9aac --- /dev/null +++ b/kubernetes/resource_kubernetes_network_policy.go @@ -0,0 +1,358 @@ +package kubernetes + +import ( + "fmt" + "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" +) + +// 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"] + 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"] + 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 { + 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, + Default: "TCP", + }, + }, + }, + }, + "from": { + Type: schema.TypeList, + Description: networkPolicyIngressRuleFromDoc, + 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(true), + }, + }, + "pod_selector": { + Type: schema.TypeList, + Description: networkPolicyPeerPodSelectorDoc, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: labelSelectorFields(true), + }, + }, + }, + }, + }, + }, + }, + }, + "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, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: labelSelectorFields(true), + }, + }, + "pod_selector": { + Type: schema.TypeList, + Description: networkPolicyPeerPodSelectorDoc, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: labelSelectorFields(true), + }, + }, + }, + }, + }, + }, + }, + }, + "pod_selector": { + Type: schema.TypeList, + Description: networkPolicySpecPodSelectorDoc, + Required: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: labelSelectorFields(true), + }, + }, + // 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, + Required: true, + MinItems: 1, + MaxItems: 2, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + }, + }, + }, + }, + } +} + +func resourceKubernetesNetworkPolicyCreate(d *schema.ResourceData, meta interface{}) error { + 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: *spec, + } + 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, err := patchNetworkPolicySpec("spec.0.", "/spec", d) + if err != nil { + return err + } + 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) + + 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..dc4e2cc05a --- /dev/null +++ b/kubernetes/resource_kubernetes_network_policy_test.go @@ -0,0 +1,583 @@ +package kubernetes + +import ( + "fmt" + "testing" + + "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" +) + +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"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.0", "Ingress"), + ), + }, + { + 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"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.0", "Ingress"), + ), + }, + { + 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"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.0", "Ingress"), + ), + }, + { + 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.#", "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.policy_types.#", "1"), + resource.TestCheckResourceAttr("kubernetes_network_policy.test", "spec.0.policy_types.0", "Ingress"), + ), + }, + { + 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"), + 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"), + ), + }, + }, + }) +} + +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"), + 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"), + 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"), + ), + }, + }, + }) +} + +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 {} + + policy_types = [ "Ingress" ] + } +} +`, 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 = [] + policy_types = [ "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" + }, + { + port = "8125" + protocol = "UDP" + }, + ] + + from = [ + { + namespace_selector { + match_labels = { + name = "default" + } + } + }, + ] + }, + ] + + policy_types = [ "Ingress" ] + } +} + `, 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 = [ + { + 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" + } + } + }, + ] + }, + ] + + policy_types = [ "Ingress" ] + } +} + `, name) +} + +func testAccKubernetesNetworkPolicyConfig_withEgress(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", + ] + } + }, + ] + }, + ] + + policy_types = [ "Ingress", "Egress" ] + } +} + `, name) +} 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": { diff --git a/kubernetes/structure_network_policy.go b/kubernetes/structure_network_policy.go new file mode 100644 index 0000000000..a54ddacab7 --- /dev/null +++ b/kubernetes/structure_network_policy.go @@ -0,0 +1,316 @@ +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" +) + +// Flatteners + +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} +} + +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"] = flattenNetworkPolicyPorts(ingress.Ports) + } + if ingress.From != nil && len(ingress.From) > 0 { + m["from"] = flattenNetworkPolicyPeer(ingress.From) + } + att[i] = m + } + return att +} + +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{}) + 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"] = string(*port.Protocol) + } + att[i] = m + } + return att +} + +func flattenNetworkPolicyPeer(in []v1.NetworkPolicyPeer) []interface{} { + att := make([]interface{}, len(in), len(in)) + for i, peer := range in { + m := make(map[string]interface{}) + if peer.IPBlock != nil { + m["ip_block"] = flattenIPBlock(peer.IPBlock) + } + if peer.NamespaceSelector != nil { + m["namespace_selector"] = flattenLabelSelector(peer.NamespaceSelector) + } + 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(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 + } + spec.Ingress = *ingress + } + if v, ok := m["egress"].([]interface{}); ok && len(v) > 0 { + egress, err := expandNetworkPolicyEgress(v) + if err != nil { + return nil, err + } + spec.Egress = *egress + } + 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, error) { + ingresses := make([]v1.NetworkPolicyIngressRule, len(l), len(l)) + for i, ingress := range l { + if ingress != nil { + in := ingress.(map[string]interface{}) + ingresses[i] = v1.NetworkPolicyIngressRule{} + if v, ok := in["ports"].([]interface{}); ok && len(v) > 0 { + policyPorts, err := expandNetworkPolicyPorts(v) + if err != nil { + return nil, err + } + ingresses[i].Ports = *policyPorts + } + if v, ok := in["from"].([]interface{}); ok && len(v) > 0 { + policyPeers, err := expandNetworkPolicyPeer(v) + if err != nil { + return nil, err + } + ingresses[i].From = *policyPeers + } + } + } + return &ingresses, nil +} + +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{}) + egresses[i] = v1.NetworkPolicyEgressRule{} + if v, ok := in["ports"].([]interface{}); ok && len(v) > 0 { + policyPorts, err := expandNetworkPolicyPorts(v) + if err != nil { + return nil, err + } + egresses[i].Ports = *policyPorts + } + if v, ok := in["to"].([]interface{}); ok && len(v) > 0 { + policyPeers, err := expandNetworkPolicyPeer(v) + if err != nil { + return nil, err + } + egresses[i].To = *policyPeers + } + } + } + return &egresses, nil +} + +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) + policyPorts[i].Port = &v + } else { + v := intstr.FromString(portStr) + policyPorts[i].Port = &v + } + } + if in["protocol"] != nil && in["protocol"] != "" { + v := api.Protocol(in["protocol"].(string)) + policyPorts[i].Protocol = &v + + } + } + return &policyPorts, nil +} + +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 { + 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 { + policyPeers[i].NamespaceSelector = expandLabelSelector(v) + } + if v, ok := in["pod_selector"].([]interface{}); ok && len(v) > 0 { + policyPeers[i].PodSelector = expandLabelSelector(v) + } + } + return &policyPeers, nil +} + +func expandIPBlock(l []interface{}) (*v1.IPBlock, error) { + ipBlock := v1.IPBlock{} + if len(l) == 0 || l[0] == nil { + 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 != "" { + ipBlock.CIDR = v + } + if v, ok := in["except"].([]interface{}); ok && len(v) > 0 { + ipBlock.Except = expandStringSlice(v) + } + return &ipBlock, nil +} + +func expandNetworkPolicyTypes(l []interface{}) (*[]v1.PolicyType, error) { + policyTypes := make([]v1.PolicyType, 0, 0) + for _, policyType := range l { + policyTypes = append(policyTypes, v1.PolicyType(policyType.(string))) + } + return &policyTypes, nil +} + +// Patchers + +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, 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", + Value: ingress, + }) + } else { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/ingress", + Value: ingress, + }) + } + } + if d.HasChange(keyPrefix + "egress") { + oldV, _ := d.GetChange(keyPrefix + "egress") + 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", + Value: egress, + }) + } else { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/egress", + Value: egress, + }) + } + } + if d.HasChange(keyPrefix + "pod_selector") { + ops = append(ops, &ReplaceOperation{ + Path: pathPrefix + "/podSelector", + Value: expandLabelSelector(d.Get(keyPrefix + "pod_selector").([]interface{})), + }) + } + 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: *policyTypes, + }) + } + return &ops, nil +} diff --git a/kubernetes/structure_network_policy_test.go b/kubernetes/structure_network_policy_test.go new file mode 100644 index 0000000000..ce9b83ff03 --- /dev/null +++ b/kubernetes/structure_network_policy_test.go @@ -0,0 +1,136 @@ +package kubernetes + +import ( + api "k8s.io/api/core/v1" + "k8s.io/api/networking/v1" + + "reflect" + "testing" + + "k8s.io/apimachinery/pkg/util/intstr" +) + +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 := flattenNetworkPolicyPorts(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, _ := expandNetworkPolicyPorts(tc.Input) + if !reflect.DeepEqual(output, &tc.ExpectedOutput) { + t.Fatalf("Unexpected output from flattener.\nExpected: %#v\nGiven: %#v", + tc.ExpectedOutput, output) + } + } +} diff --git a/website/docs/r/network_policy.html.markdown b/website/docs/r/network_policy.html.markdown new file mode 100644 index 0000000000..78cc0054ba --- /dev/null +++ b/website/docs/r/network_policy.html.markdown @@ -0,0 +1,188 @@ +--- +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" + } + } + }, + { + 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"] + } +} +``` + +## 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 + +* `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` + +#### 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. + +### `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` + +#### 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. + + +### `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 + +* `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..9f78133fbf 100644 --- a/website/kubernetes.erb +++ b/website/kubernetes.erb @@ -49,6 +49,9 @@ > kubernetes_namespace + > + kubernetes_network_policy + > kubernetes_persistent_volume