From dd37e9213775067f60dcd419a0be83939678abef Mon Sep 17 00:00:00 2001 From: Jaylon McShan Date: Fri, 15 Nov 2024 17:57:23 -0600 Subject: [PATCH] Remove deprecated PodSecurityPolicy resource and update PersistentVolumeClaim handling --- kubernetes/provider.go | 6 +- ..._kubernetes_pod_security_policy_v1beta1.go | 523 -------------- ...rnetes_pod_security_policy_v1beta1_test.go | 396 ----------- .../structure_persistent_volume_claim.go | 10 +- .../structure_pod_security_policy_spec.go | 664 ------------------ 5 files changed, 7 insertions(+), 1592 deletions(-) delete mode 100644 kubernetes/resource_kubernetes_pod_security_policy_v1beta1.go delete mode 100644 kubernetes/resource_kubernetes_pod_security_policy_v1beta1_test.go delete mode 100644 kubernetes/structure_pod_security_policy_spec.go diff --git a/kubernetes/provider.go b/kubernetes/provider.go index f0018379df..bbe08e3642 100644 --- a/kubernetes/provider.go +++ b/kubernetes/provider.go @@ -330,10 +330,8 @@ func Provider() *schema.Provider { "kubernetes_network_policy_v1": resourceKubernetesNetworkPolicyV1(), // policy - "kubernetes_pod_disruption_budget": resourceKubernetesPodDisruptionBudget(), - "kubernetes_pod_disruption_budget_v1": resourceKubernetesPodDisruptionBudgetV1(), - "kubernetes_pod_security_policy": resourceKubernetesPodSecurityPolicyV1Beta1(), - "kubernetes_pod_security_policy_v1beta1": resourceKubernetesPodSecurityPolicyV1Beta1(), + "kubernetes_pod_disruption_budget": resourceKubernetesPodDisruptionBudget(), + "kubernetes_pod_disruption_budget_v1": resourceKubernetesPodDisruptionBudgetV1(), // scheduling "kubernetes_priority_class": resourceKubernetesPriorityClassV1(), diff --git a/kubernetes/resource_kubernetes_pod_security_policy_v1beta1.go b/kubernetes/resource_kubernetes_pod_security_policy_v1beta1.go deleted file mode 100644 index da8b3696b7..0000000000 --- a/kubernetes/resource_kubernetes_pod_security_policy_v1beta1.go +++ /dev/null @@ -1,523 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package kubernetes - -import ( - "context" - "log" - - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - policy "k8s.io/api/policy/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - pkgApi "k8s.io/apimachinery/pkg/types" -) - -// Use generated swagger docs from kubernetes' client-go to avoid copy/pasting them here -var ( - pspSpecDoc = policy.PodSecurityPolicy{}.SwaggerDoc()["spec"] - pspSpecAllowPrivilegeEscalationDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowPrivilegeEscalation"] - pspSpecAllowedCapabilitiesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowedCapabilities"] - pspSpecAllowedFlexVolumesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowedFlexVolumes"] - pspAllowedFlexVolumesDriverDoc = policy.AllowedFlexVolume{}.SwaggerDoc()["driver"] - pspSpecAllowedHostPathsDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowedHostPaths"] - pspAllowedHostPathsPathPrefixDoc = policy.AllowedHostPath{}.SwaggerDoc()["pathPrefix"] - pspAllowedHostPathsReadOnlyDoc = policy.AllowedHostPath{}.SwaggerDoc()["readOnly"] - pspSpecAllowedProcMountTypesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowedProcMountTypes"] - pspSpecAllowedUnsafeSysctlsDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["allowedUnsafeSysctls"] - pspSpecDefaultAddCapabilitiesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["defaultAddCapabilities"] - pspSpecDefaultAllowPrivilegeEscalationDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["defaultAllowPrivilegeEscalation"] - pspSpecForbiddenSysctlsDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["forbiddenSysctls"] - pspSpecFSGroupDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["fsGroup"] - pspFSGroupIDRangeDoc = policy.FSGroupStrategyOptions{}.SwaggerDoc()["ranges"] - pspIDRangeMinDoc = policy.IDRange{}.SwaggerDoc()["min"] - pspIDRangeMaxDoc = policy.IDRange{}.SwaggerDoc()["max"] - pspFSGroupRuleDoc = policy.FSGroupStrategyOptions{}.SwaggerDoc()["rule"] - pspSpecHostIPCDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["hostIPC"] - pspSpecHostNetworkDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["hostNetwork"] - pspSpecHostPIDDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["hostPID"] - pspSpecHostPortsDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["hostPorts"] - pspHostPortRangeMinDoc = policy.HostPortRange{}.SwaggerDoc()["min"] - pspHostPortRangeMaxDoc = policy.HostPortRange{}.SwaggerDoc()["max"] - pspSpecPrivilegedDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["privileged"] - pspSpecReadOnlyRootFilesystemDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["readOnlyRootFilesystem"] - pspSpecRequiredDropCapabilitiesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["requiredDropCapabilities"] - pspSpecRunAsUserDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["runAsUser"] - pspRunAsUserIDRangeDoc = policy.RunAsUserStrategyOptions{}.SwaggerDoc()["ranges"] - pspRunAsUserRuleDoc = policy.RunAsUserStrategyOptions{}.SwaggerDoc()["rule"] - pspSpecSELinuxDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["seLinux"] - pspSELinuxOptionsDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["seLinuxOptions"] - pspSELinuxOptionsLevelDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["level"] - pspSELinuxOptionsRoleDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["role"] - pspSELinuxOptionsTypeDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["type"] - pspSELinuxOptionsUserDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["user"] - pspSELinuxOptionsRuleDoc = policy.SELinuxStrategyOptions{}.SwaggerDoc()["rule"] - pspSpecSupplementalGroupsDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["supplementalGroups"] - pspSupplementalGroupsRangesDoc = policy.SupplementalGroupsStrategyOptions{}.SwaggerDoc()["ranges"] - pspSupplementalGroupsRuleDoc = policy.SupplementalGroupsStrategyOptions{}.SwaggerDoc()["rule"] - pspSpecVolumesDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["volumes"] - pspSpecRunAsGroupDoc = policy.PodSecurityPolicySpec{}.SwaggerDoc()["runAsGroup"] - pspRunAsGroupIDRangeDoc = policy.RunAsGroupStrategyOptions{}.SwaggerDoc()["ranges"] - pspRunAsGroupRuleDoc = policy.RunAsGroupStrategyOptions{}.SwaggerDoc()["rule"] -) - -func resourceKubernetesPodSecurityPolicyV1Beta1() *schema.Resource { - return &schema.Resource{ - DeprecationMessage: `"PodSecurityPolicy" was deprecated in Kubernetes v1.21.0; Starting from version 1.21.0 Kubernetes has deprecated PodSecurityPolicy and has been removed entirely in v1.25.0`, - Description: "A Pod Security Policy is a cluster-level resource that controls security sensitive aspects of the pod specification. The PodSecurityPolicy objects define a set of conditions that a pod must run with in order to be accepted into the system, as well as defaults for the related fields.", - CreateContext: resourceKubernetesPodSecurityPolicyV1Beta1Create, - ReadContext: resourceKubernetesPodSecurityPolicyV1Beta1Read, - UpdateContext: resourceKubernetesPodSecurityPolicyV1Beta1Update, - DeleteContext: resourceKubernetesPodSecurityPolicyV1Beta1Delete, - Importer: &schema.ResourceImporter{ - StateContext: schema.ImportStatePassthroughContext, - }, - - Schema: map[string]*schema.Schema{ - "metadata": metadataSchema("podsecuritypolicy", false), - "spec": { - Type: schema.TypeList, - Description: pspSpecDoc, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "allow_privilege_escalation": { - Type: schema.TypeBool, - Description: pspSpecAllowPrivilegeEscalationDoc, - Optional: true, - Computed: true, - }, - "allowed_capabilities": { - Type: schema.TypeList, - Description: pspSpecAllowedCapabilitiesDoc, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "allowed_flex_volumes": { - Type: schema.TypeList, - Description: pspSpecAllowedFlexVolumesDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "driver": { - Type: schema.TypeString, - Description: pspAllowedFlexVolumesDriverDoc, - Required: true, - }, - }, - }, - }, - "allowed_host_paths": { - Type: schema.TypeList, - Description: pspSpecAllowedHostPathsDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "path_prefix": { - Type: schema.TypeString, - Description: pspAllowedHostPathsPathPrefixDoc, - Required: true, - }, - "read_only": { - Type: schema.TypeBool, - Description: pspAllowedHostPathsReadOnlyDoc, - Optional: true, - }, - }, - }, - }, - "allowed_proc_mount_types": { - Type: schema.TypeList, - Description: pspSpecAllowedProcMountTypesDoc, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "allowed_unsafe_sysctls": { - Type: schema.TypeList, - Description: pspSpecAllowedUnsafeSysctlsDoc, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "default_add_capabilities": { - Type: schema.TypeList, - Description: pspSpecDefaultAddCapabilitiesDoc, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "default_allow_privilege_escalation": { - Type: schema.TypeBool, - Description: pspSpecDefaultAllowPrivilegeEscalationDoc, - Optional: true, - Computed: true, - }, - "forbidden_sysctls": { - Type: schema.TypeList, - Description: pspSpecForbiddenSysctlsDoc, - Optional: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "fs_group": { - Type: schema.TypeList, - Description: pspSpecFSGroupDoc, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "range": { - Type: schema.TypeList, - Description: pspFSGroupIDRangeDoc, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: idRangeSchema(), - }, - }, - "rule": { - Type: schema.TypeString, - Description: pspFSGroupRuleDoc, - Required: true, - }, - }, - }, - }, - "host_ipc": { - Type: schema.TypeBool, - Description: pspSpecHostIPCDoc, - Optional: true, - Computed: true, - }, - "host_network": { - Type: schema.TypeBool, - Description: pspSpecHostNetworkDoc, - Optional: true, - Computed: true, - }, - "host_pid": { - Type: schema.TypeBool, - Description: pspSpecHostPIDDoc, - Optional: true, - Computed: true, - }, - "host_ports": { - Type: schema.TypeList, - Description: pspSpecHostPortsDoc, - Optional: true, - Computed: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "min": { - Type: schema.TypeInt, - Description: pspHostPortRangeMinDoc, - Required: true, - }, - "max": { - Type: schema.TypeInt, - Description: pspHostPortRangeMaxDoc, - Required: true, - }, - }, - }, - }, - "privileged": { - Type: schema.TypeBool, - Description: pspSpecPrivilegedDoc, - Optional: true, - Computed: true, - }, - "read_only_root_filesystem": { - Type: schema.TypeBool, - Description: pspSpecReadOnlyRootFilesystemDoc, - Optional: true, - Computed: true, - }, - "required_drop_capabilities": { - Type: schema.TypeList, - Description: pspSpecRequiredDropCapabilitiesDoc, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "run_as_user": { - Type: schema.TypeList, - Description: pspSpecRunAsUserDoc, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "range": { - Type: schema.TypeList, - Description: pspRunAsUserIDRangeDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: idRangeSchema(), - }, - }, - "rule": { - Type: schema.TypeString, - Description: pspRunAsUserRuleDoc, - Required: true, - }, - }, - }, - }, - "run_as_group": { - Type: schema.TypeList, - Description: pspSpecRunAsGroupDoc, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "range": { - Type: schema.TypeList, - Description: pspRunAsGroupIDRangeDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: idRangeSchema(), - }, - }, - "rule": { - Type: schema.TypeString, - Description: pspRunAsGroupRuleDoc, - Required: true, - }, - }, - }, - }, - "se_linux": { - Type: schema.TypeList, - Description: pspSpecSELinuxDoc, - Optional: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "se_linux_options": { - Type: schema.TypeList, - Description: pspSELinuxOptionsDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "level": { - Type: schema.TypeString, - Description: pspSELinuxOptionsLevelDoc, - Required: true, - }, - "role": { - Type: schema.TypeString, - Description: pspSELinuxOptionsRoleDoc, - Required: true, - }, - "type": { - Type: schema.TypeString, - Description: pspSELinuxOptionsTypeDoc, - Required: true, - }, - "user": { - Type: schema.TypeString, - Description: pspSELinuxOptionsUserDoc, - Required: true, - }, - }, - }, - }, - "rule": { - Type: schema.TypeString, - Description: pspSELinuxOptionsRuleDoc, - Required: true, - }, - }, - }, - }, - "supplemental_groups": { - Type: schema.TypeList, - Description: pspSpecSupplementalGroupsDoc, - Required: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "range": { - Type: schema.TypeList, - Description: pspSupplementalGroupsRangesDoc, - Optional: true, - Elem: &schema.Resource{ - Schema: idRangeSchema(), - }, - }, - "rule": { - Type: schema.TypeString, - Description: pspSupplementalGroupsRuleDoc, - Required: true, - }, - }, - }, - }, - "volumes": { - Type: schema.TypeList, - Description: pspSpecVolumesDoc, - Optional: true, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - }, - }, - }, - }, - } -} - -func resourceKubernetesPodSecurityPolicyV1Beta1Create(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return diag.FromErr(err) - } - - metadata := expandMetadata(d.Get("metadata").([]interface{})) - spec, err := expandPodSecurityPolicySpec(d.Get("spec").([]interface{})) - - if err != nil { - return diag.FromErr(err) - } - - psp := &policy.PodSecurityPolicy{ - ObjectMeta: metadata, - Spec: spec, - } - - log.Printf("[INFO] Creating new PodSecurityPolicy: %#v", psp) - out, err := conn.PolicyV1beta1().PodSecurityPolicies().Create(ctx, psp, metav1.CreateOptions{}) - - if err != nil { - return diag.FromErr(err) - } - log.Printf("[INFO] Submitted new PodSecurityPolicy: %#v", out) - d.SetId(out.Name) - - return resourceKubernetesPodSecurityPolicyV1Beta1Read(ctx, d, meta) -} - -func resourceKubernetesPodSecurityPolicyV1Beta1Read(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - exists, err := resourceKubernetesPodSecurityPolicyV1Beta1Exists(ctx, d, meta) - if err != nil { - return diag.FromErr(err) - } - if !exists { - d.SetId("") - return diag.Diagnostics{} - } - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return diag.FromErr(err) - } - - name := d.Id() - - log.Printf("[INFO] Reading PodSecurityPolicy %s", name) - psp, err := conn.PolicyV1beta1().PodSecurityPolicies().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - log.Printf("[DEBUG] Received error: %#v", err) - return diag.FromErr(err) - } - - log.Printf("[INFO] Received PodSecurityPolicy: %#v", psp) - err = d.Set("metadata", flattenMetadata(psp.ObjectMeta, d, meta)) - if err != nil { - return diag.FromErr(err) - } - - flattenedSpec := flattenPodSecurityPolicySpec(psp.Spec) - log.Printf("[DEBUG] Flattened PodSecurityPolicy roleRef: %#v", flattenedSpec) - err = d.Set("spec", flattenedSpec) - if err != nil { - return diag.FromErr(err) - } - - return nil -} - -func resourceKubernetesPodSecurityPolicyV1Beta1Update(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return diag.FromErr(err) - } - - name := d.Id() - - ops := patchMetadata("metadata.0.", "/metadata/", d) - - if d.HasChange("spec") { - diffOps := patchPodSecurityPolicySpec("spec.0.", "/spec", d) - ops = append(ops, *diffOps...) - } - data, err := ops.MarshalJSON() - if err != nil { - return diag.Errorf("Failed to marshal update operations: %s", err) - } - log.Printf("[INFO] Updating PodSecurityPolicy %q: %v", name, string(data)) - out, err := conn.PolicyV1beta1().PodSecurityPolicies().Patch(ctx, name, pkgApi.JSONPatchType, data, metav1.PatchOptions{}) - if err != nil { - return diag.Errorf("Failed to update PodSecurityPolicy: %s", err) - } - log.Printf("[INFO] Submitted updated PodSecurityPolicy: %#v", out) - d.SetId(out.Name) - - return resourceKubernetesPodSecurityPolicyV1Beta1Read(ctx, d, meta) -} - -func resourceKubernetesPodSecurityPolicyV1Beta1Delete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return diag.FromErr(err) - } - - name := d.Id() - - log.Printf("[INFO] Deleting PodSecurityPolicy: %#v", name) - err = conn.PolicyV1beta1().PodSecurityPolicies().Delete(ctx, name, metav1.DeleteOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && errors.IsNotFound(statusErr) { - return nil - } - return diag.FromErr(err) - } - log.Printf("[INFO] PodSecurityPolicy %s deleted", name) - - return nil -} - -func resourceKubernetesPodSecurityPolicyV1Beta1Exists(ctx context.Context, d *schema.ResourceData, meta interface{}) (bool, error) { - conn, err := meta.(KubeClientsets).MainClientset() - if err != nil { - return false, err - } - - name := d.Id() - - log.Printf("[INFO] Checking PodSecurityPolicy %s", name) - _, err = conn.PolicyV1beta1().PodSecurityPolicies().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - if statusErr, ok := err.(*errors.StatusError); ok && errors.IsNotFound(statusErr) { - return false, nil - } - log.Printf("[DEBUG] Received error: %#v", err) - } - return true, err -} - -func idRangeSchema() map[string]*schema.Schema { - return map[string]*schema.Schema{ - "min": { - Type: schema.TypeInt, - Description: pspIDRangeMinDoc, - Required: true, - }, - "max": { - Type: schema.TypeInt, - Description: pspIDRangeMaxDoc, - Required: true, - }, - } -} diff --git a/kubernetes/resource_kubernetes_pod_security_policy_v1beta1_test.go b/kubernetes/resource_kubernetes_pod_security_policy_v1beta1_test.go deleted file mode 100644 index 5540ac01d6..0000000000 --- a/kubernetes/resource_kubernetes_pod_security_policy_v1beta1_test.go +++ /dev/null @@ -1,396 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package kubernetes - -import ( - "context" - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" - policy "k8s.io/api/policy/v1beta1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestAccKubernetesPodSecurityPolicyV1Beta1_basic(t *testing.T) { - var conf policy.PodSecurityPolicy - name := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(10)) - resourceName := "kubernetes_pod_security_policy_v1beta1.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - testAccPreCheck(t) - skipIfClusterVersionGreaterThanOrEqual(t, "1.25.0") - }, - IDRefreshName: resourceName, - IDRefreshIgnore: []string{"metadata.0.resource_version"}, - ProviderFactories: testAccProviderFactories, - CheckDestroy: testAccCheckKubernetesPodSecurityPolicyV1Beta1Destroy, - Steps: []resource.TestStep{ - { - Config: testAccKubernetesPodSecurityPolicyV1Beta1Config_basic(name), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckKubernetesPodSecurityPolicyV1Beta1Exists(resourceName, &conf), - resource.TestCheckResourceAttr(resourceName, "metadata.0.annotations.%", "1"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.annotations.TestAnnotationOne", "one"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.labels.%", "3"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.labels.TestLabelOne", "one"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.labels.TestLabelThree", "three"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.labels.TestLabelFour", "four"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.name", name), - resource.TestCheckResourceAttrSet(resourceName, "metadata.0.generation"), - resource.TestCheckResourceAttrSet(resourceName, "metadata.0.resource_version"), - resource.TestCheckResourceAttrSet(resourceName, "metadata.0.uid"), - resource.TestCheckResourceAttr(resourceName, "spec.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.privileged", "false"), - resource.TestCheckResourceAttr(resourceName, "spec.0.allow_privilege_escalation", "false"), - resource.TestCheckResourceAttr(resourceName, "spec.0.host_ipc", "false"), - resource.TestCheckResourceAttr(resourceName, "spec.0.host_network", "false"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.#", "6"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.0", "configMap"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.1", "emptyDir"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.2", "projected"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.3", "secret"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.4", "downwardAPI"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.5", "persistentVolumeClaim"), - resource.TestCheckResourceAttr(resourceName, "spec.0.run_as_user.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.run_as_user.0.rule", "MustRunAsNonRoot"), - resource.TestCheckResourceAttr(resourceName, "spec.0.se_linux.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.se_linux.0.rule", "RunAsAny"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.0.rule", "MustRunAs"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.0.range.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.0.range.0.min", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.0.range.0.max", "65535"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.0.rule", "MustRunAs"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.0.range.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.0.range.0.min", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.0.range.0.max", "65535"), - resource.TestCheckResourceAttr(resourceName, "spec.0.read_only_root_filesystem", "true"), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"metadata.0.resource_version"}, - }, - { - Config: testAccKubernetesPodSecurityPolicyV1Beta1Config_metaModified(name), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckKubernetesPodSecurityPolicyV1Beta1Exists(resourceName, &conf), - resource.TestCheckResourceAttr(resourceName, "metadata.0.annotations.%", "2"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.annotations.TestAnnotationOne", "one"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.annotations.TestAnnotationTwo", "two"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.labels.%", "3"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.labels.TestLabelOne", "one"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.labels.TestLabelTwo", "two"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.labels.TestLabelThree", "three"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.name", name), - resource.TestCheckResourceAttrSet(resourceName, "metadata.0.generation"), - resource.TestCheckResourceAttrSet(resourceName, "metadata.0.resource_version"), - resource.TestCheckResourceAttrSet(resourceName, "metadata.0.uid"), - resource.TestCheckResourceAttr(resourceName, "spec.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.privileged", "false"), - resource.TestCheckResourceAttr(resourceName, "spec.0.allow_privilege_escalation", "false"), - resource.TestCheckResourceAttr(resourceName, "spec.0.host_ipc", "false"), - resource.TestCheckResourceAttr(resourceName, "spec.0.host_network", "false"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.#", "6"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.0", "configMap"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.1", "emptyDir"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.2", "projected"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.3", "secret"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.4", "downwardAPI"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.5", "persistentVolumeClaim"), - resource.TestCheckResourceAttr(resourceName, "spec.0.run_as_user.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.run_as_user.0.rule", "MustRunAsNonRoot"), - resource.TestCheckResourceAttr(resourceName, "spec.0.se_linux.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.se_linux.0.rule", "RunAsAny"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.0.rule", "MustRunAs"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.0.range.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.0.range.0.min", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.0.range.0.max", "65535"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.0.rule", "MustRunAs"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.0.range.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.0.range.0.min", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.0.range.0.max", "65535"), - resource.TestCheckResourceAttr(resourceName, "spec.0.read_only_root_filesystem", "true"), - ), - }, - { - Config: testAccKubernetesPodSecurityPolicyV1Beta1Config_specModified(name), - Check: resource.ComposeAggregateTestCheckFunc( - testAccCheckKubernetesPodSecurityPolicyV1Beta1Exists(resourceName, &conf), - resource.TestCheckResourceAttr(resourceName, "metadata.0.annotations.%", "0"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.labels.%", "0"), - resource.TestCheckResourceAttr(resourceName, "metadata.0.name", name), - resource.TestCheckResourceAttrSet(resourceName, "metadata.0.generation"), - resource.TestCheckResourceAttrSet(resourceName, "metadata.0.resource_version"), - resource.TestCheckResourceAttrSet(resourceName, "metadata.0.uid"), - resource.TestCheckResourceAttr(resourceName, "spec.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.privileged", "true"), - resource.TestCheckResourceAttr(resourceName, "spec.0.allow_privilege_escalation", "true"), - resource.TestCheckResourceAttr(resourceName, "spec.0.default_allow_privilege_escalation", "true"), - resource.TestCheckResourceAttr(resourceName, "spec.0.host_ipc", "true"), - resource.TestCheckResourceAttr(resourceName, "spec.0.host_network", "true"), - resource.TestCheckResourceAttr(resourceName, "spec.0.allowed_host_paths.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.allowed_host_paths.0.path_prefix", "/"), - resource.TestCheckResourceAttr(resourceName, "spec.0.allowed_host_paths.0.read_only", "true"), - resource.TestCheckResourceAttr(resourceName, "spec.0.allowed_unsafe_sysctls.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.allowed_unsafe_sysctls.0", "kernel.msg*"), - resource.TestCheckResourceAttr(resourceName, "spec.0.forbidden_sysctls.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.forbidden_sysctls.0", "kernel.shm_rmid_forced"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.#", "6"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.0", "configMap"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.1", "emptyDir"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.2", "projected"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.3", "secret"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.4", "downwardAPI"), - resource.TestCheckResourceAttr(resourceName, "spec.0.volumes.5", "persistentVolumeClaim"), - resource.TestCheckResourceAttr(resourceName, "spec.0.run_as_user.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.run_as_user.0.rule", "MustRunAsNonRoot"), - resource.TestCheckResourceAttr(resourceName, "spec.0.se_linux.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.se_linux.0.rule", "RunAsAny"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.supplemental_groups.0.rule", "RunAsAny"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.#", "1"), - resource.TestCheckResourceAttr(resourceName, "spec.0.fs_group.0.rule", "RunAsAny"), - resource.TestCheckResourceAttr(resourceName, "spec.0.read_only_root_filesystem", "true"), - ), - }, - }, - }) -} - -func testAccCheckKubernetesPodSecurityPolicyV1Beta1Destroy(s *terraform.State) error { - conn, err := testAccProvider.Meta().(KubeClientsets).MainClientset() - - if err != nil { - return err - } - ctx := context.TODO() - - for _, rs := range s.RootModule().Resources { - if rs.Type != "kubernetes_pod_security_policy_v1beta1" { - continue - } - - name := rs.Primary.ID - - resp, err := conn.PolicyV1beta1().PodSecurityPolicies().Get(ctx, name, metav1.GetOptions{}) - if err == nil { - if resp.Name == name { - return fmt.Errorf("Pod Security Policy still exists: %s", rs.Primary.ID) - } - } - } - - return nil -} - -func testAccCheckKubernetesPodSecurityPolicyV1Beta1Exists(n string, obj *policy.PodSecurityPolicy) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("Not found: %s", n) - } - - conn, err := testAccProvider.Meta().(KubeClientsets).MainClientset() - if err != nil { - return err - } - ctx := context.TODO() - - name := rs.Primary.ID - - out, err := conn.PolicyV1beta1().PodSecurityPolicies().Get(ctx, name, metav1.GetOptions{}) - if err != nil { - return err - } - - *obj = *out - return nil - } -} - -func testAccKubernetesPodSecurityPolicyV1Beta1Config_basic(name string) string { - return fmt.Sprintf(`resource "kubernetes_pod_security_policy_v1beta1" "test" { - metadata { - name = "%s" - - annotations = { - TestAnnotationOne = "one" - } - - labels = { - TestLabelOne = "one" - TestLabelThree = "three" - TestLabelFour = "four" - } - } - - spec { - volumes = [ - "configMap", - "emptyDir", - "projected", - "secret", - "downwardAPI", - "persistentVolumeClaim", - ] - - run_as_user { - rule = "MustRunAsNonRoot" - } - - se_linux { - rule = "RunAsAny" - } - - supplemental_groups { - rule = "MustRunAs" - range { - min = 1 - max = 65535 - } - } - - fs_group { - rule = "MustRunAs" - range { - min = 1 - max = 65535 - } - } - - host_ports { - min = 0 - max = 65535 - } - - read_only_root_filesystem = true - } -} -`, name) -} - -func testAccKubernetesPodSecurityPolicyV1Beta1Config_metaModified(name string) string { - return fmt.Sprintf(`resource "kubernetes_pod_security_policy_v1beta1" "test" { - metadata { - name = "%s" - - annotations = { - TestAnnotationOne = "one" - TestAnnotationTwo = "two" - } - - labels = { - TestLabelOne = "one" - TestLabelTwo = "two" - TestLabelThree = "three" - } - } - - spec { - volumes = [ - "configMap", - "emptyDir", - "projected", - "secret", - "downwardAPI", - "persistentVolumeClaim", - ] - - run_as_user { - rule = "MustRunAsNonRoot" - } - - se_linux { - rule = "RunAsAny" - } - - supplemental_groups { - rule = "MustRunAs" - range { - min = 1 - max = 65535 - } - } - - fs_group { - rule = "MustRunAs" - range { - min = 1 - max = 65535 - } - } - - read_only_root_filesystem = true - } -} -`, name) -} - -func testAccKubernetesPodSecurityPolicyV1Beta1Config_specModified(name string) string { - return fmt.Sprintf(`resource "kubernetes_pod_security_policy_v1beta1" "test" { - metadata { - name = "%s" - } - - spec { - privileged = true - allow_privilege_escalation = true - default_allow_privilege_escalation = true - host_ipc = true - host_network = true - host_pid = true - - volumes = [ - "configMap", - "emptyDir", - "projected", - "secret", - "downwardAPI", - "persistentVolumeClaim", - ] - - allowed_host_paths { - path_prefix = "/" - read_only = true - } - - allowed_unsafe_sysctls = [ - "kernel.msg*" - ] - - forbidden_sysctls = [ - "kernel.shm_rmid_forced" - ] - - run_as_user { - rule = "MustRunAsNonRoot" - } - - se_linux { - rule = "RunAsAny" - } - - supplemental_groups { - rule = "RunAsAny" - } - - fs_group { - rule = "RunAsAny" - } - - read_only_root_filesystem = true - } -} -`, name) -} diff --git a/kubernetes/structure_persistent_volume_claim.go b/kubernetes/structure_persistent_volume_claim.go index 15c0d916fa..23fae7d23a 100644 --- a/kubernetes/structure_persistent_volume_claim.go +++ b/kubernetes/structure_persistent_volume_claim.go @@ -16,7 +16,7 @@ import ( func flattenPersistentVolumeClaimSpec(in corev1.PersistentVolumeClaimSpec) []interface{} { att := make(map[string]interface{}) att["access_modes"] = flattenPersistentVolumeAccessModes(in.AccessModes) - att["resources"] = flattenResourceRequirements(in.Resources) + att["resources"] = flattenVolumeResourceRequirements(in.Resources) if in.Selector != nil { att["selector"] = flattenLabelSelector(in.Selector) } @@ -32,7 +32,7 @@ func flattenPersistentVolumeClaimSpec(in corev1.PersistentVolumeClaimSpec) []int return []interface{}{att} } -func flattenResourceRequirements(in corev1.ResourceRequirements) []interface{} { +func flattenVolumeResourceRequirements(in corev1.VolumeResourceRequirements) []interface{} { att := make(map[string]interface{}) if len(in.Limits) > 0 { att["limits"] = flattenResourceList(in.Limits) @@ -73,7 +73,7 @@ func expandPersistentVolumeClaimSpec(l []interface{}) (*corev1.PersistentVolumeC return obj, nil } in := l[0].(map[string]interface{}) - resourceRequirements, err := expandResourceRequirements(in["resources"].([]interface{})) + resourceRequirements, err := expandVolumeResourceRequirements(in["resources"].([]interface{})) if err != nil { return nil, err } @@ -94,8 +94,8 @@ func expandPersistentVolumeClaimSpec(l []interface{}) (*corev1.PersistentVolumeC return obj, nil } -func expandResourceRequirements(l []interface{}) (*corev1.ResourceRequirements, error) { - obj := &corev1.ResourceRequirements{} +func expandVolumeResourceRequirements(l []interface{}) (*corev1.VolumeResourceRequirements, error) { + obj := &corev1.VolumeResourceRequirements{} if len(l) == 0 || l[0] == nil { return obj, nil } diff --git a/kubernetes/structure_pod_security_policy_spec.go b/kubernetes/structure_pod_security_policy_spec.go deleted file mode 100644 index d9c70bafca..0000000000 --- a/kubernetes/structure_pod_security_policy_spec.go +++ /dev/null @@ -1,664 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package kubernetes - -import ( - "fmt" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - - v1 "k8s.io/api/core/v1" - v1beta1 "k8s.io/api/policy/v1beta1" - "k8s.io/utils/ptr" -) - -func flattenPodSecurityPolicySpec(in v1beta1.PodSecurityPolicySpec) []interface{} { - spec := make(map[string]interface{}) - - if in.AllowPrivilegeEscalation != nil { - spec["allow_privilege_escalation"] = in.AllowPrivilegeEscalation - } - - if len(in.AllowedCapabilities) > 0 { - spec["allowed_capabilities"] = flattenCapability(in.AllowedCapabilities) - } - - if len(in.AllowedFlexVolumes) > 0 { - spec["allowed_flex_volumes"] = flattenAllowedFlexVolumes(in.AllowedFlexVolumes) - } - - if len(in.AllowedHostPaths) > 0 { - spec["allowed_host_paths"] = flattenAllowedHostPaths(in.AllowedHostPaths) - } - - if len(in.AllowedProcMountTypes) > 0 { - spec["allowed_proc_mount_types"] = flattenAllowedProcMountTypes(in.AllowedProcMountTypes) - } - - if len(in.AllowedUnsafeSysctls) > 0 { - spec["allowed_unsafe_sysctls"] = flattenListOfStrings(in.AllowedUnsafeSysctls) - } - - if len(in.DefaultAddCapabilities) > 0 { - spec["default_add_capabilities"] = flattenCapability(in.DefaultAddCapabilities) - } - - if in.DefaultAllowPrivilegeEscalation != nil { - spec["default_allow_privilege_escalation"] = in.DefaultAllowPrivilegeEscalation - } - - if len(in.ForbiddenSysctls) > 0 { - spec["forbidden_sysctls"] = flattenListOfStrings(in.ForbiddenSysctls) - } - - spec["fs_group"] = flattenFSGroup(in.FSGroup) - spec["host_ipc"] = in.HostIPC - spec["host_network"] = in.HostNetwork - spec["host_pid"] = in.HostPID - - if len(in.HostPorts) > 0 { - spec["host_ports"] = flattenHostPortRangeSlice(in.HostPorts) - } - - spec["privileged"] = in.Privileged - spec["read_only_root_filesystem"] = in.ReadOnlyRootFilesystem - - if len(in.RequiredDropCapabilities) > 0 { - spec["required_drop_capabilities"] = flattenCapability(in.RequiredDropCapabilities) - } - - spec["run_as_user"] = flattenRunAsUser(in.RunAsUser) - - if in.RunAsGroup != nil { - spec["run_as_group"] = flattenRunAsGroup(*in.RunAsGroup) - } - - spec["se_linux"] = flattenSELinuxStrategy(in.SELinux) - spec["supplemental_groups"] = flattenSupplementalGroups(in.SupplementalGroups) - spec["volumes"] = flattenFSTypes(in.Volumes) - - return []interface{}{spec} -} - -func flattenAllowedFlexVolumes(in []v1beta1.AllowedFlexVolume) []interface{} { - result := make([]interface{}, len(in)) - - for k, v := range in { - result[k] = map[string]interface{}{ - "driver": v.Driver, - } - } - - return result -} - -func flattenAllowedHostPaths(in []v1beta1.AllowedHostPath) []interface{} { - result := make([]interface{}, len(in)) - - for k, v := range in { - result[k] = map[string]interface{}{ - "path_prefix": v.PathPrefix, - "read_only": v.ReadOnly, - } - } - - return result -} - -func flattenListOfStrings(in []string) []interface{} { - result := make([]interface{}, len(in)) - - for k, v := range in { - result[k] = v - } - - return result -} - -func flattenAllowedProcMountTypes(in []v1.ProcMountType) []interface{} { - result := make([]interface{}, len(in)) - - for k, v := range in { - result[k] = fmt.Sprintf("%v", v) - } - - return result -} - -func flattenFSGroup(in v1beta1.FSGroupStrategyOptions) []interface{} { - result := map[string]interface{}{ - "rule": in.Rule, - "range": flattenIDRangeSlice(in.Ranges), - } - - return []interface{}{result} -} - -func flattenIDRangeSlice(in []v1beta1.IDRange) []interface{} { - result := make([]interface{}, len(in)) - - for k, v := range in { - result[k] = map[string]interface{}{ - "min": int(v.Min), - "max": int(v.Max), - } - } - - return result -} - -func flattenHostPortRangeSlice(in []v1beta1.HostPortRange) []interface{} { - result := make([]interface{}, len(in)) - - for k, v := range in { - result[k] = map[string]interface{}{ - "min": int(v.Min), - "max": int(v.Max), - } - } - - return result -} - -func flattenRunAsUser(in v1beta1.RunAsUserStrategyOptions) []interface{} { - result := map[string]interface{}{ - "rule": fmt.Sprintf("%v", in.Rule), - "range": flattenIDRangeSlice(in.Ranges), - } - - return []interface{}{result} -} - -func flattenRunAsGroup(in v1beta1.RunAsGroupStrategyOptions) []interface{} { - result := map[string]interface{}{ - "rule": fmt.Sprintf("%v", in.Rule), - "range": flattenIDRangeSlice(in.Ranges), - } - - return []interface{}{result} -} - -func flattenSELinuxStrategy(in v1beta1.SELinuxStrategyOptions) []interface{} { - result := map[string]interface{}{ - "rule": fmt.Sprintf("%v", in.Rule), - } - - if in.SELinuxOptions != nil { - result["se_linux_options"] = flattenSeLinuxOptions(in.SELinuxOptions) - } - - return []interface{}{result} -} - -func flattenSupplementalGroups(in v1beta1.SupplementalGroupsStrategyOptions) []interface{} { - result := map[string]interface{}{ - "rule": fmt.Sprintf("%v", in.Rule), - "range": flattenIDRangeSlice(in.Ranges), - } - - return []interface{}{result} -} - -func flattenFSTypes(in []v1beta1.FSType) []interface{} { - result := make([]interface{}, len(in)) - - for k, v := range in { - result[k] = fmt.Sprintf("%v", v) - } - - return result -} - -func expandPodSecurityPolicySpec(in []interface{}) (v1beta1.PodSecurityPolicySpec, error) { - spec := v1beta1.PodSecurityPolicySpec{} - if len(in) == 0 || in[0] == nil { - return spec, fmt.Errorf("failed to expand PodSecurityPolicy.Spec: null or empty input") - } - - m, ok := in[0].(map[string]interface{}) - if !ok { - return spec, fmt.Errorf("failed to expand PodSecurityPolicy.Spec: malformed input") - } - - if v, ok := m["allow_privilege_escalation"].(bool); ok { - spec.AllowPrivilegeEscalation = ptr.To(v) - } - - if v, ok := m["allowed_capabilities"].([]interface{}); ok && len(v) > 0 { - spec.AllowedCapabilities = expandCapabilitySlice(v) - } - - if v, ok := m["allowed_flex_volumes"].([]interface{}); ok && len(v) > 0 { - spec.AllowedFlexVolumes = expandAllowedFlexVolumeSlice(v) - } - - if v, ok := m["allowed_host_paths"].([]interface{}); ok && len(v) > 0 { - spec.AllowedHostPaths = expandAllowedHostPathSlice(v) - } - - if v, ok := m["allowed_proc_mount_types"].([]interface{}); ok && len(v) > 0 { - spec.AllowedProcMountTypes = expandAllowedProcMountTypes(v) - } - - if v, ok := m["allowed_unsafe_sysctls"].([]interface{}); ok && len(v) > 0 { - spec.AllowedUnsafeSysctls = expandStringSlice(v) - } - - if v, ok := m["default_add_capabilities"].([]interface{}); ok && len(v) > 0 { - spec.DefaultAddCapabilities = expandCapabilitySlice(v) - } - - if v, ok := m["default_allow_privilege_escalation"].(bool); ok { - spec.DefaultAllowPrivilegeEscalation = ptr.To(v) - } - - if v, ok := m["forbidden_sysctls"].([]interface{}); ok && len(v) > 0 { - spec.ForbiddenSysctls = expandStringSlice(v) - } - - if v, ok := m["fs_group"].([]interface{}); ok && len(v) > 0 { - spec.FSGroup = expandFSGroup(v) - } - - if v, ok := m["host_ipc"].(bool); ok { - spec.HostIPC = v - } - - if v, ok := m["host_network"].(bool); ok { - spec.HostNetwork = v - } - - if v, ok := m["host_pid"].(bool); ok { - spec.HostPID = v - } - - if v, ok := m["host_ports"].([]interface{}); ok && len(v) > 0 { - spec.HostPorts = expandHostPortRangeSlice(v) - } - - if v, ok := m["privileged"].(bool); ok { - spec.Privileged = v - } - - if v, ok := m["read_only_root_filesystem"].(bool); ok { - spec.ReadOnlyRootFilesystem = v - } - - if v, ok := m["required_drop_capabilities"].([]interface{}); ok && len(v) > 0 { - spec.RequiredDropCapabilities = expandCapabilitySlice(v) - } - - if v, ok := m["run_as_user"].([]interface{}); ok && len(v) > 0 { - spec.RunAsUser = expandRunAsUser(v) - } - - if v, ok := m["run_as_group"].([]interface{}); ok && len(v) > 0 { - spec.RunAsGroup = expandRunAsGroup(v) - } - - if v, ok := m["se_linux"].([]interface{}); ok && len(v) > 0 { - spec.SELinux = expandSELinux(v) - } - - if v, ok := m["supplemental_groups"].([]interface{}); ok && len(v) > 0 { - spec.SupplementalGroups = expandSupplementalGroup(v) - } - - if v, ok := m["volumes"].([]interface{}); ok && len(v) > 0 { - spec.Volumes = expandVolumeFSTypeSlice(v) - } - - return spec, nil -} - -func expandAllowedFlexVolumeSlice(in []interface{}) []v1beta1.AllowedFlexVolume { - result := make([]v1beta1.AllowedFlexVolume, len(in)) - for k, v := range in { - result[k] = v1beta1.AllowedFlexVolume{ - Driver: v.(string), - } - } - return result -} - -func expandAllowedHostPathSlice(in []interface{}) []v1beta1.AllowedHostPath { - result := make([]v1beta1.AllowedHostPath, len(in)) - for k, v := range in { - if m, ok := v.(map[string]interface{}); ok { - hp := v1beta1.AllowedHostPath{ - PathPrefix: m["path_prefix"].(string), - } - - if ro, ok := m["read_only"].(bool); ok { - hp.ReadOnly = ro - } - - result[k] = hp - } - } - return result -} - -func expandAllowedProcMountTypes(in []interface{}) []v1.ProcMountType { - result := make([]v1.ProcMountType, len(in)) - - for k, v := range in { - result[k] = v1.ProcMountType(v.(string)) - } - - return result -} - -func expandFSGroup(in []interface{}) v1beta1.FSGroupStrategyOptions { - result := v1beta1.FSGroupStrategyOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["rule"].(string); ok { - result.Rule = v1beta1.FSGroupStrategyType(v) - } - - if v, ok := m["range"].([]interface{}); ok && len(v) > 0 { - result.Ranges = expandIDRangeSlice(v) - } - - return result -} - -func expandIDRangeSlice(in []interface{}) []v1beta1.IDRange { - result := make([]v1beta1.IDRange, len(in)) - - for k, v := range in { - if m, ok := v.(map[string]interface{}); ok { - result[k] = v1beta1.IDRange{ - Min: int64(m["min"].(int)), - Max: int64(m["max"].(int)), - } - } - } - - return result -} - -func expandHostPortRangeSlice(in []interface{}) []v1beta1.HostPortRange { - result := make([]v1beta1.HostPortRange, len(in)) - - for k, v := range in { - if m, ok := v.(map[string]interface{}); ok { - result[k] = v1beta1.HostPortRange{ - Min: int32(m["min"].(int)), - Max: int32(m["max"].(int)), - } - } - } - - return result -} - -func expandRunAsUser(in []interface{}) v1beta1.RunAsUserStrategyOptions { - result := v1beta1.RunAsUserStrategyOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["rule"].(string); ok { - result.Rule = v1beta1.RunAsUserStrategy(v) - } - - if v, ok := m["range"].([]interface{}); ok && len(v) > 0 { - result.Ranges = expandIDRangeSlice(v) - } - - return result -} - -func expandRunAsGroup(in []interface{}) *v1beta1.RunAsGroupStrategyOptions { - result := v1beta1.RunAsGroupStrategyOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["rule"].(string); ok { - result.Rule = v1beta1.RunAsGroupStrategy(v) - } - - if v, ok := m["range"].([]interface{}); ok && len(v) > 0 { - result.Ranges = expandIDRangeSlice(v) - } - - return &result -} - -func expandSELinux(in []interface{}) v1beta1.SELinuxStrategyOptions { - result := v1beta1.SELinuxStrategyOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["rule"].(string); ok { - result.Rule = v1beta1.SELinuxStrategy(v) - } - - if v, ok := m["se_linux_options"].([]interface{}); ok && len(v) > 0 { - result.SELinuxOptions = expandSELinuxOptions(v) - } - - return result -} - -func expandSELinuxOptions(in []interface{}) *v1.SELinuxOptions { - result := v1.SELinuxOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["level"].(string); ok { - result.Level = v - } - - if v, ok := m["user"].(string); ok { - result.User = v - } - - if v, ok := m["role"].(string); ok { - result.Role = v - } - - if v, ok := m["type"].(string); ok { - result.Type = v - } - - return &result -} - -func expandSupplementalGroup(in []interface{}) v1beta1.SupplementalGroupsStrategyOptions { - result := v1beta1.SupplementalGroupsStrategyOptions{} - - m := in[0].(map[string]interface{}) - - if v, ok := m["rule"].(string); ok { - result.Rule = v1beta1.SupplementalGroupsStrategyType(v) - } - - if v, ok := m["range"].([]interface{}); ok && len(v) > 0 { - result.Ranges = expandIDRangeSlice(v) - } - - return result -} - -func expandVolumeFSTypeSlice(in []interface{}) []v1beta1.FSType { - result := make([]v1beta1.FSType, len(in)) - for k, v := range in { - if s, ok := v.(string); ok { - result[k] = v1beta1.FSType(s) - } - } - - return result -} - -// Patchers - -func patchPodSecurityPolicySpec(keyPrefix string, pathPrefix string, d *schema.ResourceData) *PatchOperations { - ops := make(PatchOperations, 0) - - if d.HasChange(keyPrefix + "allow_privilege_escalation") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowPrivilegeEscalation", - Value: d.Get(keyPrefix + "allow_privilege_escalation").(bool), - }) - } - - if d.HasChange(keyPrefix + "allowed_capabilities") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowedCapabilities", - Value: d.Get(keyPrefix + "allowed_capabilities").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "allowed_flex_volumes") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowedFlexVolumes", - Value: d.Get(keyPrefix + "allowed_flex_volumes").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "allowed_host_paths") { - n := d.Get(keyPrefix + "allowed_host_paths").([]interface{}) - allowedHostPaths := expandAllowedHostPathSlice(n) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowedHostPaths", - Value: allowedHostPaths, - }) - } - - if d.HasChange(keyPrefix + "allowed_proc_mount_types") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowedProcMountTypes", - Value: d.Get(keyPrefix + "allowed_proc_mount_types").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "allowed_unsafe_sysctls") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/allowedUnsafeSysctls", - Value: d.Get(keyPrefix + "allowed_unsafe_sysctls").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "default_add_capabilities") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/defaultAddCapabilities", - Value: d.Get(keyPrefix + "default_add_capabilities").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "default_allow_privilege_escalation") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/defaultAllowPrivilegeEscalation", - Value: d.Get(keyPrefix + "default_allow_privilege_escalation").(bool), - }) - } - - if d.HasChange(keyPrefix + "forbidden_sysctls") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/forbiddenSysctls", - Value: d.Get(keyPrefix + "forbidden_sysctls").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "fs_group") { - fsGroup := expandFSGroup(d.Get(keyPrefix + "fs_group").([]interface{})) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/fsGroup", - Value: fsGroup, - }) - } - - if d.HasChange(keyPrefix + "host_ipc") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/hostIPC", - Value: d.Get(keyPrefix + "host_ipc").(bool), - }) - } - - if d.HasChange(keyPrefix + "host_network") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/hostNetwork", - Value: d.Get(keyPrefix + "host_network").(bool), - }) - } - - if d.HasChange(keyPrefix + "host_pid") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/hostPID", - Value: d.Get(keyPrefix + "host_pid").(bool), - }) - } - - if d.HasChange(keyPrefix + "host_ports") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/hostPorts", - Value: d.Get(keyPrefix + "host_ports").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "privileged") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/privileged", - Value: d.Get(keyPrefix + "privileged").(bool), - }) - } - - if d.HasChange(keyPrefix + "readonly_root_filesystem") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/readOnlyRootFilesystem", - Value: d.Get(keyPrefix + "readonly_root_filesystem").(bool), - }) - } - - if d.HasChange(keyPrefix + "required_drop_capabilities") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/requiredDropCapabilities", - Value: d.Get(keyPrefix + "required_drop_capabilities").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "run_as_group") { - runAsGroup := expandRunAsGroup(d.Get(keyPrefix + "run_as_group").([]interface{})) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/runAsGroup", - Value: runAsGroup, - }) - } - - if d.HasChange(keyPrefix + "run_as_user") { - runAsUser := expandRunAsUser(d.Get(keyPrefix + "run_as_user").([]interface{})) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/runAsUser", - Value: runAsUser, - }) - } - - if d.HasChange(keyPrefix + "se_linux") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/seLinux", - Value: d.Get(keyPrefix + "se_linux").([]interface{}), - }) - } - - if d.HasChange(keyPrefix + "supplemental_groups") { - supplementalGroups := expandSupplementalGroup(d.Get(keyPrefix + "supplemental_groups").([]interface{})) - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/supplementalGroups", - Value: supplementalGroups, - }) - } - - if d.HasChange(keyPrefix + "volumes") { - ops = append(ops, &ReplaceOperation{ - Path: pathPrefix + "/volumes", - Value: d.Get(keyPrefix + "volumes").([]interface{}), - }) - } - - return &ops -}