### Orchestrating Controller Registrations Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md The `Setup()` function iterates through a list of resource-specific setup functions, registering each controller with the manager. This ensures all controllers are initialized. ```go func Setup(mgr ctrl.Manager, o tjcontroller.Options) error { for _, setup := range []func(ctrl.Manager, tjcontroller.Options) error{ repository.Setup, branch.Setup, branchprotection.Setup, // ... all other resource controllers } { if err := setup(mgr, o); err != nil { return err } } return nil } ``` -------------------------------- ### Install Provider GitHub Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/README.md Install the provider using the Crossplane CLI. Ensure to use the latest release tag. ```bash up ctp provider install crossplane-contrib/provider-upjet-github:v0.1.0 ``` -------------------------------- ### Auto-Generated Controller Registration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Example of an auto-generated controller setup function that registers a resource controller with the manager. This is typically found in `internal/controller/cluster/` or `internal/controller/namespaced/`. ```go // internal/controller/cluster/repo/repository/setup.go func init() { mgr.AddController(...) } ``` -------------------------------- ### Complete Branch Protection Rule Example Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md A comprehensive example demonstrating the configuration of a Branch Protection rule for a repository's main branch, including various protection settings. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: BranchProtection metadata: name: main-protection-rules spec: forProvider: repository: "my-repo" pattern: "main" enforceAdmins: true requireConversationResolution: true requireCodeOwnerReviews: true requiredApprovingReviewCount: 2 dismissStaleReviews: true requiredPullRequestReviews: - requireCodeOwnerReviews: true dismissStaleReviews: true requiredChecks: - context: "continuous-integration/travis-ci" - context: "code-coverage" restrictPushes: - dismissalActors: - "app/dependabot" bypassPullRequestAllowances: - apps: - "dependabot" teams: - "admins" providerConfigRef: name: default ``` -------------------------------- ### Complete Repository Ruleset Example Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md A full example of a RepositoryRuleset resource, defining rules for the main branch with pull request, status checks, and non-fast-forward enforcement. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: RepositoryRuleset metadata: name: main-branch-ruleset spec: forProvider: repository: "my-repo" name: "Main Branch Rules" target: "branch" enforcement: "active" rules: - type: "pull_request" parameters: dismissStaleReviewsOnPush: true requireCodeOwnerReview: true requiredApprovalCount: 2 - type: "required_status_checks" parameters: requiredChecks: - context: "tests" - context: "lint" - type: "non_fast_forward" - type: "commit_message_pattern" parameters: operator: "starts_with" pattern: "JIRA-[0-9]+" conditions: refName: include: - "refs/heads/main" providerConfigRef: name: default ``` -------------------------------- ### GitHub Client Setup Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/INDEX.md Custom Terraform setup function for GitHub credentials. It resolves ProviderConfig from Kubernetes, extracts credentials from a Secret, builds the Terraform provider configuration, and caches credentials with a 55-minute TTL. Supports both PAT and GitHub App authentication. ```go func setupGitHubClient(ctx context.Context, cfg *configv1alpha1.ProviderConfig) (*github.Client, error) { // ... resolve ProviderConfig from Kubernetes // ... extract GitHub credentials from Secret // ... build Terraform provider configuration // ... cache credentials with 55-minute TTL // ... handle PAT and GitHub App auth return nil, nil } ``` -------------------------------- ### Declarative Provider Installation Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/README.md Install the provider declaratively using kubectl. This method applies a Kubernetes resource definition. ```yaml apiVersion: pkg.crossplane.io/v1 kind: Provider metadata: name: provider-upjet-github spec: package: crossplane-contrib/provider-upjet-github:v0.1.0 ``` -------------------------------- ### Example Status Conditions Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/api-reference-types.md Illustrates the structure of the `status.conditions` field, showing how resource synchronization and readiness are reported. ```yaml status: conditions: - type: Synced status: "True" lastTransitionTime: "2024-01-15T10:00:00Z" - type: Ready status: "True" lastTransitionTime: "2024-01-15T10:00:00Z" ``` -------------------------------- ### Resource Configurator Application Order Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/configuration-reference.md Illustrates the order in which resource configurators are applied during provider setup. This sequence ensures that resources are configured in a dependency-aware manner. ```go for _, configure := range []func(provider *ujconfig.Provider){ actions.Configure, actionsenvironmentsecret.Configure, // ... more configurators in order repositoryfile.Configure, // ... more team.Configure, // ... etc } { configure(pc) } ``` -------------------------------- ### Create GitHub Repository Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/README.md Example of creating a public GitHub repository using the Crossplane GitHub provider. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: Repository metadata: name: my-repo spec: forProvider: visibility: public providerConfigRef: name: default ``` -------------------------------- ### GitHub App Authentication Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/INDEX.md Example JSON configuration for authenticating with the GitHub Provider using a GitHub App. This includes app ID, installation ID, and the PEM file content. ```json { "app_auth": [{"id": "...", "installation_id": "...", "pem_file": "..."}], "owner": "organization" } ``` -------------------------------- ### IssueLabels Resource Example Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md An example Kubernetes manifest for creating an `IssueLabels` resource. This manifest defines a set of standard labels for a repository, including their names, colors, and descriptions, and references a `providerConfigRef`. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: IssueLabels metadata: name: standard-labels spec: forProvider: repository: "my-repo" label: - name: "bug" color: "ff0000" description: "Bug report" - name: "documentation" color: "0075ca" description: "Documentation" - name: "duplicate" color: "cfd3d7" description: "This issue or pull request already exists" - name: "enhancement" color: "a2eeef" description: "New feature or request" - name: "good first issue" color: "7057ff" description: "Good for newcomers" - name: "help wanted" color: "008672" description: "Extra attention is needed" - name: "invalid" color: "e4e669" description: "This doesn't seem right" - name: "question" color: "d876e3" description: "Further information is requested" - name: "wontfix" color: "ffffff" description: "This will not be worked on" providerConfigRef: name: default ``` -------------------------------- ### ProviderConfig Custom Resource Example Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/provider-configuration.md Example of a ProviderConfig resource defining how the provider should authenticate. It specifies a Kubernetes secret for storing credentials. ```yaml apiVersion: github.upbound.io/v1beta1 kind: ProviderConfig metadata: name: default spec: credentials: source: Secret secretRef: name: provider-secret namespace: upbound-system key: credentials ``` -------------------------------- ### Cache Terraform Setup Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Caches the initialized Terraform setup with a Time-To-Live (TTL) for reuse. ```go tfSetups[configRefName] = CachedTerraformSetup{ setup: &ps, expiry: time.Now().Add(tfSetupCacheTTL), } ``` -------------------------------- ### Referencing Multiple ProviderConfigs for GitHub Repositories Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md This example demonstrates how to create GitHub repositories that reference distinct ProviderConfigs, enabling authentication with different GitHub organizations. Ensure that ProviderConfig resources named 'org-a-config' and 'org-b-config' are pre-configured with the appropriate credentials for each organization. ```yaml --- apiVersion: repo.github.upbound.io/v1alpha1 kind: Repository metadata: name: org-a-repo spec: forProvider: visibility: public providerConfigRef: name: org-a-config # Uses organization A credentials --- apiVersion: repo.github.upbound.io/v1alpha1 kind: Repository metadata: name: org-b-repo spec: forProvider: visibility: public providerConfigRef: name: org-b-config # Uses organization B credentials ``` -------------------------------- ### Example Usage of SecretKeySelector Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/api-reference-types.md Demonstrates how to reference a specific key from a Kubernetes Secret in YAML configuration, including the secret name, namespace, and key. ```yaml plaintextValueSecretRef: name: my-secret namespace: default key: password ``` -------------------------------- ### Tag Name Pattern Rule Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md Enforce naming conventions for tags. This example requires tag names to start with 'v' followed by numbers. ```yaml rules: - type: "tag_name_pattern" parameters: operator: "starts_with" pattern: "v[0-9]+" negate: false ``` -------------------------------- ### RBAC Check for CRD Permissions Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Verifies if the provider has 'get', 'list', and 'watch' permissions on CustomResourceDefinitions. This check is crucial for the SafeStart Gate to ensure proper RBAC setup before controller initialization. ```go verbs := []string{"get", "list", "watch"} for _, verb := range verbs { sar := &authv1.SelfSubjectAccessReview{ Spec: authv1.SelfSubjectAccessReviewSpec{ ResourceAttributes: &authv1.ResourceAttributes{ Group: "apiextensions.k8s.io", Resource: "customresourcedefinitions", Verb: verb, }, }, } if err := mgr.GetClient().Create(ctx, sar); err != nil { return false, errors.Wrapf(err, "unable to perform RBAC check for verb %s", verb) } if !sar.Status.Allowed { return false, nil } } return true, nil ``` -------------------------------- ### Creation Rule Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md Restrict who can create branches or tags. This example allows anyone to create, but can be restricted to admins. ```yaml rules: - type: "creation" parameters: restrictToAdmins: false ``` -------------------------------- ### Branch Name Pattern Rule Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md Enforce naming conventions for branches. This example requires branch names to start with 'feature/' or 'hotfix/'. ```yaml rules: - type: "branch_name_pattern" parameters: operator: "starts_with" pattern: "feature/|hotfix/" negate: false ``` -------------------------------- ### Using ProviderConfig in a Repository Resource Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/provider-configuration.md This example demonstrates how to reference a ProviderConfig in a GitHub Repository resource. Ensure the 'providerConfigRef.name' matches the name of your ProviderConfig resource. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: Repository metadata: name: my-repo spec: forProvider: visibility: public providerConfigRef: name: default ``` -------------------------------- ### Configure a GitHub Actions Variable Resource Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/api-reference-resources.md This example shows how to define an ActionsVariable resource in Kubernetes. It specifies the repository, the variable name, and the desired value for the variable. ```yaml apiVersion: actions.github.upbound.io/v1alpha1 kind: ActionsVariable metadata: name: deployment-region spec: forProvider: repository: "my-repo" variableName: "DEPLOY_REGION" value: "us-west-2" providerConfigRef: name: default ``` -------------------------------- ### Verify ProviderConfig Existence Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/error-handling.md Use `kubectl get providerconfigs` to list available ProviderConfigs and `kubectl describe providerconfig ` to check a specific one. Ensure the ProviderConfig name matches the reference and that it exists before the resource that references it. ```bash kubectl get providerconfigs kubectl describe providerconfig default ``` -------------------------------- ### Per-Resource Rate Limiting Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Example JSON configuration for setting per-resource delays in milliseconds for read and write operations. This allows fine-grained control over API interaction rates for specific resources. ```json { "token": "ghp_...", "owner": "myorg", "read_delay_ms": 100, "write_delay_ms": 200 } ``` -------------------------------- ### Describe Resource Status Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/error-handling.md Use this command to get detailed information about a specific Kubernetes resource, which can help identify its current state and potential issues. ```bash kubectl describe ``` -------------------------------- ### Configure a GitHub Actions Secret Resource Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/api-reference-resources.md This example demonstrates how to define an ActionsSecret resource in Kubernetes. It specifies the repository, the secret name, and references a Kubernetes Secret containing the plaintext value. ```yaml apiVersion: actions.github.upbound.io/v1alpha1 kind: ActionsSecret metadata: name: my-action-secret spec: forProvider: repository: "my-repo" secretName: "MY_SECRET" plaintextValueSecretRef: name: action-secret-value key: value providerConfigRef: name: default ``` -------------------------------- ### Management Policies Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Example YAML configuration for management policies. This allows fine-grained control over reconciliation operations like Create, Update, and Delete on a per-resource basis. ```yaml spec: managementPolicies: - Create - Update ``` -------------------------------- ### Personal Access Token (PAT) Authentication Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/INDEX.md Example JSON configuration for authenticating with the GitHub Provider using a Personal Access Token. Ensure the token and owner are correctly specified. ```json { "token": "ghp_...", "owner": "organization" } ``` -------------------------------- ### Valid JSON Formats for GitHub Credentials Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/error-handling.md Examples of valid JSON structures for GitHub credentials, including token-based and GitHub App-based authentication. ```json {"token": "ghp_...", "owner": "myorg"} ``` ```json {"app_auth": [{"id": "...", "installation_id": "...", "pem_file": "..."}], "owner": "myorg"} ``` -------------------------------- ### Upjet Controller Options Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Configures options for an Upjet-based controller, including logger, rate limiting, polling intervals, and metric settings. This setup is essential for initializing the controller's reconciliation loop. ```go clusterOpts := tjcontroller.Options{ Options: xpcontroller.Options{ Logger: logr, GlobalRateLimiter: ratelimiter.NewGlobal(*maxReconcileRate), PollInterval: *pollInterval, MaxConcurrentReconciles: *maxReconcileRate, Features: &feature.Flags{}, MetricOptions: &xpcontroller.MetricOptions{ PollStateMetricInterval: *pollStateMetricInterval, MRMetrics: metricRecorder, MRStateMetrics: stateMetrics, }, }, Provider: provider, SetupFn: clients.TerraformSetupBuilder(provider.TerraformProvider, logr), PollJitter: pollJitter, OperationTrackerStore: tjcontroller.NewOperationStore(logr), } ``` -------------------------------- ### Cluster-Scoped ProviderConfig Example Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/provider-configuration.md This snippet shows how to create a cluster-scoped ProviderConfig resource. It includes a Kubernetes Secret for storing credentials and the ProviderConfig resource itself, referencing the secret. ```yaml --- apiVersion: v1 kind: Secret metadata: name: provider-secret namespace: upbound-system type: Opaque stringData: credentials: '{"token":"ghp_xxxxxxxxxxxxxxxxxxxx","owner":"myorg"}' --- apiVersion: github.upbound.io/v1beta1 kind: ProviderConfig metadata: name: default spec: credentials: source: Secret secretRef: name: provider-secret namespace: upbound-system key: credentials ``` -------------------------------- ### Configure GitHub Provider with RepositoryFile Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/README.md This Go code demonstrates how to include the `repositoryfile.Configure` function in the main provider configuration. This ensures that the `github_repository_file` resource is correctly set up. ```go package config import ( "github.com/crossplane-contrib/provider-upjet-github/config/branchprotection" "github.com/crossplane-contrib/provider-upjet-github/config/defaultbranch" "github.com/crossplane-contrib/provider-upjet-github/config/repository" "github.com/crossplane-contrib/provider-upjet-github/config/repositoryfile" "github.com/crossplane-contrib/provider-upjet-github/config/team" "github.com/crossplane-contrib/provider-upjet-github/config/teamrepository" ujconfig "github.com/crossplane/upjet/pkg/config" ) func GetProvider() *ujconfig.Provider { defaults := ujconfig.DefaultInfo{ // The default group for all resources in this provider. // This is the same as the name of the provider. Group: "github.upbound.io", // The default version for all resources in this provider. Version: "v1alpha1", } controlleredDefaults := ujconfig.PolicyDefaultInfo{ // The default group for all resources in this provider. // This is the same as the name of the provider. Group: "github.upbound.io", // The default version for all resources in this provider. Version: "v1alpha1", } p := ujconfig.NewProvider(defaults, controlleredDefaults, // Add any custom config functions here. // These functions will be called in the order they are defined. ujconfig.WithRootGroup("github.upbound.io"), ujconfig.WithTerraformProviderName("github"), ujconfig.WithShortGroup("github"), ujconfig.WithTerraformProviderVersion("1.3.0"), ujconfig.WithResourcePackagePath("github.com/crossplane-contrib/provider-upjet-github/apis"), ujconfig.WithExternalNameConfigSetup( config.ExternalNameConfigurations{}), ujconfig.WithGeneratorConfig( config.Generator{}, ), ) // add custom config functions repository.Configure, branchprotection.Configure, defaultbranch.Configure, repository.Configure, branch.Configure, repositoryfile.Configure, team.Configure, teamrepository.Configure, defaultbranch.Configure, return p } ``` -------------------------------- ### Commit Message Pattern Rule Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md Enforce a specific format for commit messages. This example requires messages to start with a JIRA ticket identifier. ```yaml rules: - type: "commit_message_pattern" parameters: operator: "starts_with" pattern: "JIRA-[0-9]+" negate: false ``` -------------------------------- ### Create a GitHub Repository Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/api-reference-resources.md Use this snippet to create a new GitHub repository with specified configurations like visibility, description, and auto-initialization. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: Repository metadata: name: my-repo spec: forProvider: visibility: public description: "My repository" autoInit: true gitignoreTemplate: Go topics: - golang - crossplane providerConfigRef: name: default ``` -------------------------------- ### Initialize Provider Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/INDEX.md The entry point for the provider initializes the Kubernetes controller-runtime manager, API groups, controller hierarchies, feature flags, SafeStart capability check, and metrics recording. Flags can be used to control debug logging, cache sync period, drift check interval, max reconcile rate, and management policies. ```go func main() { // ... controller-runtime manager initialization // ... API group registration // ... dual controller hierarchies // ... feature flags // ... SafeStart capability check // ... metrics recording } ``` -------------------------------- ### Configure Terraform GitHub Client Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Initializes the Terraform GitHub provider with the constructed configuration. ```go err = configureNoForkGithubClient(ctx, &ps, *tfProvider) ``` -------------------------------- ### Thread-Safe Credential Caching Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Manages concurrent access to Terraform setups using a mutex. It attempts to lock, checks for a valid cached setup, and defers unlocking. ```go var tfSetupLock sync.RWMutex tfSetups := make(map[string]CachedTerraformSetup) // Lock and update credentials unlocked := tfSetupLock.TryLock() if !unlocked { // Return cached setup if available if ok && tfSetup.expiry.After(time.Now()) { return *tfSetup.setup, nil } return ps, errors.New(errGitHubTokenNotReady) } deffer unlockMutex(&tfSetupLock, logr) ``` -------------------------------- ### Unsafe Startup Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Initializes controllers immediately without a CRD gate. This can lead to errors if controllers attempt to access CustomResourceDefinitions that are not yet ready. ```go controllerCluster.Setup(mgr, clusterOpts) ``` -------------------------------- ### Provider Configuration Issues Reference Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/INDEX.md Troubleshoot missing provider configurations, invalid references, and credential issues. ```markdown | Error | |-------|-------| | "no providerConfigRef provided" | Missing reference in spec | | "cannot get referenced ProviderConfig" | ProviderConfig doesn't exist | | "cannot unmarshal github credentials as JSON" | Invalid JSON in Secret | | "github provider app_auth needs owner key" | App auth without owner | ``` -------------------------------- ### Example Invalid Request Error in Resource Status Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/error-handling.md This YAML snippet shows an example of an error message that might appear in a resource's status when the specification contains invalid values for the GitHub API. It indicates a 'TerraformError' with a message about an invalid visibility value. ```yaml status: conditions: - type: Synced status: "False" reason: "TerraformError" message: "Error creating github_repository: invalid visibility value" ``` -------------------------------- ### Add RepositoryFile to GitHub Provider Config Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/README.md This snippet shows how to configure the `github_repository_file` resource in the provider. It specifies the Kind, ShortGroup, and references for the repository and branch. ```go package repositoryfile import "github.com/crossplane/upjet/pkg/config" // Configure github_repository_file resource. func Configure(p *config.Provider) { p.AddResourceConfigurator("github_repository_file", func(r *config.Resource) { // We need to override the default group that upjet generated for // this resource, which would be "github" r.Kind = "RepositoryFile" r.ShortGroup = "repo" r.References["repository"] = config.Reference{ Type: "Repository", } r.References["branch"] = config.Reference{ Type: "Branch", } }) } ``` -------------------------------- ### Deletion Rule Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md Restrict who can delete branches or tags. This example allows anyone to delete, but can be restricted to admins. ```yaml rules: - type: "deletion" parameters: restrictToAdmins: false ``` -------------------------------- ### Declaring Cross-Resource References Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/configuration-reference.md Demonstrates how to declare cross-resource references using the `References` field. This enables references between Kubernetes resources. ```go r.References["repository"] = config.Reference{ Type: "Repository", } ``` ```go r.References["branch"] = config.Reference{ Type: "Branch", } ``` -------------------------------- ### Required Code Scanning Rule Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md Mandate code scanning checks to pass. This example configures 'semgrep' to run with a 'warning' severity. ```yaml rules: - type: "required_code_scanning" parameters: tools: - key: "semgrep" severity: "warning" ``` -------------------------------- ### Committer Email Pattern Rule Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md Restrict commits to specific committer email addresses. This example requires emails to contain '@company.com'. ```yaml rules: - type: "committer_email_pattern" parameters: operator: "contains" pattern: "@company.com$" negate: false ``` -------------------------------- ### Import GitHub Repository Resource Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/resource-catalog.md Use this command to import an existing GitHub repository into Crossplane. Ensure you provide the correct repository name, metadata name, and path. ```bash kubectl crossplane resource import github_repository \ -r my-repo \ --metadata-name my-repo \ --path my-repo ``` -------------------------------- ### Set up GitHub Repository Webhook with Crossplane Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/api-reference-resources.md Configure a webhook for a GitHub repository. Requires the repository name, webhook URL, and a list of events to trigger the webhook. Can be set to active, specify content type, and include a secret. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: RepositoryWebhook metadata: name: webhook-ci spec: forProvider: repository: "my-repo" url: "https://ci.example.com/webhook" active: true events: - push - pull_request contentType: json providerConfigRef: name: default ``` -------------------------------- ### Add CRD Watch Permissions to Provider RBAC Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/error-handling.md Apply this ClusterRole definition to grant the provider permissions to get, list, and watch CustomResourceDefinitions. ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: provider-upjet-github rules: - apiGroups: ["apiextensions.k8s.io"] resources: ["customresourcedefinitions"] verbs: ["get", "list", "watch"] ``` -------------------------------- ### Import GitHub Repository by Name Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/configuration-reference.md Import an existing GitHub repository using its name. The provider maps the Kubernetes metadata.name to the GitHub identifier. ```bash crossplane resource import github_repository \ -r my-repo \ --metadata-name my-repo ``` -------------------------------- ### Environment Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/api-reference-resources.md Represents a GitHub repository environment, enabling the configuration of deployment environments with options for descriptions, reviewers, and deployment branch policies. ```APIDOC ## Resource: Environment ### Description Represents a GitHub repository environment. Can be imported using: `repository:environment-name`. ### Kind `Environment` ### API Group `repo.github.upbound.io` ### API Version `v1alpha1` ### Specification Fields #### `repository` - **Type**: `string` - **Required**: Yes - **Description**: Repository name #### `environment` - **Type**: `string` - **Required**: Yes - **Description**: Environment name #### `description` - **Type**: `string` - **Required**: No - **Description**: Environment description #### `reviewers` - **Type**: `array` - **Required**: No - **Description**: Reviewers (teams or users) #### `deploymentBranchPolicy` - **Type**: `object` - **Required**: No - **Description**: Branch policy for deployments ### Example Usage ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: Environment metadata: name: production spec: forProvider: repository: "my-repo" environment: "production" description: "Production environment" providerConfigRef: name: default ``` ``` -------------------------------- ### Obtain Enterprise ID using GraphQL Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/README.md Use this GraphQL query with the GitHub CLI to get the enterprise ID, which is required for managing GitHub Enterprise organizations. ```bash gh api graphql -f query='query ($slug: String!) { enterprise(slug: $slug) { id } }' -F slug='' --jq '.data.enterprise.id' ``` -------------------------------- ### Safe Startup with CRD Gate Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Initializes controllers using a CRD gate, which delays startup until CRDs are ready. This ensures that controllers do not attempt to operate before their necessary CustomResourceDefinitions are available. ```go crdGate := new(gate.Gate[schema.GroupVersionKind]) clusterOpts.Gate = crdGate customresourcesgate.Setup(mgr, ...) controllerCluster.SetupGated(mgr, clusterOpts) ``` -------------------------------- ### Resource Creation Issues Reference Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/INDEX.md Diagnose and resolve errors related to invalid field values, non-existent resources, insufficient permissions, and rate limiting. ```markdown | Error | |-------|-------| | "invalid visibility value" | Invalid enum | | "422 Unprocessable Entity" | Invalid field values | | "404 Not Found" | Resource doesn't exist | | "403 Forbidden" | Insufficient permissions | | "429 Too Many Requests" | Rate limited | ``` -------------------------------- ### TerraformCustomDiff for Ignoring State Changes Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/configuration-reference.md Provides a custom diff function to ignore specific Terraform state changes. This example shows how to remove spurious diffs for empty arrays. ```go r.TerraformCustomDiff = func(diff *terraform.InstanceDiff, _ *terraform.InstanceState, _ *terraform.ResourceConfig) (*terraform.InstanceDiff, error) { if diff == nil || diff.Destroy { return diff, nil } // Remove spurious diffs for empty arrays if ppDiff, ok := diff.Attributes["topics.#"]; ok && ppDiff.Old == "" && ppDiff.New == "" { delete(diff.Attributes, "topics.#") } return diff, nil } ``` -------------------------------- ### Resource Status with Terraform Error Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Example YAML snippet showing a resource's status conditions when a reconciliation error occurs. It indicates a 'False' Synced status due to a 'TerraformError'. ```yaml status: conditions: - type: Synced status: "False" reason: "TerraformError" message: "Error creating github_repository: 422 Unprocessable Entity" lastTransitionTime: "2024-01-15T10:00:00Z" ``` -------------------------------- ### Resource Configurator Pattern Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/configuration-reference.md Illustrates the standard pattern for creating a resource configurator in Go for the Crossplane GitHub Provider. This pattern is used to customize how resources map to Terraform. ```go package resourcename import "github.com/crossplane/upjet/v2/pkg/config" // Configure github_resource_name resource. func Configure(p *config.Provider) { p.AddResourceConfigurator("github_resource_name", func(r *config.Resource) { // Customizations r.Kind = "ResourceName" r.ShortGroup = "group" // ... more config }) } ``` -------------------------------- ### Enable Debug Logging for Provider Upjet GitHub Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/error-handling.md Run the provider-upjet-github with the --debug flag to enable verbose logging. This is useful for understanding Terraform operations, credential handling, and reconciliation details. ```bash provider-upjet-github --debug ``` -------------------------------- ### Reduce Concurrent Reconciliation Rate Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/error-handling.md To prevent transient 'github token not ready yet' errors caused by token refreshes, reduce the maximum reconciliation rate. This can be done by setting the `--max-reconcile-rate` flag when starting the provider. ```bash provider-upjet-github --max-reconcile-rate=50 ``` -------------------------------- ### Setting ShortGroup for API Group Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/configuration-reference.md Demonstrates how to set the `ShortGroup` field to define the API group for a resource. This affects the resulting Kubernetes API endpoint. ```go r.ShortGroup = "repo" // → repo.github.upbound.io ``` ```go r.ShortGroup = "actions" // → actions.github.upbound.io ``` ```go r.ShortGroup = "team" // → team.github.upbound.io ``` -------------------------------- ### Check CRD Watch Permissions Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/configuration-reference.md This function checks if the provider has the necessary RBAC permissions to watch Custom Resource Definitions (CRDs). It's used in the SafeStart implementation to determine if controllers can start immediately or if they need to wait for CRDs to be ready. ```go func canWatchCRD(ctx context.Context, mgr manager.Manager) (bool, error) { verbs := []string{"get", "list", "watch"} for _, verb := range verbs { sar := &authv1.SelfSubjectAccessReview{ Spec: authv1.SelfSubjectAccessReviewSpec{ ResourceAttributes: &authv1.ResourceAttributes{ Group: "apiextensions.k8s.io", Resource: "customresourcedefinitions", Verb: verb, }, }, } if err := mgr.GetClient().Create(ctx, sar); err != nil { return false, errors.Wrapf(err, "unable to perform RBAC check for verb %s", verb) } if !sar.Status.Allowed { return false, nil } } return true, nil } ``` -------------------------------- ### Create Upjet Provider Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/configuration-reference.md This code snippet shows how to initialize an Upjet provider using the embedded schema and metadata. It passes the schema, provider name, import path, and metadata to the `ujconfig.NewProvider` function. ```go pc := ujconfig.NewProvider( []byte(providerSchema), "github", "github.com/crossplane-contrib/provider-upjet-github", []byte(providerMetadata), // ... options ) ``` -------------------------------- ### Manage GitHub Repository, Branch, and File Resources Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/README.md This YAML configuration defines a GitHub repository, a branch within that repository, and a file added to that branch. It demonstrates how to use Crossplane to manage these resources declaratively. ```yaml --- apiVersion: repo.github.upbound.io/v1alpha1 kind: Repository metadata: name: github-crossplane-file-test spec: forProvider: visibility: public autoInit: true gitignoreTemplate: Terraform providerConfigRef: name: default --- apiVersion: repo.github.upbound.io/v1alpha1 kind: Branch metadata: name: add-file-branch spec: forProvider: repositoryRef: name: github-crossplane-file-test providerConfigRef: name: default --- apiVersion: repo.github.upbound.io/v1alpha1 kind: RepositoryFile metadata: name: sample-file-dot-txt spec: forProvider: file: sample-file.txt content: | I am an crossplane provider. This should be nice. commitMessage: "managed by crossplane provider" commitAuthor: "Crossplane Github Provider" commitEmail: "github-provider@crossplane.com" repositoryRef: name: github-crossplane-file-test branchRef: name: add-file-branch providerConfigRef: name: default ``` -------------------------------- ### Create a GitHub Branch Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/api-reference-resources.md This snippet demonstrates how to create a new branch in a GitHub repository, specifying the source branch and linking to the repository resource. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: Branch metadata: name: feature-branch spec: forProvider: branch: "feature/new-feature" sourceBranch: "main" repositoryRef: name: my-repo providerConfigRef: name: default ``` -------------------------------- ### App Auth Struct Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/provider-configuration.md Defines the structure for GitHub App authentication within the provider configuration. ```go type appAuth struct { ID string // App ID InstallationID string // Installation ID AuthPemFile string // PEM-encoded private key } ``` -------------------------------- ### Configure GitHub Repository Environment with Crossplane Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/api-reference-resources.md Define a GitHub repository environment. Specify the repository, environment name, and an optional description. Supports configuring reviewers and deployment branch policies. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: Environment metadata: name: production spec: forProvider: repository: "my-repo" environment: "production" description: "Production environment" providerConfigRef: name: default ``` -------------------------------- ### Create GitHub Deploy Key with Crossplane Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/api-reference-resources.md Manage a GitHub deploy key for a repository. Requires the repository name, a title for the key, and the SSH public key. Can be configured for read-only access. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: DeployKey metadata: name: ci-deploy-key spec: forProvider: repository: "my-repo" title: "CI Deploy Key" key: "ssh-rsa AAAA..." readOnly: true providerConfigRef: name: default ``` -------------------------------- ### Verify Provider RBAC Permissions Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/error-handling.md Check the ClusterRole and ClusterRoleBinding for the provider to ensure it has the necessary permissions to watch CustomResourceDefinitions. ```bash kubectl get clusterrole -l app.kubernetes.io/name=provider-upjet-github kubectl get clusterrolebinding -l app.kubernetes.io/name=provider-upjet-github ``` -------------------------------- ### Initialize Controller Manager Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Initializes the Kubernetes controller-runtime manager responsible for orchestrating resource controllers. Configures leader election, cache sync period, and lease durations. ```go mgr, err := ctrl.NewManager(cfg, ctrl.Options{ LeaderElection: *leaderElection, LeaderElectionID: "crossplane-leader-election-provider-upjet-github", Cache: cache.Options{ SyncPeriod: syncPeriod, }, LeaderElectionResourceLock: resourcelock.LeasesResourceLock, LeaseDuration: func() *time.Duration { d := 60 * time.Second; return &d }(), RenewDeadline: func() *time.Duration { d := 50 * time.Second; return &d }(), }) ``` -------------------------------- ### Add RepositoryFile to README Table Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/README.md This diff shows the addition of `RepositoryFile` to the table of supported resources in the README.md file. It indicates that `RepositoryFile` is now a recognized resource type. ```diff diff --git a/README.md b/README.md index 06704c1..7adefad 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ You can see the API reference [here](https://doc.crds.dev/github.com/crossplane-contrib/p | `Branch` | `repo` | `github_branch` | | | `DefaultBranch` | `repo` | `github_branch_default` | name change | | `BranchProtection` | `repo` | `github_branch_protection` | | +| `RepositoryFile` | `repo` | `github_repository_file` | | | `Team` | `team` | `github_team` | | | `TeamRepository` | `team` | `github_team_repository` | | ``` -------------------------------- ### Configure Global Rate Limiter Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Initializes a global rate limiter to control the maximum number of reconciliation operations per second across all controllers. This is configurable via a command-line flag. ```go GlobalRateLimiter: ratelimiter.NewGlobal(*maxReconcileRate) ``` -------------------------------- ### View Provider Logs Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/INDEX.md Use this command to view the logs for the provider-upjet-github deployment in your Kubernetes cluster. ```bash kubectl logs -n upbound-system -l app.kubernetes.io/name=provider-upjet-github ``` -------------------------------- ### View Provider Logs in Real-time Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/error-handling.md Stream the logs for the provider-upjet-github deployment to monitor ongoing operations and identify errors. This command is useful for real-time debugging. ```bash kubectl logs -n upbound-system -l app.kubernetes.io/name=provider-upjet-github -f ``` -------------------------------- ### Configure Repository Autolink Reference Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md Use this snippet to automatically convert issue references in comments to links. Specify the repository, key prefix, and URL template. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: RepositoryAutolinkReference metadata: name: jira-autolink spec: forProvider: repository: "my-repo" keyPrefix: "JIRA-" urlTemplate: "https://jira.example.com/browse/JIRA-" isAlphanumeric: false providerConfigRef: name: default ``` -------------------------------- ### Set Up GitHub Branch Protection Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/INDEX.md This snippet configures branch protection rules for a specified repository and branch pattern. It enforces required approvals and admin restrictions. A ProviderConfig must be in place. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: BranchProtection metadata: name: main-protection spec: forProvider: repository: "my-repo" pattern: "main" enforceAdmins: true requiredApprovingReviewCount: 1 providerConfigRef: name: default ``` -------------------------------- ### Inspect ProviderConfig Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/error-handling.md Check the status and details of the ProviderConfig resource, which defines how the provider connects to external services. This is crucial for authentication and configuration issues. ```bash kubectl get providerconfig kubectl describe providerconfig default ``` -------------------------------- ### Configure GitHub Repository External Name Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/configuration-reference.md Use IdentifierFromProvider for resources that directly map to GitHub's own identifiers, such as repository names. ```go "github_repository": config.IdentifierFromProvider, ``` -------------------------------- ### GitHub Configuration Struct Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/provider-configuration.md Defines the structure for GitHub provider configuration, including API endpoints, authentication details, and retry settings. ```go type githubConfig struct { BaseURL *string // Custom API endpoint Owner *string // Organization or user Token *string // PAT token AppAuth *[]appAuth // GitHub App authentication WriteDelayMs *int // Write operation delay ReadDelayMs *int // Read operation delay RetryDelayMs *int // Retry backoff delay MaxRetries *int // Retry attempts RetryableErrors []int // HTTP codes to retry } ``` -------------------------------- ### Configure Environment Deployment Policy Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/advanced-resources.md Use this snippet to control which branches can deploy to a specific environment. Configure repository, environment, and branch policies. ```yaml apiVersion: repo.github.upbound.io/v1alpha1 kind: EnvironmentDeploymentPolicy metadata: name: prod-deployment-policy spec: forProvider: repository: "my-repo" environment: "production" protectedBranches: true customBranchPolicies: - "refs/heads/main" - "refs/heads/release/*" providerConfigRef: name: default ``` -------------------------------- ### Enable Feature Flags Programmatically Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/configuration-reference.md Enables feature flags within the provider's startup logic. This code snippet shows how to programmatically enable a feature flag based on a variable. ```go if *enableManagementPolicies { clusterOpts.Features.Enable(features.EnableBetaManagementPolicies) namespacedOpts.Features.Enable(features.EnableBetaManagementPolicies) } ``` -------------------------------- ### LateInitializer Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/configuration-reference.md Configures the `LateInitializer` to control which fields are populated from GitHub after resource creation. Ignored fields are not overwritten by the API response. ```go r.LateInitializer = config.LateInitializer{ IgnoredFields: []string{"private", "default_branch"}, } ``` -------------------------------- ### Increase Debug Verbosity Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/error-handling.md Enable debug logging for the provider-upjet-github deployment by setting the DEBUG environment variable to 'true'. This provides more detailed output for troubleshooting. ```bash kubectl set env -n upbound-system deployment/provider-upjet-github DEBUG=true ``` -------------------------------- ### Build Terraform Provider Configuration Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/controller-architecture.md Constructs the Terraform provider configuration from unmarshalled credentials. ```go ps.Configuration, err = terraformProviderConfigurationBuilder(creds) ``` -------------------------------- ### Reference Type for Cross-Resource Dependencies Source: https://github.com/crossplane-contrib/provider-upjet-github/blob/main/_autodocs/api-reference-types.md Represents a cross-resource reference used for defining dependencies between resources. It includes the name of the referenced resource and an optional resolution policy. ```go type Reference struct { Name string `json:"name"` Policy *Policy `json:"policy,omitempty"` } ```