Добавление ошибки выдачи CustomResourceDefinition при попытке выполнить с использованием версии V1 в aks

Я пытаюсь добавить customresourcedeployment в aks. Ранее мы использовали версию V1beta1, которая, как мне кажется, устарела. Теперь я пытаюсь использовать версию v1, которая выдает ошибку проверки схемы. Версия V1beta1 выглядит следующим образом.

      {
  'apiVersion': 'apiextensions.k8s.io/v1beta1',
  'kind': 'CustomResourceDefinition',
  'metadata': {
    'name': 'azureassignedidentities.aadpodidentity.k8s.io'
  },
  'spec': {
    'group': 'aadpodidentity.k8s.io',
    'version': 'v1',
    'names': {
      'kind': 'AzureAssignedIdentity',
      'plural': 'azureassignedidentities'
    },
    'scope': 'Namespaced'
  }
}

Теперь я пытаюсь использовать следующий шаблон.

      let collection = {
  'apiVersion': 'apiextensions.k8s.io/v1',
  'kind': 'CustomResourceDefinition',
  'metadata': {
    "annotations": {
      "api-approved.kubernetes.io": "unapproved",
      "controller-gen.kubebuilder.io/version": "v0.5.0"
    },
    'name': 'azureassignedidentities.aadpodidentity.k8s.io'
  },
  'spec': {
    'group': 'aadpodidentity.k8s.io',
    'names': {
      'kind': 'AzureAssignedIdentity',
      'listKind': 'AzureAssignedIdentityList',
      'plural': 'azureassignedidentities',
      'singular': 'azureassignedidentity'
    },
    'scope': 'Namespaced',
    'versions': {
      'name': 'v1',
      'schema': {
        'openAPIV3Schema': {
          'description': 'AzureAssignedIdentity contains the identity <-> pod mapping which is matched.',
          'properties': {
            'apiVersion': {
              'description': 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources',
              'type': 'string'
            },
            'kind': {
              'description': 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds',
              'type': 'string'
            },
            'metadata': {
              'type': 'object'
            },
            'spec': {
              'description': 'AzureAssignedIdentitySpec contains the relationship between an AzureIdentity and an AzureIdentityBinding.',
              'properties': {
                'azureBindingRef': {
                  'description': 'AzureBindingRef is an embedded resource referencing the AzureIdentityBinding used by the AzureAssignedIdentity, which requires x-kubernetes-embedded-resource fields to be true',
                  'properties': {
                    'apiVersion': {
                      'description': 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources',
                      'type': 'string'
                    },
                    'kind': {
                      'description': 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds',
                      'type': 'string'
                    },
                    'metadata': {
                      'type': 'object'
                    },
                    'spec': {
                      'description': 'AzureIdentityBindingSpec matches the pod with the Identity. Used to indicate the potential matches to look for between the pod/deployment and the identities present.',
                      'properties': {
                        'azureIdentity': {
                          'type': 'string'
                        },
                        'metadata': {
                          'type': 'object'
                        },
                        'selector': {
                          'type': 'string'
                        },
                        'weight': {
                          'description': 'Weight is used to figure out which of the matching identities would be selected.',
                          'type': 'integer'
                        }
                      },
                      'type': 'object'
                    },
                    'status': {
                      'description': 'AzureIdentityBindingStatus contains the status of an AzureIdentityBinding.',
                      'properties': {
                        'availableReplicas': {
                          'format': 'int32',
                          'type': 'integer'
                        },
                        'metadata': {
                          'type': 'object'
                        }
                      },
                      'type': 'object'
                    }
                  },
                  'type': 'object',
                  'x-kubernetes-embedded-resource': 'true'
                },
                'azureIdentityRef': {
                  'description': 'AzureIdentityRef is an embedded resource referencing the AzureIdentity used by the AzureAssignedIdentity, which requires x-kubernetes-embedded-resource fields to be true',
                  'properties': {
                    'apiVersion': {
                      'description': 'APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources',
                      'type': 'string'
                    },
                    'kind': {
                      'description': 'Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds',
                      'type': 'string'
                    },
                    'metadata': {
                      'type': 'object'
                    },
                    'spec': {
                      'description': 'AzureIdentitySpec describes the credential specifications of an identity on Azure.',
                      'properties': {
                        'adEndpoint': {
                          'type': 'string'
                        },
                        'adResourceID': {
                          'description': 'For service principal. Option param for specifying the  AD details.',
                          'type': 'string'
                        },
                        'auxiliaryTenantIDs': {
                          'description': 'Service principal auxiliary tenant ids',
                          'items': {
                            'type': 'string'
                          },
                          'nullable': 'true',
                          'type': 'array'
                        },
                        'clientID': {
                          'description': 'Both User Assigned MSI and SP can use this field.',
                          'type': 'string'
                        },
                        'clientPassword': {
                          'description': 'Used for service principal',
                          'properties': {
                            'name': {
                              'description': 'Name is unique within a namespace to reference a secret resource.',
                              "type": "string"
                            },
                            'namespace': {
                              'description': 'Namespace defines the space within which the secret name must be unique.',
                              'type': 'string'
                            }
                          },
                          'type': 'object'
                        },
                        'metadata': {
                          'type': 'object'
                        },
                        'replicas': {
                          'format': 'int32',
                          'nullable': 'true',
                          'type': 'integer'
                        },
                        'resourceID': {
                          'description': 'User assigned MSI resource id.',
                          'type': 'string'
                        },
                        'tenantID': {
                          'description': 'Service principal primary tenant id.',
                          'type': 'string'
                        },
                        'type': {
                          'description': 'UserAssignedMSI or Service Principal',
                          'type': 'integer'
                        }
                      },
                      'type': 'object'
                    },
                    'status': {
                      'description': 'AzureIdentityStatus contains the replica status of the resource.',
                      'properties': {
                        'availableReplicas': {
                          'format': 'int32',
                          'type': 'integer'
                        },
                        'metadata': {
                          'type': 'object'
                        }
                      },
                      'type': 'object'
                    }
                  },
                  'type': 'object',
                  'x-kubernetes-embedded-resource': 'true'
                },
                'metadata': {
                  'type': 'object'
                },
                'nodename': {
                  'type': 'string'
                },
                'pod': {
                  'type': 'string'
                },
                'podNamespace': {
                  'type': 'string'
                },
                'replicas': {
                  'format': 'int32',
                  'nullable': 'true',
                  'type': 'integer'
                }
              },
              'type': 'object'
            },
            'status': {
              'description': 'AzureAssignedIdentityStatus contains the replica status of the resource.',
              'properties': {
                'availableReplicas': {
                  'format': 'int32',
                  'type': 'integer'
                },
                'metadata': {
                  'type': 'object'
                },
                'status': {
                  'type': 'string'
                }
              },
              'type': 'object'
            }
          },
          'type': 'object'
        }
      },
      'served': 'true',
      'storage': 'true',
      
    }
  },
  'status': {
    'acceptedNames': {
      'kind': "",
      'plural': ""
    },
    'conditions': [],
    'storedVersions': []
  }
}

Я пытаюсь развернуть, используя следующий код.

      const client = this.kubeConfig.makeApiClient(k8s.ApiextensionsV1Api);
return new Promise<string>((resolve, reject) => {
  client.createCustomResourceDefinition(collection).then(
    (response) => {
        resolve(response);
    },
    (err) => {
      reject(err.response && err.response.body ? err.response.body : err);
    },
  );
});

Ошибка заключается в следующем.

*{ "message": "CustomResourceDefinition.apiextensions.k8s.io "azureassignedidentities.aadpodidentity.k8s.io" недопустимо: [spec.versions[0].schema.openAPIV3Schema: Требуемое значение: требуются схемы, spec.versions[1].schema.openAPIV3Schema: обязательное значение: требуются схемы, спец.версии[2].schema.openAPIV3Schema: обязательное значение: требуются схемы, спец.версии[3].schema.openAPIV3Schema: обязательное значение: требуются схемы, спец. .versions[0].name: недопустимое значение: "": метка DNS-1035 должна состоять из строчных буквенно-цифровых символов или "-", начинаться с буквенного символа и заканчиваться буквенно-цифровым символом (например, "мое имя" , или 'abc-123', для проверки используется регулярное выражение 'az?'), spec.versions[1].name: недопустимое значение: "":метка DNS-1035 должна состоять из буквенно-цифровых символов нижнего регистра или «-», начинаться с буквенно-цифрового символа и заканчиваться буквенно-цифровым символом (например, «мое-имя» или «abc-123», для проверки используется регулярное выражение ' az?'), spec.versions[2].name: Недопустимое значение: "": метка DNS-1035 должна состоять из строчных буквенно-цифровых символов или '-', начинаться с буквенного символа и заканчиваться буквенно-цифровым символом ( например, 'my-name' или 'abc-123', для проверки используется регулярное выражение 'az?'), spec.versions[3].name: недопустимое значение: "": метка DNS-1035 должна состоять из нижнего регистра буквенно-цифровые символы или '-', начинаются с буквенного символа и заканчиваются буквенно-цифровым символом (например, 'my-name' или 'abc-123', для проверки используется регулярное выражение 'az?'),spec.versions: Недопустимое значение: []apiextensions.CustomResourceDefinitionVersion{apiextensions.CustomResourceDefinitionVersion{Name:"", Подается:false, Хранилище:false, Устарело:false, Предупреждение об устаревании:(*string)(nil), Схема:(*apiextensions.CustomResourceValidation)(nil), Subresources:(*apiextensions.CustomResourceSubresources)(nil), AdditionalPrinterColumns:[]apiextensions.CustomResourceColumnDefinition(nil)}, apiextensions.CustomResourceDefinitionVersion{Name: "", Served:false, Storage:false, Deprecated:false, DeprecationWarning:(*string)(nil), Schema:(*apiextensions.CustomResourceValidation)(nil), Subresources:(*apiextensions.CustomResourceSubresources)(nil), AdditionalPrinterColumns:[]apextensions.CustomResourceColumnDefinition(nil)}, apiextensions.CustomResourceDefinitionVersion{Имя: "", Подано: false, Хранение: false,Устарело:false, DeprecationWarning:(*string)(nil), Schema:(*apiextensions.CustomResourceValidation)(nil), Subresources:(*apiextensions.CustomResourceSubresources)(nil), AdditionalPrinterColumns:[]apiextensions.CustomResourceColumnDefinition(nil)}, apiextensions.CustomResourceDefinitionVersion{Name: "", Served:false, Storage:false, Deprecated:false, DeprecationWarning:(*string)(nil), Schema:(*apiextensions.CustomResourceValidation)(nil), Subresources:(*apiextensions.CustomResourceSubresources)(nil), AdditionalPrinterColumns:[]apiextensions.CustomResourceColumnDefinition(nil)}}: должны содержать уникальные имена версий, spec.versions: Недопустимое значение: []apiextensions.CustomResourceDefinitionVersion{apiextensions.CustomResourceDefinitionVersion{Name:"", Served:false, Storage:false, Deprecated:false, DeprecationWarning:(*string)(nil),Схема:(*apiextensions.CustomResourceValidation)(nil), Подресурсы:(*apiextensions.CustomResourceSubresources)(nil), AdditionalPrinterColumns:[]apiextensions.CustomResourceColumnDefinition(nil)}, apiextensions.CustomResourceDefinitionVersion{Name:"", Served:false, Storage:false, Deprecated:false, DeprecationWarning:(*string)(nil), Schema:(*apiextensions.CustomResourceValidation)(nil), Subresources:(*apiextensions.CustomResourceSubresources)(nil), AdditionalPrinterColumns:[]apiextensions.CustomResourceColumnDefinition(nil) )}, apiextensions.CustomResourceDefinitionVersion{Name: "", Served:false, Storage:false, Deprecated:false, DeprecationWarning:(*string)(nil), Schema:(*apiextensions.CustomResourceValidation)(nil), Subresources:(*apiextensions.CustomResourceSubresources)(nil), AdditionalPrinterColumns:[]apiextensions.CustomResourceColumnDefinition(nil)}, apiextensions.CustomResourceDefinitionVersion{Name:"", Served:false, Storage:false, Deprecated:false, DeprecationWarning:(*string)(nil), Schema:(*apiextensions.CustomResourceValidation)(nil), Subresources:(apiextensions.CustomResourceSubresources)(nil), AdditionalPrinterColumns:[]apiextensions.CustomResourceColumnDefinition(nil)}}: должна быть ровно одна версия, помеченная как версия хранилища, status.storedVersions: Недопустимое значение: []string(nil): должна быть хотя бы одна сохраненная версия]" }

ПОЖАЛУЙСТА, ПОМОГИТЕ МНЕ РЕШИТЬ ЭТО

1 ответ

Пожалуйста, проверьте, возможна ли причина того, что версии (по крайней мере 1) не сохраняются в статусе сохраненных версий.

Смотрите ошибку, которая говорит

status.storedVersions: Недопустимое значение: []string(nil): должна быть хотя бы одна сохраненная версия]" }

При прекращении поддержки версий выберите процедуру обновления хранилища. Удалите старую версию из поля CustomResourceDefinition status.storedVersions и убедитесь, что присутствует новая версия (хотя бы одна).

Вручную обновите существующие объекты до новой сохраненной версии: напишите процедуру обновления, чтобы перечислить все существующие объекты и записать их с тем же содержимым. Это заставляет серверную часть записывать объекты в текущей версии хранилища, то есть v1.

Шаги

1.Сначала создал ресурс crd1.yaml с предыдущей версией.

       versions:
     - name: v1beta1
        served: true
        storage: true

примените его с помощью kubectl.

      kubectl apply -f crd1.yaml

2. Обновите ресурс с определением более поздней версии, скажем, v1. Установите v1 в качестве хранилища в файле CustomResourceDefinition crd12.yaml.

      versions:
    - name: v1
      served: true
      storage: true

и применить его с помощью kubectl.

      kubectl apply -f crd12.yaml
  1. Подтверждение наличия двух версий

kubectl получить CustomResourceDefinition $resource_name -o yaml

      storedVersions: [v1beta1 ,v1]
  1. Check и Set служили false для старой версии в списке spec.versions.

( Примечание : у нас есть возможность сохранить версию v1beta1 в CRD. Если указано с serve: false, любая операция получения/создания/обновления ресурса v1alpha1 будет предотвращена. )

Убедитесь, что storage is set to trueдля новой версии в списке spec.versions в CustomResourceDefinition.

Вы можете сохранить CustomResourceDefinition в файле YAML, а затем использовать kubectl apply для его создания.

пример:

      spec:
  group: example.com
  # list of versions supported by this CustomResourceDefinition
  versions:
  - name: v1
    served: true
    storage: true     # One and only one version must be marked as the storage version.
    schema:
      openAPIV3Schema:
        type: object
        properties:
          host:
            type: string
          port:
            type: string
          ........
   - name: v1beta1
    served: false     # Each version can be enabled/disabled by Served flag.
    storage: false
    # A schema is required
    schema:
      openAPIV3Schema:
        type: object
        properties:
          host:
            type: string
          port:
            type: string
             ......
  conversion:
    strategy: None

 # None conversion assumes the same schema for all versions and only sets the apiVersion
     field of custom resources to the proper value

Затем удалите старую версию. Поля под статусом изменяются через подресурс статуса,

например:

         curl -d '[{ "op": "replace", "path":"/status/storedVersions", "value": ["v1"] }]' \
      -H "Content-Type: application/json-patch+json" \
      -X PATCH \ http://localhost:8080  /apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions/$resource_name/status

Убедитесь, что старая версия больше не указана в статусе CustomResourceDefinition.storedVersions.


Пожалуйста , обратитесь к ним:

  1. Удалить версию из status.storedVersions (kubernetesquestions.com) или как удалить версию из status.storedVersions (github.com)
  2. пример управления версиями пользовательского определения ресурса.
  3. Версии в CustomResourceDefinitions — Kubernetes
Другие вопросы по тегам