### Example: Creating and Using GroupClient Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/client-factories.md Demonstrates how to get configuration, instantiate a GroupClient, and retrieve group information using the client. ```go cfg, err := common.GetConfig(ctx, k8sClient, groupResource) if err != nil { return fmt.Errorf("failed to get config: %w", err) } groupClient := NewGroupClient(cfg) group, _, err := groupClient.GetGroup(groupID, nil) if err != nil { return fmt.Errorf("failed to get group: %w", err) } ``` -------------------------------- ### Create GitLab Instance Settings Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of configuring GitLab instance-wide settings. Requires specifying the settings resource. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: Settings metadata: name: gitlab-instance-settings spec: forProvider: instanceAdministration: maxProjectCreationLevel: "developer" ``` -------------------------------- ### NewClient Function Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example demonstrating the usage of the NewClient function to initialize a GitLab client. Requires a ProviderConfig. ```go import ( "context" "github.com/crossplane/crossplane-runtime/pkg/logging" "github.com/upbound/provider-gitlab/apis/v1alpha1" ) func NewClient(ctx context.Context, cfg v1alpha1.ProviderConfig, log logging.Logger) (*gitlab.Client, error) { // ... implementation details ... return gitlab.NewClient(cfg.Spec.Credentials.SecretRef.Name, cfg.Spec.Credentials.SecretRef.Namespace, cfg.Spec.Credentials.SecretRef.Key) } ``` -------------------------------- ### Create GitLab Project Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of creating a GitLab Project resource. Includes project name, path, namespace, and description. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: Project metadata: name: my-cool-project spec: forProvider: name: My Cool Project path: my-cool-project namespaceId: "12345" description: "This is a cool project managed by Crossplane" ``` -------------------------------- ### Self-Rotating Service Account Token Setup Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example demonstrating how to set up a self-rotating service account token, covering both owner and self-managed modes. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: ServiceAccountAccessToken metadata: name: my-rotating-token spec: forProvider: serviceAccountName: "my-service-account" scopes: ["api", "read_repository"] expiresAt: "2024-01-01T00:00:00Z" # Token will expire and be rotated ``` -------------------------------- ### NewGroupClient Factory Function Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of using the NewGroupClient factory function to create an instance of the Group Client. ```go import ( "github.com/upbound/provider-gitlab/internal/clients/gitlab" ) func main() { // Assume client is an authenticated gitlab.Client var client *gitlab.Client groupClient := gitlab.NewGroupClient(client) // Now you can use groupClient to interact with GitLab groups } ``` -------------------------------- ### FetchFromEndpoint Basic Auth Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of using FetchFromEndpoint with Basic Authentication for GitLab API requests. ```go import ( "context" "github.com/upbound/provider-gitlab/internal/clients/http" ) func ExampleFetchFromEndpoint_basicAuth() { ctx := context.Background() username := "your_username" password := "your_password" resp, err := http.FetchFromEndpoint(ctx, "https://gitlab.example.com/api/v4/user", nil, nil, username, password) // ... handle response and error ... } ``` -------------------------------- ### Multi-instance Configuration Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Demonstrates how to configure multiple instances of the GitLab provider, each with potentially different credentials or settings. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: ProviderConfig metadata: name: gitlab-config-instance-1 spec: credentials: source: Secret secretRef: namespace: crossplane-system name: gitlab-token-1 key: token --- apiVersion: gitlab.upbound.io/v1beta1 kind: ProviderConfig metadata: name: gitlab-config-instance-2 spec: credentials: source: Secret secretRef: namespace: crossplane-system name: gitlab-token-2 key: token ``` -------------------------------- ### GenerateCreateGroupOptions Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example showing how to convert provider spec fields into options for creating a GitLab group via the API. ```go import ( "github.com/upbound/provider-gitlab/apis/v1alpha1" gitlab "github.com/xanzy/go-gitlab" ) func (mg *v1alpha1.Group) GenerateCreateGroupOptions() *gitlab.CreateGroupOptions { opts := &gitlab.CreateGroupOptions{} if mg.Spec.ForProvider.Name != nil { opts.Name = mg.Spec.ForProvider.Name } if mg.Spec.ForProvider.Path != nil { opts.Path = mg.Spec.ForProvider.Path } // ... other option conversions ... return opts } ``` -------------------------------- ### FetchFromEndpoint Token Authentication Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of using FetchFromEndpoint with token-based authentication for GitLab API requests. ```go import ( "context" "github.com/upbound/provider-gitlab/internal/clients/http" ) func ExampleFetchFromEndpoint_tokenAuth() { ctx := context.Background() token := "your_gitlab_token" resp, err := http.FetchFromEndpoint(ctx, "https://gitlab.example.com/api/v4/projects", nil, &token) // ... handle response and error ... } ``` -------------------------------- ### Helm Integration Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Illustrates how to integrate Crossplane-managed GitLab resources within a Helm-based deployment strategy. ```yaml # This is a conceptual example. Actual integration involves Helm chart development. # Crossplane resources can be packaged into a Helm chart and deployed. # Example: A Helm chart containing GitLab resource definitions. # charts/gitlab-resources/templates/project.yaml # apiVersion: gitlab.upbound.io/v1beta1 # kind: Project # metadata: # name: {{ .Values.project.name }} spec: forProvider: name: {{ .Values.project.name }} description: {{ .Values.project.description }} # values.yaml # project: # name: "Helm Managed Project" # description: "Project deployed via Helm." ``` -------------------------------- ### Create GitLab Runner Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of registering a GitLab Runner. Requires specifying the runner's description, tags, and run untagged status. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: Runner metadata: name: my-gitlab-runner spec: forProvider: description: "My Awesome Runner" active: true tags: - docker - linux runUntagged: false ``` -------------------------------- ### GenerateObservation Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example demonstrating the GenerateObservation function, which maps GitLab API resource details to the provider's observation status. ```go import ( "github.com/upbound/provider-gitlab/apis/v1alpha1" gitlab "github.com/xanzy/go-gitlab" ) func (mg *MyResource) GenerateObservation(gitlabGroup *gitlab.Group) { // ... implementation details ... mg.Status.AtProvider.GroupID = gitlabGroup.ID mg.Status.AtProvider.Visibility = v1alpha1.VisibilityValueV1alpha1ToGitlab(gitlabGroup.Visibility) // ... other field mappings ... } ``` -------------------------------- ### Complete Workflow: Group with Members Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt A step-by-step YAML example demonstrating the creation of a GitLab group and adding members to it. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: Group metadata: name: my-group spec: forProvider: name: "My Awesome Group" description: "This is a group managed by Crossplane." membershipLock: false shareWithGroupLock: false requireTwoFactorAuthentication: false defaultProjectVisibility: "private" defaultBranchProtection: "developers_can_merge" emailsDisabled: false mentionsDisabled: false --- # Add members to the group apiVersion: gitlab.upbound.io/v1beta1 kind: GroupMember metadata: name: my-group-member spec: forProvider: groupId: "my-group" userId: "12345" accessLevel: "developer" expiresAt: "2024-12-31T23:59:59Z" ``` -------------------------------- ### Handle Provider Configuration Errors Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/errors.md This example demonstrates how to handle various errors that can occur when retrieving provider configuration, such as missing references or unsupported credential sources. ```go cfg, err := common.GetConfig(ctx, k8sClient, managedResource) if err != nil { if strings.Contains(err.Error(), "providerConfigRef is not given") { return fmt.Errorf("spec.providerConfigRef is required: %w", err) } if strings.Contains(err.Error(), "cannot get referenced") { return fmt.Errorf("Referenced ProviderConfig not found: %w", err) } return fmt.Errorf("failed to get provider config: %w", err) } ``` -------------------------------- ### Controller Integration Pattern Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Illustrates a common pattern for integrating GitLab resources within a Kubernetes controller, showing reconciliation logic. ```go package controller import ( "context" "github.com/go-logr/logr" "k8s.io/apimachinery/pkg/runtime" reconcile "sigs.k8s.io/controller-runtime/pkg/reconcile" "github.com/upbound/provider-gitlab/internal/clients/gitlab" ) type GroupReconciler struct { Client gitlab.GroupClient Log logr.Logger Scheme *runtime.Scheme } func (r *GroupReconciler) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) { // Fetch the Group instance // ... // Call GitLab API via GroupClient // ... // Update status // ... return reconcile.Result{}, nil } ``` -------------------------------- ### ProjectCreationLevelValueV1alpha1ToGitlab Conversion Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Shows the conversion of the V1alpha1 ProjectCreationLevelValue type to the GitLab API's format. ```go import ( "github.com/upbound/provider-gitlab/apis/v1alpha1" gitlab "github.com/xanzy/go-gitlab" ) func convertProjectCreationLevel(v1alpha1Level v1alpha1.ProjectCreationLevelValue) gitlab.ProjectCreationLevelValue { return v1alpha1.ProjectCreationLevelValueV1alpha1ToGitlab(v1alpha1Level) } ``` -------------------------------- ### Create GitLab Group Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of creating a GitLab Group resource using the provider. Specifies group name, path, and visibility. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: Group metadata: name: my-awesome-group spec: forProvider: name: My Awesome Group path: my-awesome-group visibility: public ``` -------------------------------- ### Create GitLab Service Account Access Token Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of creating a Service Account Access Token for a GitLab project. Requires project name and scopes. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: ServiceAccountAccessToken metadata: name: my-project-token spec: forProvider: projectName: my-cool-project scopes: - api - read_repository expiresAt: "2024-12-31T23:59:59Z" ``` -------------------------------- ### FetchFromEndpoint: Basic Authentication Request Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/http-utilities.md Illustrates how to perform a request using Basic Authentication with a username and password. This is used for services requiring traditional HTTP auth. ```go username := "user@example.com" password := "secret" content, err := FetchFromEndpoint(ctx, RequestParameters{ EndpointURL: "https://api.example.com/protected", Auth: &AuthParameters{ Username: &username, Password: &password, }, }) ``` -------------------------------- ### Flux CD Integration Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Shows how to integrate Crossplane-managed GitLab resources with Flux CD for GitOps workflows. ```yaml # This is a conceptual example. Actual integration involves Flux CD's GitRepository and Kustomization resources. # Crossplane resources (e.g., Project, Group) would be defined in a separate Git repository # and applied by Flux CD. # Example: A Flux CD Kustomization pointing to a directory containing Crossplane manifests. # apiVersion: kustomize.toolkit.fluxcd.io/v1 # kind: Kustomization # metadata: # name: crossplane-gitlab-resources # namespace: flux-system spec: interval: 1h path: ./gitlab-resources prune: true sourceRef: kind: GitRepository name: my-git-repo ``` -------------------------------- ### ProviderConfigUsage Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/configuration.md An example of a ProviderConfigUsage resource, which tracks managed resource references to a ProviderConfig. This is auto-managed by Crossplane. ```yaml apiVersion: gitlab.crossplane.io/v1beta1 kind: ProviderConfigUsage metadata: name: default-group-default namespace: crossplane-system providerConfigRef: apiVersion: gitlab.crossplane.io/v1beta1 kind: ProviderConfig name: default resourceRef: apiVersion: groups.gitlab.m.crossplane.io/v1alpha1 kind: Group name: my-group namespace: default ``` -------------------------------- ### Token Rotation Workflow Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Illustrates a complete workflow for rotating GitLab tokens, including checking rotation status and computing the next rotation time. ```go import ( "context" "time" "github.com/upbound/provider-gitlab/internal/clients/tokenmanager" ) func ExampleTokenRotationWorkflow(ctx context.Context) { // Assume currentTokenTime and lastRotationTime are defined // Assume tokenSecretName and tokenSecretNamespace are defined if tokenmanager.IsSecretRenewalDue(ctx, tokenSecretName, tokenSecretNamespace, lastRotationTime) { nextRotation, err := tokenmanager.NextSecretRenewalTime(ctx, tokenSecretName, tokenSecretNamespace) // ... handle error ... // Rotate token logic here... _ = nextRotation } } ``` -------------------------------- ### Group Client Interface Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Shows the definition of the Group Client interface, outlining the available methods for interacting with GitLab groups. ```go package gitlab type GroupClient interface { ListGroups(opts ...ListGroupsOption) ([]*Group, error) GetGroup(id interface{}) (*Group, error) CreateGroup(opts ...CreateGroupOption) (*Group, error) UpdateGroup(id interface{}, opts ...UpdateGroupOption) (*Group, error) DeleteGroup(id interface{}) error // ... other methods ... } ``` -------------------------------- ### Resource Composition Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/resource-kinds.md Demonstrates how resources can reference each other using status.atProvider fields, such as referencing a Group's ID when creating a GroupMember. ```yaml --- apiVersion: groups.gitlab.m.crossplane.io/v1alpha1 kind: Group metadata: name: my-group spec: forProvider: path: my-group --- apiVersion: groups.gitlab.m.crossplane.io/v1alpha1 kind: GroupMember metadata: name: john-developer spec: forProvider: groupId: "$(my-group.status.atProvider.id)" # Reference group ID userId: 456 accessLevel: "30" ``` -------------------------------- ### ProviderConfig Reference Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/resource-kinds.md References the default provider configuration for a resource. ```yaml spec: providerConfigRef: name: default # Default provider config ``` -------------------------------- ### Namespaced ProviderConfig Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Demonstrates the use of a namespaced ProviderConfig for a specific Kubernetes namespace. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: ProviderConfig metadata: name: gitlab-config-dev namespace: development spec: credentials: source: Secret secretRef: namespace: crossplane-system name: gitlab-token-dev key: token ``` -------------------------------- ### Provider Configuration with Basic Authentication Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of configuring the GitLab provider using Basic Authentication. Requires username and password. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: ProviderConfig metadata: name: gitlab-config spec: credentials: source: Secret secretRef: namespace: crossplane-system name: gitlab-basic-auth key: username # For password, use a separate key in the same secret # key: password ``` -------------------------------- ### SubGroupCreationLevelValueV1alpha1ToGitlab Conversion Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Illustrates the conversion of the V1alpha1 SubGroupCreationLevelValue type to the GitLab API's format. ```go import ( "github.com/upbound/provider-gitlab/apis/v1alpha1" gitlab "github.com/xanzy/go-gitlab" ) func convertSubGroupCreationLevel(v1alpha1Level v1alpha1.SubGroupCreationLevelValue) gitlab.SubGroupCreationLevelValue { return v1alpha1.SubGroupCreationLevelValueV1alpha1ToGitlab(v1alpha1Level) } ``` -------------------------------- ### FetchFromEndpoint: Token-Authenticated Request Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/http-utilities.md Shows how to make a request to an HTTP endpoint using Bearer token authentication. This is common for API authentication. ```go token := "my-bearer-token" content, err := FetchFromEndpoint(ctx, RequestParameters{ EndpointURL: "https://api.example.com/config", Auth: &AuthParameters{ Token: &token, }, Timeout: ptr.To(10 * time.Second), MaxSize: ptr.To(int64(5 * 1024 * 1024)), // 5 MB limit }) if err != nil { return fmt.Errorf("fetch failed: %w", err) } ``` -------------------------------- ### Complete Self-Rotation Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/token-management.md Demonstrates a complete workflow for self-rotating a GitLab Personal Access Token. This includes checking rotation necessity, generating a new expiry, creating a new token, revoking the old one, and updating secrets. ```go func Example_selfRotateToken() { // 1. Check if token needs rotation shouldRotate := ShouldRotateToken( isActive, &createdAt, ¤tExpiresAt, nil, // no explicit expiry &renewBefore, // rotate 7 days before expiry time.Now(), ) if shouldRotate { // 2. Generate new expiry newExpires := GenerateRenewalExpiration(30) // 3. Create new token via GitLab API newToken, _, err := client.PersonalAccessTokens.CreatePersonalAccessToken( &gitlab.CreatePersonalAccessTokenOptions{ Name: "self-rotating-token", Scopes: []string{"api", "self_rotate"}, ExpiresAt: newExpires, }, ) // 4. Revoke old token _, err = client.PersonalAccessTokens.RevokePersonalAccessToken(oldTokenID) // 5. Update secret with new token secret.Data["token"] = []byte(newToken.Token) // 6. Compute and store next rotation time nextRot := ComputeNextRotation(newToken.CreatedAt, newToken.ExpiresAt, &renewBefore) // Store in status.nextRotation } } ``` -------------------------------- ### FetchFromEndpoint: Unauthenticated Request Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/http-utilities.md Demonstrates how to fetch content from an HTTP endpoint without any authentication. This is suitable for publicly accessible resources. ```go content, err := FetchFromEndpoint(ctx, RequestParameters{ EndpointURL: "https://example.com/api/data", }) if err != nil { log.Fatal(err) } fmt.Println(content) ``` -------------------------------- ### VisibilityValueV1alpha1ToGitlab Conversion Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Demonstrates the conversion of the V1alpha1 VisibilityValue type to the GitLab API's expected format. ```go import ( "github.com/upbound/provider-gitlab/apis/v1alpha1" gitlab "github.com/xanzy/go-gitlab" ) func convertVisibility(v1alpha1Visibility v1alpha1.VisibilityValue) gitlab.VisibilityValue { return v1alpha1.VisibilityValueV1alpha1ToGitlab(v1alpha1Visibility) } ``` -------------------------------- ### Create a GitLab Project Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/resource-kinds.md Example of how to define a GitLab Project resource in Crossplane. This configuration specifies project details like path, description, visibility, and feature enablement. ```yaml apiVersion: projects.gitlab.m.crossplane.io/v1alpha1 kind: Project metadata: name: my-project namespace: default spec: forProvider: namespacedPath: "my-group/my-project" description: "My awesome project" visibility: private issuesEnabled: true mergeRequestsEnabled: true wikiEnabled: false providerConfigRef: name: default ``` -------------------------------- ### TLS Configuration with InsecureSkipVerify Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of configuring TLS for the GitLab provider, specifically disabling certificate verification. Use with caution. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: ProviderConfig metadata: name: gitlab-config spec: tls: insecureSkipVerify: true ``` -------------------------------- ### Multiple GitLab ProviderConfigs and Resource References Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/configuration.md This example shows how to define two distinct ProviderConfig resources for gitlab.com and an internal GitLab instance. It also illustrates how to create managed GitLab Group resources that explicitly reference one of these ProviderConfigs using `providerConfigRef`. ```yaml --- # Secrets apiVersion: v1 kind: Secret metadata: name: gitlab-com-token namespace: crossplane-system type: Opaque stringData: token: glpat-gitlab-com-token-xxx --- apiVersion: v1 kind: Secret metadata: name: gitlab-internal-token namespace: crossplane-system type: Opaque stringData: token: glpat-internal-token-xxx --- # Cluster-scoped configs apiVersion: gitlab.crossplane.io/v1beta1 kind: ProviderConfig metadata: name: gitlab-com spec: baseURL: https://gitlab.com/ credentials: source: Secret method: PersonalAccessToken secretRef: name: gitlab-com-token namespace: crossplane-system key: token --- apiVersion: gitlab.crossplane.io/v1beta1 kind: ProviderConfig metadata: name: gitlab-internal spec: baseURL: https://gitlab.internal/ insecureSkipVerify: true # Self-signed cert credentials: source: Secret method: PersonalAccessToken secretRef: name: gitlab-internal-token namespace: crossplane-system key: token --- # Managed resources reference different providers apiVersion: groups.gitlab.m.crossplane.io/v1alpha1 kind: Group metadata: name: public-group spec: forProvider: path: public-group name: Public Group providerConfigRef: name: gitlab-com # Uses gitlab.com provider --- apiVersion: groups.gitlab.m.crossplane.io/v1alpha1 kind: Group metadata: name: internal-group spec: forProvider: path: internal-group name: Internal Group providerConfigRef: name: gitlab-internal # Uses internal GitLab provider ``` -------------------------------- ### Project Client Usage in Crossplane Reconciliation Loop Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/project-client.md This example demonstrates how to use the Project Client within a Crossplane managed resource controller's reconciliation loop. It covers fetching, creating, and updating GitLab projects based on desired state from Kubernetes. ```go // In a reconciliation loop projectClient := NewProjectClient(cfg) // Fetch desired state from Kubernetes desired := &v1alpha1.Project{ Spec: v1alpha1.ProjectSpec{ Parameters: &v1alpha1.ProjectParameters{ NamespacedPath: "my-namespace/my-project", Description: "My project", Visibility: &v1alpha1.PrivateVisibility, }, }, } // Try to get current state current, _, err := projectClient.GetProject(currentID, nil) if err != nil && IsErrorProjectNotFound(err) { // Create project opts := GenerateCreateProjectOptions(desired, ...) created, _, err := projectClient.CreateProject(opts) if err != nil { return err } // Update status desired.Status.AtProvider = GenerateObservation(created) } else if err != nil { return err } else { // Update if changed opts := GenerateEditProjectOptions(desired, current) updated, _, err := projectClient.EditProject(currentID, opts) if err != nil { return err } // Update status desired.Status.AtProvider = GenerateObservation(updated) } ``` -------------------------------- ### Project Creation with Dependency Reference Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/examples.md Create a GitLab Project and demonstrate how to reference its status fields for creating dependent resources, such as Project Members. The example shows using `my-project.status.atProvider.id` to set the `projectId` for a `ProjectMember`. ```yaml # Use status.atProvider fields for dependencies apiVersion: projects.gitlab.m.crossplane.io/v1alpha1 kind: Project metadata: name: my-project namespace: default spec: forProvider: namespacedPath: "my-group/my-project" providerConfigRef: name: default --- # This would reference the project's ID apiVersion: projects.gitlab.m.crossplane.io/v1alpha1 kind: ProjectMember metadata: name: dev-access namespace: default spec: forProvider: projectId: 1 # Would get from my-project.status.atProvider.id userId: 10 accessLevel: "30" providerConfigRef: name: default ``` -------------------------------- ### Configure Crossplane for Multiple GitLab Instances Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/examples.md This example demonstrates how to configure the Crossplane GitLab provider to connect to multiple GitLab instances, including public GitLab.com and a private self-hosted instance. It shows setting up Kubernetes Secrets for authentication and ProviderConfig resources for each instance. ```yaml --- # Secrets for different instances apiVersion: v1 kind: Secret metadata: name: gitlab-com-token namespace: crossplane-system type: Opaque stringData: token: glpat-gitlab-com-token --- apiVersion: v1 kind: Secret metadata: name: internal-gitlab-token namespace: crossplane-system type: Opaque stringData: token: glpat-internal-token --- # ProviderConfigs for each instance apiVersion: gitlab.crossplane.io/v1beta1 kind: ProviderConfig metadata: name: gitlab-com spec: baseURL: https://gitlab.com/ credentials: source: Secret method: PersonalAccessToken secretRef: name: gitlab-com-token namespace: crossplane-system key: token --- apiVersion: gitlab.crossplane.io/v1beta1 kind: ProviderConfig metadata: name: gitlab-internal spec: baseURL: https://gitlab.internal/ insecureSkipVerify: true credentials: source: Secret method: PersonalAccessToken secretRef: name: internal-gitlab-token namespace: crossplane-system key: token --- # Groups from different instances can coexist apiVersion: groups.gitlab.m.crossplane.io/v1alpha1 kind: Group metadata: name: public-group namespace: default spec: forProvider: path: public-group name: Public Group providerConfigRef: name: gitlab-com --- apiVersion: groups.gitlab.m.crossplane.io/v1alpha1 kind: Group metadata: name: internal-group namespace: default spec: forProvider: path: internal-group name: Internal Group providerConfigRef: name: gitlab-internal ``` -------------------------------- ### ClusterProviderConfig Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of a cluster-scoped ProviderConfig, typically used for cluster-wide GitLab configurations. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: ClusterProviderConfig metadata: name: gitlab-config-global spec: credentials: source: Secret secretRef: namespace: crossplane-system name: gitlab-token-global key: token ``` -------------------------------- ### NewApplicationSettingsClient Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/client-factories.md Creates a client for managing GitLab instance settings, including admin configurations. Requires a common.Config for GitLab client configuration. ```go func NewApplicationSettingsClient(cfg common.Config) ApplicationSettingsClient ``` -------------------------------- ### General Client Factory Usage Pattern Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/client-factories.md Illustrates the standard pattern for obtaining configuration, creating a specific client using a factory function, and then performing operations with that client. ```go // Get configuration from ProviderConfig cfg, err := common.GetConfig(ctx, k8sClient, managedResource) if err != nil { return err } // Create client using factory function specificClient := NewSpecificClient(cfg) // Use client to perform operations result, _, err := specificClient.SomeOperation(...) ``` -------------------------------- ### NewApplicationSettingsClient Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/client-factories.md Creates a client for managing GitLab instance settings (admin configuration). ```APIDOC ## NewApplicationSettingsClient ### Description Creates a client for managing GitLab instance settings (admin configuration). ### Method ```go func NewApplicationSettingsClient(cfg common.Config) ApplicationSettingsClient ``` ### Parameters #### Path Parameters - `cfg` (common.Config): GitLab client configuration ### Returns - `ApplicationSettingsClient`: Client for application settings operations ``` -------------------------------- ### FetchFromEndpoint Unauthenticated Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of using FetchFromEndpoint to retrieve data from a GitLab API endpoint without authentication. ```go import ( "context" "github.com/upbound/provider-gitlab/internal/clients/http" ) func ExampleFetchFromEndpoint_unauthenticated() { ctx := context.Background() resp, err := http.FetchFromEndpoint(ctx, "https://gitlab.example.com/api/v4/version", nil, nil) // ... handle response and error ... } ``` -------------------------------- ### ServiceAccountAccessToken - Self-Managed Mode Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/resource-kinds.md Example of how to configure a ServiceAccountAccessToken in Self-Managed Mode, where the token manages itself and requires a special bootstrap secret. ```APIDOC ## ServiceAccountAccessToken - Self-Managed Mode ### Description Manages a service account access token with optional self-rotation in Self-Managed Mode. ### Method CREATE/UPDATE/DELETE (Kubernetes API) ### Endpoint N/A (Kubernetes Resource) ### Parameters #### Spec Fields - **forProvider.groupId** (integer) - Required - GitLab group ID. - **forProvider.serviceAccountId** (integer) - Required - Service account ID. - **forProvider.scopes** ([]string) - Required - Token scopes (e.g., api, self_rotate). - **forProvider.expiresAt** (string) - Optional - Explicit expiration date (RFC3339). - **forProvider.renewBeforeDays** (integer) - Optional - Auto-rotate N days before expiry (enables auto-renewal). - **forProvider.renewalPeriodDays** (integer) - Optional - Days until next renewal for connection secret. ### Request Example ```yaml apiVersion: v1 kind: Secret metadata: name: sa-self-rotating-token namespace: default type: connection.crossplane.io/v1alpha1 stringData: token: glpat-xxxxxxxxxxxx --- apiVersion: groups.gitlab.m.crossplane.io/v1alpha1 kind: ServiceAccountAccessToken metadata: name: sa-self-token namespace: default spec: forProvider: groupId: 123 serviceAccountId: 456 scopes: - api - self_rotate renewBeforeDays: 7 providerConfigRef: name: self-managed writeConnectionSecretToRef: name: sa-self-rotating-token namespace: default ``` ### Response #### Status Fields - **status.atProvider.id** - Token ID. - **status.atProvider.active** - Whether token is active. - **status.atProvider.createdAt** - Creation timestamp. - **status.atProvider.expiresAt** - Expiration timestamp. - **status.conditions[].type=SelfManaged** - Token is in self-managed rotation mode. - **status.nextRotation** - When token will next be rotated (auto-renewal mode). ``` -------------------------------- ### ServiceAccountAccessToken - Owner Mode Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/resource-kinds.md Example of how to configure a ServiceAccountAccessToken in Owner Mode, where the ProviderConfig is the group owner and manages the token lifecycle. ```APIDOC ## ServiceAccountAccessToken - Owner Mode ### Description Manages a service account access token with optional self-rotation in Owner Mode. ### Method CREATE/UPDATE/DELETE (Kubernetes API) ### Endpoint N/A (Kubernetes Resource) ### Parameters #### Spec Fields - **forProvider.groupId** (integer) - Required - GitLab group ID. - **forProvider.serviceAccountId** (integer) - Required - Service account ID. - **forProvider.scopes** ([]string) - Required - Token scopes (e.g., api, read_api, write_repository). - **forProvider.expiresAt** (string) - Optional - Explicit expiration date (RFC3339). - **forProvider.renewBeforeDays** (integer) - Optional - Auto-rotate N days before expiry (enables auto-renewal). - **forProvider.renewalPeriodDays** (integer) - Optional - Days until next renewal for connection secret. ### Request Example ```yaml apiVersion: groups.gitlab.m.crossplane.io/v1alpha1 kind: ServiceAccountAccessToken metadata: name: sa-token namespace: default spec: forProvider: groupId: 123 serviceAccountId: 456 scopes: - api - read_api renewBeforeDays: 7 providerConfigRef: name: group-owner writeConnectionSecretToRef: name: sa-token-secret namespace: default ``` ### Response #### Status Fields - **status.atProvider.id** - Token ID. - **status.atProvider.active** - Whether token is active. - **status.atProvider.createdAt** - Creation timestamp. - **status.atProvider.expiresAt** - Expiration timestamp. - **status.conditions[].type=SelfManaged** - Token is in self-managed rotation mode. - **status.nextRotation** - When token will next be rotated (auto-renewal mode). ``` -------------------------------- ### Project with CI/CD Configuration Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Sets up a GitLab project including variables and protected branches, demonstrating CI/CD configuration. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: Project metadata: name: my-cicd-project spec: forProvider: name: "My CI/CD Project" description: "Project with CI/CD setup." --- # Add a variable to the project apiVersion: gitlab.upbound.io/v1beta1 kind: ProjectVariable metadata: name: my-project-variable spec: forProvider: projectId: "my-cicd-project" key: "API_KEY" value: "secret-value" protected: true --- # Protect a branch apiVersion: gitlab.upbound.io/v1beta1 kind: ProjectProtectedBranch metadata: name: main-protected-branch spec: forProvider: projectId: "my-cicd-project" branch: "main" pushAccessLevel: "maintainers" mergeAccessLevel: "developers_and_maintainers" ``` -------------------------------- ### Create GitLab Group Resource Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/errors.md Example of creating a GitLab Group resource using Crossplane. ```yaml apiVersion: groups.gitlab.m.crossplane.io/v1alpha1 kind: Group metadata: name: my-group spec: forProvider: path: my-group name: My Group ``` -------------------------------- ### Connection Secret Reference Example Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/resource-kinds.md Specifies a reference to a Kubernetes secret where connection information for the resource will be written. ```yaml spec: writeConnectionSecretToRef: name: resource-secret namespace: default ``` -------------------------------- ### NewApplicationClient Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/client-factories.md Creates a client for managing GitLab applications, including OAuth applications. Requires a common.Config for GitLab client configuration. ```go func NewApplicationClient(cfg common.Config) ApplicationClient ``` -------------------------------- ### Get Project Push Rules Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/project-client.md Retrieves push rules for a project. This is a GitLab Enterprise Edition feature. ```go rules, _, err := projectClient.GetProjectPushRules(projectID) if err != nil { return fmt.Errorf("failed to get push rules: %w", err) } ``` -------------------------------- ### Create a GitLab Project with CI/CD Configuration Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/examples.md This snippet shows how to create a GitLab project with various settings including visibility, enabled features, topics, and container expiration policies. It also demonstrates creating project variables and setting up protected branches. ```yaml --- apiVersion: projects.gitlab.m.crossplane.io/v1alpha1 kind: Project metadata: name: my-app namespace: default spec: forProvider: namespacedPath: "engineering/my-app" description: "Main application project" visibility: private issuesEnabled: true mergeRequestsEnabled: true wikiEnabled: true snippetsEnabled: true mergeMethod: merge # Create merge commit topics: - application - production containerExpirationPolicy: enabled: true cadence: 1d # Daily cleanup keepN: 5 # Keep 5 images olderThan: 30d # Remove older than 30 days providerConfigRef: name: my-gitlab --- # Project Variables for CI/CD apiVersion: projects.gitlab.m.crossplane.io/v1alpha1 kind: Variable metadata: name: app-db-url namespace: default spec: forProvider: projectId: 456 # From Project.status.atProvider.id key: DATABASE_URL value: "postgres://user:pass@db.internal/app" protected: true masked: true providerConfigRef: name: my-gitlab --- # Protected Branch (main branch protection) apiVersion: projects.gitlab.m.crossplane.io/v1alpha1 kind: ProtectedBranch metadata: name: main-protection namespace: default spec: forProvider: projectId: 456 name: main pushAccessLevel: 40 # Maintainers only mergeAccessLevel: 30 # Developers can merge allowForcePush: false codeOwnerApprovalRequired: true providerConfigRef: name: my-gitlab ``` -------------------------------- ### NewAppearanceClient Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/client-factories.md Creates a client for managing GitLab instance appearance, such as logo and colors. Requires a common.Config for GitLab client configuration. ```go func NewAppearanceClient(cfg common.Config) AppearanceClient ``` -------------------------------- ### Token Expiry Monitoring Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example illustrating how to monitor the expiry of GitLab tokens, potentially triggering alerts or rotation actions. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: PersonalAccessToken metadata: name: monitored-token spec: forProvider: tokenName: "MyMonitoredToken" scopes: ["read_user"] expiresAt: "2024-06-30T12:00:00Z" # Monitoring this expiry date ``` -------------------------------- ### Edit Project Push Rule Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/project-client.md Updates existing push rules for a project. For example, to enable denying tag deletion. ```go opts := &gitlab.EditProjectPushRuleOptions{ DenyDeleteTag: gitlab.Ptr(true), } rules, _, err := projectClient.EditProjectPushRule(projectID, opts) ``` -------------------------------- ### Safely Initialize GitLab Client Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/errors.md Validates configuration before calling NewClient to prevent panics. Ensures token is present and correctly formatted for BasicAuth. ```go import ( "encoding/json" "fmt" common "github.com/crossplane-contrib/provider-gitlab/pkg/common" "github.com/crossplane-contrib/provider-gitlab/pkg/common/auth" ) // Assume cfg is a Config struct and common.NewClient is available // Assume log is a logger instance // Validate config before passing to NewClient if cfg.Token == "" { return fmt.Errorf("token is required") } if cfg.AuthMethod == auth.BasicAuth { // Validate JSON format var ba common.BasicAuth if err := json.Unmarshal([]byte(cfg.Token), &ba); err != nil { return fmt.Errorf("invalid BasicAuth token JSON: %w", err) } if ba.Username == "" { return fmt.Errorf("BasicAuth requires username") } } client := common.NewClient(cfg) // Won't panic if config is valid ``` -------------------------------- ### Project Client Interface Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt This outlines the available methods for interacting with GitLab projects, including push rules management and sharing operations. ```go type ProjectClient interface { // ProjectClient methods // ... GetProjectPushRules(ctx context.Context, projectID int) (*gitlab.ProjectPushRules, *gitlab.Response, error) AddProjectPushRule(ctx context.Context, projectID int, opts gitlab.AddProjectPushRuleOptions) (*gitlab.ProjectPushRule, *gitlab.Response, error) EditProjectPushRule(ctx context.Context, projectID int, opts gitlab.EditProjectPushRuleOptions) (*gitlab.ProjectPushRule, *gitlab.Response, error) ShareProjectWithGroup(ctx context.Context, projectID int, opts gitlab.ShareProjectWithGroupOptions) (*gitlab.ProjectShare, *gitlab.Response, error) DeleteSharedProjectFromGroup(ctx context.Context, projectID int, groupID int) (*gitlab.Response, error) } ``` -------------------------------- ### Deletion Policy Examples Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/resource-kinds.md Specifies how a Kubernetes resource should be handled when deleted. 'Delete' removes the resource from GitLab, while 'Orphan' leaves it in GitLab. ```yaml spec: deletionPolicy: Delete # Remove from GitLab when K8s resource deleted # OR deletionPolicy: Orphan # Keep in GitLab when K8s resource deleted ``` -------------------------------- ### CreateProject Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/project-client.md Create a new project. ```APIDOC ## Method: CreateProject ### Description Create a new project. ### Method POST (implied) ### Endpoint `/projects` (implied) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `opt` (*gitlab.CreateProjectOptions) - Required - Options for creating the project ### Response #### Success Response (200) - `*gitlab.Project`: The newly created project details - `*gitlab.Response`: The API response object #### Response Example (Response structure depends on gitlab.Project type) ``` -------------------------------- ### Get Token Value from Local Secret Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/auth-and-config.md Retrieves a token from a secret in the same namespace as the managed resource. It delegates to GetTokenValueFromSecret after resolving the namespace. ```go localSelector := &v2.LocalSecretKeySelector{ Name: "my-secret", Key: "token", } token, err := common.GetTokenValueFromLocalSecret(ctx, k8sClient, resource, localSelector) ``` -------------------------------- ### Instance Client Factory Functions Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt A collection of factory functions for creating clients that manage instance-level settings and resources in GitLab. ```go func NewInstanceAppearanceClient(cfg *gitlab.Client) *gitlab.InstanceAppearanceClient func NewInstanceApplicationClient(cfg *gitlab.Client) *gitlab.InstanceApplicationClient func NewInstanceLicenseClient(cfg *gitlab.Client) *gitlab.InstanceLicenseClient func NewInstanceServiceAccountClient(cfg *gitlab.Client) *gitlab.InstanceServiceAccountClient func NewInstanceServiceAccountAccessTokenClient(cfg *gitlab.Client) *gitlab.InstanceServiceAccountAccessTokenClient func NewInstanceSettingsClient(cfg *gitlab.Client) *gitlab.InstanceSettingsClient func NewInstanceVariableClient(cfg *gitlab.Client) *gitlab.InstanceVariableClient ``` -------------------------------- ### Handle Credential Retrieval Errors Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/errors.md This example shows how to handle specific errors during credential retrieval from Kubernetes secrets, such as missing secrets or keys. ```go token, err := common.GetTokenValueFromSecret(ctx, k8sClient, mr, selector) if err != nil { if strings.Contains(err.Error(), "Cannot find referenced secret") { return fmt.Errorf("ProviderConfig references non-existent secret: %w", err) } if strings.Contains(err.Error(), "Cannot find key in referenced secret") { return fmt.Errorf("Secret key not found - check ProviderConfig.credentials.secretRef.key: %w", err) } return fmt.Errorf("credential retrieval failed: %w", err) } ``` -------------------------------- ### Create New GitLab Client Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/auth-and-config.md Instantiates a new GitLab API client using the provided configuration. Handles different authentication methods and TLS verification. ```go func NewClient(c Config) *gitlab.Client { // ... implementation details ... } ``` ```go cfg := common.Config{ Token: "glpat-xxxxxxxxxxxx", BaseURL: "https://gitlab.com/", AuthMethod: auth.PersonalAccessToken, } client := common.NewClient(cfg) ``` -------------------------------- ### Provider Configuration with OAuth Token Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of configuring the GitLab provider using an OAuth Token. This method is suitable for integrating with OAuth applications. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: ProviderConfig metadata: name: gitlab-config spec: credentials: source: Secret secretRef: namespace: crossplane-system name: gitlab-oauth-token key: token ``` -------------------------------- ### NewApplicationClient Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/client-factories.md Creates a client for managing GitLab applications, including OAuth applications. ```APIDOC ## NewApplicationClient ### Description Creates a client for managing GitLab applications/OAuth applications. ### Method ```go func NewApplicationClient(cfg common.Config) ApplicationClient ``` ### Parameters #### Path Parameters - `cfg` (common.Config): GitLab client configuration ### Returns - `ApplicationClient`: Client for application operations ``` -------------------------------- ### Provider Configuration with Personal Access Token Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/GENERATION_SUMMARY.txt Example of configuring the GitLab provider using a Personal Access Token. This is the default authentication method. ```yaml apiVersion: gitlab.upbound.io/v1beta1 kind: ProviderConfig metadata: name: gitlab-config spec: credentials: source: Secret secretRef: namespace: crossplane-system name: gitlab-token key: token ``` -------------------------------- ### NewAppearanceClient Source: https://github.com/crossplane-contrib/provider-gitlab/blob/master/_autodocs/api-reference/client-factories.md Creates a client for managing GitLab instance appearance, including logo and colors. ```APIDOC ## NewAppearanceClient ### Description Creates a client for managing GitLab instance appearance (logo, colors, etc.). ### Method ```go func NewAppearanceClient(cfg common.Config) AppearanceClient ``` ### Parameters #### Path Parameters - `cfg` (common.Config): GitLab client configuration ### Returns - `AppearanceClient`: Client for appearance operations ```