package v1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// AuthorSpec defines the desired state of Author
type AuthorSpec struct {
Name string `json:"name"`
Email string `json:"email"`
}
// AuthorStatus defines the observed state of Author
type AuthorStatus struct {
BooksPublished int32 `json:"booksPublished"`
}
//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
// Author is the Schema for the authors API
type Author struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec AuthorSpec `json:"spec,omitempty"`
Status AuthorStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// AuthorList contains a list of Author
type AuthorList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Author `json:"items"`
}
func init() {
SchemeBuilder.Register(&Author{}, &AuthorList{})
}
Step 3: Create Book Resource with Author Reference
bash
kubebuilder create api --group bookstore --version v1 --kind Book --plural books
Modify api/v1/book_types.go to reference Author:
go
package v1
import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// BookSpec defines the desired state of Book
type BookSpec struct {
Title string `json:"title"`
ISBN string `json:"isbn"`
// Reference to Author
AuthorRef corev1.LocalObjectReference `json:"authorRef"`
}
// BookStatus defines the observed state of Book
type BookStatus struct {
Published bool `json:"published"`
}
//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
// Book is the Schema for the books API
type Book struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec BookSpec `json:"spec,omitempty"`
Status BookStatus `json:"status,omitempty"`
}
//+kubebuilder:object:root=true
// BookList contains a list of Book
type BookList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Book `json:"items"`
}
func init() {
SchemeBuilder.Register(&Book{}, &BookList{})
}
Step 4: Generate CRD Manifests
bash
make manifests
This generates CRDs in config/crd/bases/bookstore.example.com_books.yaml and ..._authors.yaml.