Repository: bridgecrewio/checkov

Issue:
Kustomize reorders yaml and crashes checkov
**Describe the issue**

Checkov should be able to scan Kubernetes objects with arbitrary element names when using kustomize.

I am scanning a rook-ceph deployment, that contains a Storage class with a key `allowVolumeExpansion`. The storage class is included through a `kustomization.yaml`. 

This key will be listed before `apiVersion`, and make Checkov break - at it expects the apiVersion to be [the first entry](https://github.com/bridgecrewio/checkov/blob/master/checkov/kustomize/runner.py#L328). However, this is not guaranteed - kustomize will order the items in the .yaml file alphabetically.

**Examples**
Please share an example code sample (in the IaC of your choice) + the expected outcomes.

Storageclass:
```yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: rook-ceph-block
  annotations:
    storageclass.kubernetes.io/is-default-class: "true"
# Change "rook-ceph" provisioner prefix to match the operator namespace if needed
provisioner: rook-ceph.rbd.csi.ceph.com
parameters:
  # [...]
allowVolumeExpansion: true
reclaimPolicy: Delete
```

Kustomization:
```yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
- storageclass.yaml
```

Storageclass.yaml built with kustomize:

```sh
/code/components/rook-ceph/bases/v1.7.8 # kustomize build
allowVolumeExpansion: true
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  annotations:
    storageclass.kubernetes.io/is-default-class: "true"
  name: rook-ceph-block
parameters:
  clusterID: rook-ceph
  csi.storage.k8s.io/controller-expand-secret-name: rook-csi-rbd-provisioner
  csi.storage.k8s.io/controller-expand-secret-namespace: rook-ceph
  csi.storage.k8s.io/fstype: ext4
  csi.storage.k8s.io/node-stage-secret-name: rook-csi-rbd-node
  csi.storage.k8s.io/node-stage-secret-namespace: rook-ceph
  csi.storage.k8s.io/provisioner-secret-name: rook-csi-rbd-provisioner
  csi.storage.k8s.io/provisioner-secret-namespace: rook-ceph
  imageFeatures: layering
  imageFormat: "2"
  pool: replicapool
provisioner: rook-ceph.rbd.csi.ceph.com
reclaimPolicy: Delete
```


**Exception Trace**
```sh
LOG_LEVEL=debug checkov -f /code/components/rook-ceph/bases/v1.7.8/kustomization.y
aml
2022-02-16 09:59:20,550 [MainThread  ] [DEBUG]  Checkov version: 2.0.853
2022-02-16 09:59:20,550 [MainThread  ] [DEBUG]  Python executable: /usr/local/bin/python
2022-02-16 09:59:20,550 [MainThread  ] [DEBUG]  Python version: 3.10.2 (main, Jan 29 2022, 03:40:37) [GCC 10.3.1 20211027]
2022-02-16 09:59:20,550 [MainThread  ] [DEBUG]  Checkov executable (argv[0]): /usr/local/bin/checkov
2022-02-16 09:59:20,550 [MainThread  ] [DEBUG]  Command Line Args:   -f /code/components/rook-ceph/bases/v1.7.8/kustomization.yaml
Defaults:
  --framework:       ['all']
  --branch:          master
  --download-external-modules:False
  --external-modules-download-path:.external_modules
  --evaluate-variables:True
  --min-cve-severity:none

2022-02-16 09:59:20,550 [MainThread  ] [INFO ]  Resultant set of frameworks (removing skipped frameworks): all
2022-02-16 09:59:20,550 [MainThread  ] [DEBUG]  terraform_runner declares no system dependency checks required.
2022-02-16 09:59:20,550 [MainThread  ] [DEBUG]  cloudformation_runner declares no system dependency checks required.
2022-02-16 09:59:20,550 [MainThread  ] [DEBUG]  kubernetes_runner declares no system dependency checks required.
2022-02-16 09:59:20,550 [MainThread  ] [DEBUG]  serverless_runner declares no system dependency checks required.
2022-02-16 09:59:20,550 [MainThread  ] [DEBUG]  arm_runner declares no system dependency checks required.
2022-02-16 09:59:20,550 [MainThread  ] [DEBUG]  terraform_plan_runner declares no system dependency checks required.
2022-02-16 09:59:20,550 [MainThread  ] [INFO ]  Checking necessary system dependancies for helm checks.
2022-02-16 09:59:20,575 [MainThread  ] [INFO ]  Found working version of helm dependancies: v3.8.0
2022-02-16 09:59:20,576 [MainThread  ] [DEBUG]  dockerfile_runner declares no system dependency checks required.
2022-02-16 09:59:20,576 [MainThread  ] [DEBUG]  secrets_runner declares no system dependency checks required.
2022-02-16 09:59:20,576 [MainThread  ] [DEBUG]  json_runner declares no system dependency checks required.
2022-02-16 09:59:20,576 [MainThread  ] [DEBUG]  github_configuration_runner declares no system dependency checks required.
2022-02-16 09:59:20,576 [MainThread  ] [DEBUG]  gitlab_configuration_runner declares no system dependency checks required.
2022-02-16 09:59:20,576 [MainThread  ] [INFO ]  Checking necessary system dependancies for kustomize checks.
2022-02-16 09:59:20,582 [MainThread  ] [INFO ]  Found working version of kustomize dependancy kustomize: v4.5.2
2022-02-16 09:59:20,582 [MainThread  ] [DEBUG]  sca_package_runner declares no system dependency checks required.
2022-02-16 09:59:20,582 [MainThread  ] [DEBUG]  No API key found. Scanning locally only.
2022-02-16 09:59:20,630 [MainThread  ] [DEBUG]  Got checkov mappings from Bridgecrew BE
2022-02-16 09:59:20,636 [MainThread  ] [INFO ]  Scanning root folder and producing fresh tf_definitions and context
2022-02-16 09:59:20,642 [MainThread  ] [DEBUG]  Parsed file /code/components/rook-ceph/bases/v1.7.8/kustomization.yaml incorrectly {}
2022-02-16 09:59:20,642 [MainThread  ] [INFO ]  creating cloudformation graph
2022-02-16 09:59:20,643 [MainThread  ] [INFO ]  [CloudformationLocalGraph] created 0 vertices
2022-02-16 09:59:20,643 [MainThread  ] [INFO ]  [CloudformationLocalGraph] created 0 edges
2022-02-16 09:59:20,643 [MainThread  ] [INFO ]  Rendering variables, graph has 0 vertices and 0 edges
2022-02-16 09:59:20,643 [MainThread  ] [INFO ]  done evaluating edges
2022-02-16 09:59:20,643 [MainThread  ] [INFO ]  done evaluate_non_rendered_values
2022-02-16 09:59:20,643 [MainThread  ] [INFO ]  Loading external checks from /usr/local/lib/python3.10/site-packages/checkov/cloudformation/checks/graph_checks
2022-02-16 09:59:20,644 [MainThread  ] [INFO ]  Searching through ['__pycache__'] and ['__init__.py']
2022-02-16 09:59:20,644 [MainThread  ] [INFO ]  Searching through [] and ['__init__.cpython-310.pyc']
2022-02-16 09:59:20,647 [MainThread  ] [INFO ]  Creating vertices
2022-02-16 09:59:20,647 [MainThread  ] [INFO ]  Creating edges
2022-02-16 09:59:20,647 [MainThread  ] [INFO ]  Rendering variables, graph has 0 vertices and 0 edges
2022-02-16 09:59:20,647 [MainThread  ] [INFO ]  done evaluating edges
2022-02-16 09:59:20,647 [MainThread  ] [INFO ]  done evaluate_non_rendered_values
2022-02-16 09:59:20,648 [MainThread  ] [DEBUG]  Created definitions context
2022-02-16 09:59:20,648 [MainThread  ] [INFO ]  Loading external checks from /usr/local/lib/python3.10/site-packages/checkov/terraform/checks/graph_checks
2022-02-16 09:59:20,648 [MainThread  ] [INFO ]  Searching through ['aws', 'gcp', '__pycache__', 'azure'] and ['__init__.py']
2022-02-16 09:59:20,648 [MainThread  ] [INFO ]  Searching through [] and ['ALBRedirectsHTTPToHTTPS.yaml', 'GuardDutyIsEnabled.yaml', 'WAF2HasLogs.yaml', 'CloudtrailHasCloudwatch.yaml', 'AutoScallingEnabledELB.yaml', 'S3BucketHasPublicAccessBlock.yaml', 'APIProtectedByWAF.yaml', 'IAMUsersAreMembersAtLeastOneGroup.yaml', 'ALBProtectedByWAF.yaml', 'RDSClusterHasBackupPlan.yaml', 'EIPAllocatedToVPCAttachedEC2.yaml', 'Route53ARecordAttachedResource.yaml', 'VPCHasFlowLog.yaml', 'EBSAddedBackup.yaml', 'IAMUserHasNoConsoleAccess.yaml', 'EFSAddedBackup.yaml', 'SGAttachedToResource.yaml', 'EncryptedEBSVolumeOnlyConnectedToEC2s.yaml', 'AWSSSMParameterShouldBeEncrypted.yaml', 'SubnetHasACL.yaml', 'AutoScalingEnableOnDynamoDBTables.yaml', 'AMRClustersNotOpenToInternet.yaml', 'IAMGroupHasAtLeastOneUser.yaml', 'APIGWLoggingLevelsDefinedProperly.yaml', 'AppSyncProtectedByWAF.yaml', 'AWSNATGatewaysshouldbeutilized.yaml', 'PostgresRDSHasQueryLoggingEnabled.yaml', 'VPCHasRestrictedSG.yaml', 'CloudFrontHasSecurityHeadersPolicy.yaml', 'PostgresDBHasQueryLoggingEnabled.yaml']
2022-02-16 09:59:20,651 [MainThread  ] [DEBUG]  Failed to load /code/components/rook-ceph/bases/v1.7.8/kustomization.yaml as is not a .json file, skipping
2022-02-16 09:59:20,651 [MainThread  ] [INFO ]  creating kubernetes graph
2022-02-16 09:59:20,652 [MainThread  ] [INFO ]  failed to create a vertex in file /code/components/rook-ceph/bases/v1.7.8/kustomization.yaml
2022-02-16 09:59:20,652 [MainThread  ] [INFO ]  Loading external checks from /usr/local/lib/python3.10/site-packages/checkov/kubernetes/checks/graph_checks
2022-02-16 09:59:20,652 [MainThread  ] [INFO ]  Searching through ['__pycache__'] and ['__init__.py']
2022-02-16 09:59:20,652 [MainThread  ] [INFO ]  Searching through [] and ['__init__.cpython-310.pyc']
2022-02-16 09:59:20,654 [MainThread  ] [INFO ]  Running with --file argument; checking for Helm Chart.yaml files
2022-02-16 09:59:20,668 [MainThread  ] [INFO ]  Secrets scanning will scan 1 files
2022-02-16 09:59:20,670 [MainThread  ] [DEBUG]  The json runner requires that external checks are defined.
2022-02-16 09:59:20,678 [MainThread  ] [INFO ]  Running with --file argument; file must be a kustomization.yaml file
2022-02-16 09:59:20,679 [MainThread  ] [DEBUG]  Kustomization contains resources: section. Likley a base. /code/components/rook-ceph/bases/v1.7.8/kustomization.yaml
2022-02-16 09:59:20,681 [MainThread  ] [DEBUG]  Kustomization at /code/components/rook-ceph/bases/v1.7.8 likley a base
2022-02-16 09:59:20,775 [MainThread  ] [INFO ]  Searching through [] and ['GCPProjectHasNoLegacyNetworks.yaml', 'GCPKMSCryptoKeysAreNotPubliclyAccessible.yaml', 'ServiceAccountHasGCPmanagedKey.yaml', 'GCPKMSKeyRingsAreNotPubliclyAccessible.yaml', 'GCPAuditLogsConfiguredForAllServicesAndUsers.yaml', 'GKEClustersAreNotUsingDefaultServiceAccount.yaml', 'DisableAccessToSqlDBInstanceForRootUsersWithoutPassword.yaml', 'GCPLogBucketsConfiguredUsingLock.yaml']
2022-02-16 09:59:20,805 [MainThread  ] [INFO ]  Searching through [] and ['__init__.cpython-310.pyc']
2022-02-16 09:59:20,805 [MainThread  ] [INFO ]  Searching through [] and ['AzureActiveDirectoryAdminIsConfigured.yaml', 'CognitiveServicesCustomerManagedKey.yaml', 'DataExplorerEncryptionUsesCustomKey.yaml', 'SQLServerAuditingEnabled.yaml', 'VAsetPeriodicScansOnSQL.yaml', 'AzureAntimalwareIsConfiguredWithAutoUpdatesForVMs.yaml', 'AzureStorageAccountsUseCustomerManagedKeyForEncryption.yaml', 'PGSQLenablesCustomerManagedKey.yaml', 'StorageContainerActivityLogsNotPublic.yaml', 'AzureSynapseWorkspacesHaveNoIPFirewallRulesAttached.yaml', 'AzureMSSQLServerHasSecurityAlertPolicy.yaml', 'AzureUnattachedDisksAreEncrypted.yaml', 'VAconfiguredToSendReportsToAdmins.yaml', 'AzureDataFactoriesEncryptedWithCustomerManagedKey.yaml', 'VAconfiguredToSendReports.yaml', 'SQLServerAuditingRetention90Days.yaml', 'StorageLoggingIsEnabledForBlobService.yaml', 'VAisEnabledInStorageAccount.yaml', 'StorageLoggingIsEnabledForTableService.yaml', 'AccessToPostgreSQLFromAzureServicesIsDisabled.yaml', 'StorageCriticalDataEncryptedCMK.yaml', 'AzureNetworkInterfacePublicIPAddressId.yaml', 'VMHasBackUpMachine.yaml', 'VirtualMachinesUtilizingManagedDisks.yaml', 'MSQLenablesCustomerManagedKey.yaml']
2022-02-16 09:59:20,888 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_20
2022-02-16 09:59:20,889 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_3
2022-02-16 09:59:20,892 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_15
2022-02-16 09:59:20,892 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_6
2022-02-16 09:59:20,892 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_29
2022-02-16 09:59:20,890 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_31
2022-02-16 09:59:20,890 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_10
2022-02-16 09:59:20,892 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_21
2022-02-16 09:59:20,895 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_1
2022-02-16 09:59:20,893 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_8
2022-02-16 09:59:20,895 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_7
2022-02-16 09:59:20,893 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_23
2022-02-16 09:59:20,896 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_4
2022-02-16 09:59:20,894 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_9
2022-02-16 09:59:20,896 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_35
2022-02-16 09:59:20,894 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_18
2022-02-16 09:59:20,896 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_12
2022-02-16 09:59:20,894 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_2
2022-02-16 09:59:20,895 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_34
2022-02-16 09:59:20,897 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_GCP_2
2022-02-16 09:59:20,896 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_14
2022-02-16 09:59:20,897 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_GCP_3
2022-02-16 09:59:20,896 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_33
2022-02-16 09:59:20,897 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_GCP_5
2022-02-16 09:59:20,896 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_27
2022-02-16 09:59:20,897 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_GCP_7
2022-02-16 09:59:20,896 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_32
2022-02-16 09:59:20,898 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_7
2022-02-16 09:59:20,897 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_30
2022-02-16 09:59:20,897 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_GCP_6
2022-02-16 09:59:20,898 [ThreadPoolEx] [DEBUG]  Running graph check: CKV_AZURE_23
2022-02-16 09:59:20,897 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_GCP_8
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_10
2022-02-16 09:59:20,897 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_GCP_1
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_17
2022-02-16 09:59:20,898 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_GCP_4
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_19
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_13
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_14
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_5
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_15
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_4
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV_AZURE_24
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_21
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_8
2022-02-16 09:59:20,900 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_20
2022-02-16 09:59:20,900 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_6
2022-02-16 09:59:20,900 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_1
2022-02-16 09:59:20,900 [ThreadPoolEx] [DEBUG]  Running graph check: CKV_AZURE_119
2022-02-16 09:59:20,900 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_12
2022-02-16 09:59:20,900 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_9
2022-02-16 09:59:20,900 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_16
2022-02-16 09:59:20,893 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_11
2022-02-16 09:59:20,893 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_19
2022-02-16 09:59:20,898 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_22
2022-02-16 09:59:20,895 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_16
2022-02-16 09:59:20,898 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_3
2022-02-16 09:59:20,894 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_5
2022-02-16 09:59:20,894 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_22
2022-02-16 09:59:20,898 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_11
2022-02-16 09:59:20,899 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_18
2022-02-16 09:59:20,900 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AZURE_2
2022-02-16 09:59:20,893 [ThreadPoolEx] [DEBUG]  Running graph check: CKV2_AWS_28
2022-02-16 09:59:21,903 [MainThread  ] [INFO ]  Ran kustomize to build Kustomize output. DIR: /code/components/rook-ceph/bases/v1.7.8. TYPE: base.
2022-02-16 09:59:21,905 [MainThread  ] [DEBUG]  Kustomize: Temporary directory for /code/components/rook-ceph/bases/v1.7.8 at /tmp/tmpz3ilf0ej/rook-ceph/bases/v1.7.8
Process ForkProcess-13:
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/multiprocessing/process.py", line 315, in _bootstrap
    self.run()
  File "/usr/local/lib/python3.10/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.10/site-packages/checkov/common/parallelizer/parallel_runner.py", line 29, in func_wrapper
    result = original_func(item)
  File "/usr/local/lib/python3.10/site-packages/checkov/common/runners/runner_registry.py", line 63, in <lambda>
    lambda runner: runner.run(root_folder, external_checks_dir=external_checks_dir, files=files,
  File "/usr/local/lib/python3.10/site-packages/checkov/kustomize/runner.py", line 329, in run
    raise Exception(f'Line {line_num}: Expected line to start with apiVersion:  {s}')
Exception: Line 5: Expected line to start with apiVersion:  allowVolumeExpansion: true
```

**Desktop (please complete the following information):**
 - OS:  Running inside a container
 - Checkov Version 2.0.853

**Additional context**




Discussion:

Resolving patch:
diff --git a/checkov/kustomize/runner.py b/checkov/kustomize/runner.py
--- a/checkov/kustomize/runner.py
+++ b/checkov/kustomize/runner.py
@@ -324,15 +324,13 @@ def run(self, root_folder, external_checks_dir=None, files=None, runner_filter=R
                     if last_line_dashes:
                         # The next line should contain a "apiVersion" line for the next Kubernetes manifest
                         # So we will close the old file, open a new file, and write the dashes from last iteration plus this line
-
-                        if not s.startswith('apiVersion:'):
-                            raise Exception(f'Line {line_num}: Expected line to start with apiVersion:  {s}')
-                        # TODO: GET SOURCE FROM LATER ON AND RENAME PLACEHOLDER
                         source = file_num
                         file_num += 1 
                         if source != cur_source_file:
                             if cur_writer:
-                                self._curWriterRenameAndClose(cur_writer, filePath)
+                                # Here we are about to close a "complete" file. The function will validate it looks like a K8S manifest before continuing.
+                                self._curWriterValidateStoreMapAndClose(cur_writer, filePath)
+                                # 
                             file_path = os.path.join(extractDir, str(source))
                             parent = os.path.dirname(file_path)
                             os.makedirs(parent, exist_ok=True)
@@ -344,10 +342,7 @@ def run(self, root_folder, external_checks_dir=None, files=None, runner_filter=R
                         last_line_dashes = False
                     
                     else:
-
-                        if s.startswith('apiVersion:'):
-                            raise Exception(f'Line {line_num}: Unexpected line starting with apiVersion:  {s}')
-
+                        
                         if not cur_writer:
                             continue
                         else:
@@ -356,7 +351,7 @@ def run(self, root_folder, external_checks_dir=None, files=None, runner_filter=R
                     line_num += 1
 
                 if cur_writer:
-                    self._curWriterRenameAndClose(cur_writer, filePath)
+                    self._curWriterValidateStoreMapAndClose(cur_writer, filePath)
 
             try:
                 k8s_runner = K8sKustomizeRunner()
@@ -380,30 +375,35 @@ def run(self, root_folder, external_checks_dir=None, files=None, runner_filter=R
 
         return report
 
-    def _curWriterRenameAndClose(self, cur_writer, FilePath):
+    def _curWriterValidateStoreMapAndClose(self, cur_writer, FilePath):
         currentFileName = cur_writer.name
         cur_writer.close()
         # Now we have a complete k8s manifest as we closed the writer, and it's temporary file name (currentFileName) plus the original file templated out (FilePath)
         # Rename them to useful information from the K8S metadata before conting.
-        # Then keep a mapping of temp files to original repo locations for use with Checkov output later.
+        # Then keep a mapping of template files to original kustomize repo locations for use with Checkov output later.
         try:
             with open(currentFileName) as f:
                 currentYamlObject = yaml.safe_load(f)
-                itemName = []
-                itemName.append(currentYamlObject['kind'])
-                if 'namespace' in currentYamlObject['metadata']:
-                    itemName.append(currentYamlObject['metadata']['namespace'])
-                else:
-                    itemName.append("default")
-                if 'name' in currentYamlObject['metadata']:
-                    itemName.append(currentYamlObject['metadata']['name'])
+                # Validate we have a K8S manifest
+                if "apiVersion" in currentYamlObject:
+                    itemName = []
+                    itemName.append(currentYamlObject['kind'])
+                    if 'namespace' in currentYamlObject['metadata']:
+                        itemName.append(currentYamlObject['metadata']['namespace'])
+                    else:
+                        itemName.append("default")
+                    if 'name' in currentYamlObject['metadata']:
+                        itemName.append(currentYamlObject['metadata']['name'])
+                    else:
+                        itemName.append("noname")
+            
+                    filename = f"{'-'.join(itemName)}.yaml"
+                    newFullPathFilename = str(pathlib.Path(currentFileName).parent / filename) 
+                    os.rename(currentFileName, newFullPathFilename) 
+                    self.kustomizeFileMappings[newFullPathFilename] = FilePath
+                
                 else:
-                    itemName.append("noname")
-        
-                filename = f"{'-'.join(itemName)}.yaml"
-                newFullPathFilename = str(pathlib.Path(currentFileName).parent) + "/" + filename
-                os.rename(currentFileName, newFullPathFilename) 
-                self.kustomizeFileMappings[newFullPathFilename] = FilePath
+                    raise Exception(f'Not a valid Kubernetes manifest (no apiVersion) while parsing Kustomize template: {FilePath}. Templated output: {currentFileName}.')
 
         except IsADirectoryError:
             pass


Test patch: