### Install and Start godoc Server Source: https://github.com/carvel-dev/ytt/blob/develop/docs/dev.md Installs the godoc tool and starts a local server to view project documentation. Visit the provided URL to access the docs. ```bash go get -v golang.org/x/tools/cmd/godoc godoc -http=:6060 ``` -------------------------------- ### Install gopkg.in/check.v1 Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/gopkg.in/check.v1/README.md Install the gopkg.in/check.v1 package using the go get command. ```bash go get gopkg.in/check.v1 ``` -------------------------------- ### Install go-version Library Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/hashicorp/go-version/README.md Install the go-version library using the standard Go package manager. ```bash $ go get github.com/hashicorp/go-version ``` -------------------------------- ### Install Cobra Library Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/cobra/README.md Use 'go get' to install the latest version of the Cobra library. ```go go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Install difflib Go Library Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/k14s/difflib/README.md Use 'go get' to install the difflib library. This command fetches and installs the package and its dependencies. ```bash go get github.com/aryann/difflib ``` -------------------------------- ### Example Deployment with 5 Replicas Source: https://github.com/carvel-dev/ytt/blob/develop/examples/k8s-relative-rolling-update/README.md Demonstrates a basic Kubernetes deployment configuration specifying 5 replicas. ```yaml replicas: 5 ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/cobra/README.md Install the 'cobra-cli' command line program to generate Cobra application scaffolding. ```go go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Install TOML Go Package Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/BurntSushi/toml/README.md Add the TOML package to your go.mod file. Requires Go 1.13 or newer. ```bash % go get github.com/BurntSushi/toml@latest ``` -------------------------------- ### Install TOML Validator CLI Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/BurntSushi/toml/README.md Install the TOML validator command-line tool. This tool can be used to validate TOML files. ```bash % go install github.com/BurntSushi/toml/cmd/tomlv@latest % tomlv some-toml-file.toml ``` -------------------------------- ### Basic TOML Data Example Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/BurntSushi/toml/README.md A simple TOML structure with various data types including integers, strings, arrays, and timestamps. ```toml Age = 25 Cats = [ "Cauchy", "Plato" ] Pi = 3.14 Perfection = [ 6, 28, 496, 8128 ] DOB = 1987-07-05T05:45:00Z ``` -------------------------------- ### Check if Started by Explorer Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/inconshreveable/mousetrap/README.md This Go function checks if the current process was initiated by a double-click action in Windows Explorer. It returns a boolean value. ```go func StartedByExplorer() (bool) ``` -------------------------------- ### Import difflib in Go Project Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/k14s/difflib/README.md Import the difflib package along with other necessary packages like 'fmt' when starting to use the library in your Go project. ```go import ( ... "fmt" "github.com/aryann/difflib" ... ) ``` -------------------------------- ### TOML with Struct Tags for Key Mapping Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/BurntSushi/toml/README.md Example of TOML data with a key that does not directly map to a Go struct field name. Uses `toml` struct tags for mapping. ```toml some_key_NAME = "wat" ``` -------------------------------- ### Retrieve URL with LoadBalancer Service Source: https://github.com/carvel-dev/ytt/blob/develop/examples/playground/basics/example-k8s-helm-ish/NOTES.txt Exports the LoadBalancer IP to construct the application URL. Note that it may take a few minutes for the IP to become available. Use 'kubectl get svc -w ' to monitor status. ```bash export SERVICE_IP=$(kubectl get svc --namespace (@= data.values.Release.Namespace @) (@= fullname(data.values) @) -o jsonpath='{.status.loadBalancer.ingress[0].ip}') echo http://$SERVICE_IP:(@= str(data.values.service.externalPort) @) ``` -------------------------------- ### Retrieve URL with NodePort Service Source: https://github.com/carvel-dev/ytt/blob/develop/examples/playground/basics/example-k8s-helm-ish/NOTES.txt Exports the NodePort and Node IP to construct the application URL for NodePort services. Requires kubectl to be installed and configured. ```bash export NODE_PORT=$(kubectl get --namespace (@= data.values.Release.Namespace @) -o jsonpath="{.spec.ports[0].nodePort}" services (@= fullname(data.values) @)) export NODE_IP=$(kubectl get nodes --namespace (@= data.values.Release.Namespace @) -o jsonpath="{.items[0].status.addresses[0].address}") echo http://$NODE_IP:$NODE_PORT ``` -------------------------------- ### Deprecating a Flag Shorthand Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/pflag/README.md Illustrates how to deprecate a shorthand for a flag while keeping the flag itself active, with a message guiding users to the full flag name. ```go // deprecate a flag shorthand by specifying its flag name and a usage message flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only") ``` -------------------------------- ### Customizing Nil Pointer Chance Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/google/gofuzz/README.md Illustrates how to customize the probability of generating nil pointers for fields within a struct. This example sets the nil chance to 0.5, meaning about half of the pointers will be nil. ```go f := fuzz.New().NilChance(.5) var fancyStruct struct { A, B, C, D *string } f.Fuzz(&fancyStruct) // About half the pointers should be set. ``` -------------------------------- ### Custom Fuzzing Function for Complex Types Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/google/gofuzz/README.md Demonstrates advanced customization using `Funcs` to define specific fuzzing logic for a custom struct type. This example ensures that the `Type` field corresponds to whether `AInfo` or `BInfo` is set. ```go type MyEnum string const ( A MyEnum = "A" B MyEnum = "B" ) type MyInfo struct { Type MyEnum AInfo *string BInfo *string } f := fuzz.New().NilChance(0).Funcs( func(e *MyInfo, c fuzz.Continue) { switch c.Intn(2) { case 0: e.Type = A c.Fuzz(&e.AInfo) case 1: e.Type = B c.Fuzz(&e.BInfo) } }, ) var myObject MyInfo f.Fuzz(&myObject) // Type will correspond to whether A or B info is set. ``` -------------------------------- ### Run difflib Demo Application Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/k14s/difflib/README.md Execute the demo application using 'go run' with two file paths as arguments. The demo launches a web server displaying diff results. ```bash go run src/github.com/aryann/difflib/difflib_server/difflib_demo.go ``` -------------------------------- ### Check Version Against Constraints in Go Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/hashicorp/go-version/README.md Shows how to create a version constraint and check if a given version satisfies it. Error handling for NewConstraint is recommended. ```go v1, err := version.NewVersion("1.2") // Constraints example. constraints, err := version.NewConstraint(">= 1.0, < 1.4") if constraints.Check(v1) { fmt.Printf("%s satisfies constraints %s", v1, constraints) } ``` -------------------------------- ### Deprecating a Flag Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/pflag/README.md Shows how to mark a flag as deprecated, providing a message to guide users to a replacement flag. ```go // deprecate a flag by specifying its name and a usage message flags.MarkDeprecated("badflag", "please use --good-flag instead") ``` -------------------------------- ### Parse and Compare Versions in Go Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/hashicorp/go-version/README.md Demonstrates parsing version strings into version objects and comparing them using LessThan. Ensure error handling for NewVersion. ```go v1, err := version.NewVersion("1.2") v2, err := version.NewVersion("1.5+metadata") // Comparison example. There is also GreaterThan, Equal, and just // a simple Compare that returns an int allowing easy >=, <=, etc. if v1.LessThan(v2) { fmt.Printf("%s is less than %s", v1, v2) } ``` -------------------------------- ### Build Website Assets and Serve Locally Source: https://github.com/carvel-dev/ytt/blob/develop/docs/dev.md Combines website assets into a Go file and serves the ytt website locally for quick iteration. This command is useful for frontend development. ```bash ./hack/build.sh && ytt website ``` -------------------------------- ### Create ytt Template Options Instance Source: https://github.com/carvel-dev/ytt/blob/develop/examples/integrating-with-ytt/apis.md Create and populate an instance of the template command options. ```go opts := template.NewOptions() ``` -------------------------------- ### Import gopkg.in/check.v1 Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/gopkg.in/check.v1/README.md Import the gopkg.in/check.v1 package into your Go code. Use '_check_' as the package alias. ```go import "gopkg.in/check.v1" // Use _check_ as the package name inside the code. ``` -------------------------------- ### Get flag value from FlagSet Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/pflag/README.md Retrieve the integer value of a flag named 'flagname' from a pflag.FlagSet. This method will fail if the flag does not exist or is not an integer. ```go i, err := flagset.GetInt("flagname") ``` -------------------------------- ### Importing and Basic Fuzzing of a Single Variable Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/google/gofuzz/README.md Demonstrates how to import the gofuzz library and use it to populate a single integer variable with a random value. ```go import "github.com/google/gofuzz" f := fuzz.New() var myInt int f.Fuzz(&myInt) // myInt gets a random value. ``` -------------------------------- ### Configuring Library and Other Data Values Source: https://github.com/carvel-dev/ytt/blob/develop/examples/data-values-wrap-library/README.md This snippet shows how to configure both a specific library's data values (e.g., '@app1:other') and general data values ('image.username') simultaneously. This allows for fine-grained control over nested configurations. ```bash $ ytt -f . -v image.username=bob -v @app1:other=new-config vals: image: url: registry.com/bob/repo other: new-config ``` -------------------------------- ### Process Configuration with YTT Library Source: https://github.com/carvel-dev/ytt/blob/develop/examples/playground/basics/example-ytt-library-module/README.md Applies YTT to the configuration directory, which includes custom library definitions. ```bash $ ytt -f ./examples/playground/example-ytt-library-module ``` -------------------------------- ### Clone Cobra Repository Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/cobra/CONTRIBUTING.md Download a local copy of the Cobra project to your machine. This is the first step in contributing. ```bash git clone https://github.com/your_username/cobra && cd cobra ``` -------------------------------- ### Applying Environment-Specific Configurations Source: https://github.com/carvel-dev/ytt/blob/develop/examples/data-values-multiple-envs/README.md These commands apply the base configuration from 'config/' along with environment-specific data values from 'envs/dev.yml', 'envs/staging.yml', or 'envs/prod.yml'. ```bash ytt -f config/ -f envs/dev.yml ``` ```bash ytt -f config/ -f envs/staging.yml ``` ```bash ytt -f config/ -f envs/prod.yml ``` -------------------------------- ### Run ytt Overlay Source: https://github.com/carvel-dev/ytt/blob/develop/examples/k8s-update-env-var/README.md Execute the ytt command to apply overlays to the current directory's configuration files. ```bash ytt -f . ``` -------------------------------- ### Run Tests with Make Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/cobra/CONTRIBUTING.md An alternative method to run tests using the make utility. Ensure tests pass before submitting code. ```bash make test ``` -------------------------------- ### Basic Data Values Configuration Source: https://github.com/carvel-dev/ytt/blob/develop/examples/data-values-wrap-library/README.md This snippet shows the default output when no specific data values are provided. It displays the initial configuration of 'vals.image.url' and 'vals.other'. ```bash $ ytt -f . vals: image: url: registry.com//repo other: config ``` -------------------------------- ### Clone ytt and Build Project Source: https://github.com/carvel-dev/ytt/blob/develop/docs/dev.md Clones the ytt repository and executes the build script. Ensure you are in the correct directory before running. ```bash git clone https://github.com/carvel-dev/ytt ./src/github.com/carvel-dev/ytt export GOPATH=$PWD cd ./src/github.com/carvel-dev/ytt ./hack/build.sh ./hack/test-unit.sh ./hack/test-e2e.sh ./hack/test-all.sh ``` -------------------------------- ### ytt Command with Data Values Directory Source: https://github.com/carvel-dev/ytt/blob/develop/examples/data-values-directory/README.md Shows the command-line execution of ytt, specifying a configuration file and a directory for data values. ```bash $ ytt -f examples/data-values-directory/config.yml \ --data-values-file examples/data-values-directory/values/ ``` -------------------------------- ### Sort Versions in Go Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/hashicorp/go-version/README.md Illustrates sorting a slice of version strings using the go-version library's collection type. This correctly handles prerelease versions and SemVer ordering. ```go versionsRaw := []string{"1.1", "0.7.1", "1.4-beta", "1.4", "2"} versions := make([]*version.Version, len(versionsRaw)) for i, raw := range versionsRaw { v, _ := version.NewVersion(raw) versions[i] = v } // After this, the versions are properly sorted sort.Sort(version.Collection(versions)) ``` -------------------------------- ### Applying Base Configuration with Version Override Source: https://github.com/carvel-dev/ytt/blob/develop/examples/data-values-multiple-envs/README.md This command applies the base configuration from the 'config/' directory and overrides the 'version' data value. ```bash ytt -f config/ -v version=123 ``` -------------------------------- ### Display Default Schema Values Source: https://github.com/carvel-dev/ytt/blob/develop/examples/schema/README.md Run this command to see the default values from the schema file in the output. ```bash ytt -f config.yml -f schema.yml ``` -------------------------------- ### ConfigMap with Initial Configuration Source: https://github.com/carvel-dev/ytt/blob/develop/examples/k8s-overlay-in-config-map/expected.txt Defines a ConfigMap with an initial set of key-value pairs for configuration. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: conf1 data: contents.yml: | some_key: true another_key: true shared_conf: val ``` -------------------------------- ### Fuzzing a Map with Customizations Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/google/gofuzz/README.md Shows how to fuzz a map, customizing the chance of nil pointers to 0 and ensuring exactly one element in the map. ```go f := fuzz.New().NilChance(0).NumElements(1, 1) var myMap map[ComplexKeyType]string f.Fuzz(&myMap) // myMap will have exactly one element. ``` -------------------------------- ### Run All Tests Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/cobra/CONTRIBUTING.md Execute all tests for the project. This command is useful for verifying code changes before submission. ```bash go test ./... ``` -------------------------------- ### Unmarshal and Marshal YAML Data in Go Source: https://github.com/carvel-dev/ytt/blob/develop/pkg/yamlmeta/internal/yaml.v2/README.md Demonstrates how to unmarshal YAML data into a Go struct and a map, and then marshal them back into YAML format. Ensure struct fields are public for correct unmarshalling. ```Go package main import ( "fmt" "log" "carvel.dev/ytt/pkg/yamlmeta/internal/yaml.v2" ) var data = ` a: Easy! b: c: 2 d: [3, 4] ` // Note: struct fields must be public in order for unmarshal to // correctly populate the data. type T struct { A string B struct { RenamedC int `yaml:"c"` D []int `yaml:",flow"` } } func main() { t := T{} err := yaml.Unmarshal([]byte(data), &t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t:\n%v\n\n", t) d, err := yaml.Marshal(&t) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- t dump:\n%s\n\n", string(d)) m := make(map[interface{}]interface{}) err = yaml.Unmarshal([]byte(data), &m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m:\n%v\n\n", m) d, err = yaml.Marshal(&m) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("--- m dump:\n%s\n\n", string(d)) } ``` -------------------------------- ### Invoke ytt Command to Evaluate Source: https://github.com/carvel-dev/ytt/blob/develop/examples/integrating-with-ytt/apis.md Invoke the ytt command with the specified inputs and UI configuration to evaluate templates. ```go output := opts.RunWithFiles(inputs, ui) ``` -------------------------------- ### Supporting Go Flags with pflag Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/pflag/README.md Explains how to integrate flags defined using Go's standard `flag` package into a `pflag` flagset, often needed for third-party libraries. ```go import ( goflag "flag" flag "github.com/spf13/pflag" ) var ip *int = flag.Int("flagname", 1234, "help message for flagname") func main() { flag.CommandLine.AddGoFlagSet(goflag.CommandLine) flag.Parse() } ``` -------------------------------- ### Format Code and Run Tests Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/cobra/CONTRIBUTING.md Ensures code consistency by formatting and running all tests. This is a required step before submitting changes. ```bash make all ``` -------------------------------- ### Import pflag as flag Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/pflag/README.md Import the pflag package with the alias 'flag' to use it as a drop-in replacement for Go's native flag package. ```go import flag "github.com/spf13/pflag" ``` -------------------------------- ### Apply Default Labeling Source: https://github.com/carvel-dev/ytt/blob/develop/examples/k8s-add-global-label/README.md Use this command to apply default labeling to all resources in the current directory. Ensure your YTT configuration defines the default label. ```bash ytt -f . # uses defaults ``` -------------------------------- ### Client VPN Connection Handler Sample Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/aws/aws-lambda-go/events/README_ClientVPN.md A sample AWS Lambda function in Go that processes Client VPN connection requests. It validates the source IP against a predefined map and logs the request and decision to CloudWatch Logs. This function requires the 'aws-lambda-go/events' and 'aws-lambda-go/lambda' packages. ```go import ( "fmt" "log" "net" "encoding/json" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) var ( AllowedIPs = map[string]bool{ "10.11.12.13": true, } ) func handler(request events.ClientVPNConnectionHandlerRequest) (events.ClientVPNConnectionHandlerResponse, error) { requestJson, _ := json.MarshalIndent(request, "", " ") log.Printf("REQUEST: %s", requestJson) sourceIP := request.PublicIP if net.ParseIP(sourceIP) == nil { return events.ClientVPNConnectionHandlerResponse{}, fmt.Errorf("Invalid parameter PublicIP passed in request: %q", sourceIP) } log.Printf("SOURCE IP: %q", sourceIP) if allowed, ok := AllowedIPs[sourceIP]; ok && allowed { log.Printf("Allowing access from: %q", sourceIP) return events.ClientVPNConnectionHandlerResponse{ Allow: true, ErrorMsgOnFailedPostureCompliance: "", PostureComplianceStatuses: []string{}, SchemaVersion: "v1", }, nil } log.Printf("Blocking access from: %q", sourceIP) return events.ClientVPNConnectionHandlerResponse{ Allow: false, ErrorMsgOnFailedPostureCompliance: "You're trying to connect from an IP address that is not allowed.", PostureComplianceStatuses: []string{"BlockedSourceIP"}, SchemaVersion: "v1", }, nil } func main() { lambda.Start(handler) } ``` -------------------------------- ### pflag Command Line Flag Syntax Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/pflag/README.md Illustrates the basic syntax for pflag command-line flags, including long flags with and without values, and shorthand flag usage. ```bash --flag // boolean flags, or flags with no option default values --flag x // only on flags without a default value --flag=x ``` ```bash // boolean or flags where the 'no option default value' is set -f -f=true -abc but -b true is INVALID // non-boolean and flags without a 'no option default value' -n 1234 -n=1234 -n1234 // mixed -abcs "hello" -absd="hello" -abcs1234 ``` -------------------------------- ### Integrating go-fuzz with go-fuzz Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/google/gofuzz/README.md Shows how to use gofuzz to convert a byte slice from go-fuzz into an integer input for a function `MyFunc`. This is useful for fuzzing functions that expect specific types. ```go // +build gofuzz package mypackage import fuzz "github.com/google/gofuzz" func Fuzz(data []byte) int { var i int fuzz.NewFromGoFuzz(data).Fuzz(&i) MyFunc(i) return 0 } ``` -------------------------------- ### Accept Raw JSON Blob in Go Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/aws/aws-lambda-go/events/README_CloudWatch_Events.md Shows how to accept a raw JSON blob as a byte slice (json.RawMessage) when the exact structure of the CloudWatch Event payload is unknown or varies. ```go import "encoding/json" func handler(ctx context.Context, b json.RawMessage) { // json.RawMessage is basically []byte which can be unmarshalled } ``` -------------------------------- ### Directory Structure for Data Values Source: https://github.com/carvel-dev/ytt/blob/develop/examples/data-values-directory/README.md Illustrates the expected directory layout for providing data values to ytt. Non-YAML files are ignored. ```text ├── config │ ├── config.yml │ └── values-schema.yml └── values <-- any YAML under here is assumed to be plain Data Values ├── appdev-overrides <-- sorted by full pathname, alphabetically │ └── values.yaml └── operator-overrides ├── 50-operations-overrides.yml ├── 99-opssec-overrides.yml └── approvals.toml <-- non YAML files are ignored. ``` -------------------------------- ### Sample CodeCommit Event Handler in Go Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/aws/aws-lambda-go/events/README_CodeCommit.md A basic Lambda function that accepts CodeCommit event records and prints them to standard output. Ensure the 'github.com/aws/aws-lambda-go/events' package is imported. ```go import ( "fmt" "github.com/aws/aws-lambda-go/events" ) func handleRequest(evt events.CodeCommitEvent) { for _, record := range evt.Records { fmt.Println(record) } } ``` -------------------------------- ### External Data Values File Configuration Source: https://github.com/carvel-dev/ytt/blob/develop/examples/data-values-wrap-library/README.md This snippet demonstrates using an external YAML file to define data values, including library-specific configurations. This approach is useful for managing complex configurations or sharing them across different contexts. ```yaml #@data/values --- image: username: bob #@data/values #@library/ref "@app1" --- other: new-config ``` ```bash $ ytt -f . -f /tmp/custom.yml vals: image: url: registry.com/bob/repo other: new-config ``` -------------------------------- ### Add ytt as a Go Module Dependency Source: https://github.com/carvel-dev/ytt/blob/develop/examples/integrating-with-ytt/apis.md Add ytt as a dependency in your go.mod file to use it as a Go module. ```go.mod require ( ... carvel.dev/ytt v0.40.0 ... ) ``` -------------------------------- ### Cognito Pre-Signup Lambda Handler in Go Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/aws/aws-lambda-go/events/README_Cognito_UserPools_PreSignup.md A sample Go Lambda function that receives a Cognito User Pools pre-signup event, logs the username, and automatically confirms the user. This function is designed to be triggered by Cognito User Pools. ```go package main import ( "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) // handler is the lambda handler invoked by the `lambda.Start` function call func handler(event events.CognitoEventUserPoolsPreSignup) (events.CognitoEventUserPoolsPreSignup, error) { fmt.Printf("PreSignup of user: %s\n", event.UserName) event.Response.AutoConfirmUser = true return event, nil } func main() { lambda.Start(handler) } ``` -------------------------------- ### Access Application with ClusterIP Service Source: https://github.com/carvel-dev/ytt/blob/develop/examples/playground/basics/example-k8s-helm-ish/NOTES.txt For ClusterIP services, this sets up port forwarding to access the application locally. It retrieves the pod name and then uses kubectl port-forward. ```bash export POD_NAME=$(kubectl get pods --namespace (@= data.values.Release.Namespace @) -l "app.kubernetes.io/name=(@= name(data.values) @),app.kubernetes.io/instance=(@= data.values.Release.Name @)" -o jsonpath="{.items[0].metadata.name}") echo "Visit http://127.0.0.1:8080 to use your application" kubectl port-forward $POD_NAME 8080:80 ``` -------------------------------- ### Custom Flag Name Normalization Function Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/pflag/README.md Demonstrates how to set a custom normalization function for flag names to handle variations like hyphens, underscores, and periods, or to create aliases. ```go func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { from := []string{"-", "_"} to := "." for _, sep := range from { name = strings.Replace(name, sep, to, -1) } return pflag.NormalizedName(name) } myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc) ``` ```go func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { switch name { case "old-flag-name": name = "new-flag-name" break } return pflag.NormalizedName(name) } myFlagSet.SetNormalizeFunc(aliasNormalizeFunc) ``` -------------------------------- ### Handle ALB Target Group Request in Go Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/aws/aws-lambda-go/events/README_ALBTargetGroupEvents.md A sample Go function to process ALB Target Group events. It logs request details like trace ID, body size, and headers, then returns a 200 OK response with the original request body. ```go package main import ( "context" "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func handleRequest(ctx context.Context, request events.ALBTargetGroupRequest) (events.ALBTargetGroupResponse, error) { fmt.Printf("Processing request data for traceId %s.\n", request.Headers["x-amzn-trace-id"]) fmt.Printf("Body size = %d.\n", len(request.Body)) fmt.Println("Headers:") for key, value := range request.Headers { fmt.Printf(" %s: %s\n", key, value) } return events.ALBTargetGroupResponse{Body: request.Body, StatusCode: 200, StatusDescription: "200 OK", IsBase64Encoded: false, Headers: map[string]string{}}, nil } func main() { lambda.Start(handleRequest) } ``` -------------------------------- ### Parse command-line arguments Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/pflag/README.md After defining all flags, call flag.Parse() to parse the command line into the defined flags. ```go flag.Parse() ``` -------------------------------- ### Helm Chart RBAC Adjustment Pipeline Source: https://github.com/carvel-dev/ytt/blob/develop/examples/k8s-adjust-rbac-version/README.md This command pipeline shows how to template a Helm chart, apply RBAC fixes using ytt, and then deploy the modified resources with kapp. ```bash helm template ... | ytt -f- -f rbac-fix.yml | kapp deploy -a app1 -f- -y ``` -------------------------------- ### Go Lambda Function for CodeDeploy Events Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/aws/aws-lambda-go/events/README_CodeDeploy.md A sample AWS Lambda function written in Go that accepts and prints a CodeDeploy event. Ensure the 'github.com/aws/aws-lambda-go/events' package is imported. ```go import ( "fmt" "github.com/aws/aws-lambda-go/events" ) func handleRequest(evt events.CodeDeployEvent) { fmt.Println(evt) } ``` -------------------------------- ### Import Cobra in Go Application Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/cobra/README.md Include Cobra in your Go application by importing the package. ```go import "github.com/spf13/cobra" ``` -------------------------------- ### ytt Command for Helm Upgrade with Post-Renderer Source: https://github.com/carvel-dev/ytt/blob/develop/examples/k8s-overlay-ingress/ReadMe.md This command orchestrates a Helm upgrade, using ytt for data value schema validation and a post-renderer script to apply ytt overlays on the Helm-generated output. It's useful for managing complex Helm chart configurations that require dynamic patching. ```text ytt -f "./config.yaml" -f "./schema.yml" --data-value cluster="my-cluster" \ | helm upgrade --atomic --install "HELM_INSTALL_NAME" "HELM_CHART_NAME" --version "HELM_VERSION" --create-namespace --namespace "KUBERNETES_NAMESPACE" --values - \ --post-renderer "./ytt-helm-postrender/ytt-overlay-on-helm-post-renderer.sh" ``` -------------------------------- ### Helm Template with YTT Post-Renderer Source: https://github.com/carvel-dev/ytt/blob/develop/examples/helm-ytt-post-renderer/README.md This command uses Helm to template a chart and pipes the output through a local ytt post-renderer script. The `--post-renderer` flag specifies the script to execute. ```bash helm repo add stable https://kubernetes-charts.storage.googleapis.com helm pull --untar stable/postgresql helm template postgresql postgresql/ --post-renderer ./ytt-post-renderer ``` -------------------------------- ### Hiding a Flag Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/pflag/README.md Demonstrates how to mark a flag as hidden, so it functions normally but does not appear in help or usage text. ```go // hide a flag by specifying its name flags.MarkHidden("secretFlag") ``` -------------------------------- ### Move Library Directory Source: https://github.com/carvel-dev/ytt/blob/develop/examples/playground/basics/example-ytt-library-module/README.md Renames the library directory from _ytt_lib1 to _ytt_lib to prepare for YTT processing. ```bash # turn _ytt_lib1 -> _ytt_lib $ mv ./examples/playground/example-ytt-library-module/_ytt_lib{1,} ``` -------------------------------- ### Go Code for Initializing Files Map Source: https://github.com/carvel-dev/ytt/blob/develop/pkg/website/generated.go.txt Initializes a Go map named 'Files' with file names and their content. The content is processed by the 'golang_escape_tick' function to handle backticks correctly within Go string literals. ```Go func init() { Files = map[string]File{ "(@= name @)": File{ Name: "(@= name @)", Content: `(@= golang_escape_tick(data.read(name)) @)`, }, } exampleSets = []exampleSet{ (@ for group in exampleSets: @) { ID: "(@= group["id"] @)", DisplayName: "(@= group["id"].replace("-", " ").title() @)", Description: "(@= group["description"] @)", Examples: []Example{ (@ for example in group["examples"]: @) { ID: "(@= example["id"] @)", DisplayName: "(@= example["id"].replace("example-", "").replace("-", " ").capitalize() @)", Files: []File{ (@ for file in example["files"]: @) (@ if file.endswith("README.md"): @)(@ continue @)(@ end @) { Name: "(@= file.replace(example["id"]+"/", "", 1).replace("_ytt_lib1", "_ytt_lib") @)", Content: `(@= golang_escape_tick(data.read(file)) @)`, }, (@ end @) }, ``` -------------------------------- ### ConfigMap with Multiple YAML and JSON Files Source: https://github.com/carvel-dev/ytt/blob/develop/examples/k8s-config-map-files/expected.txt This ConfigMap contains multiple data entries, each representing a file. It includes YAML files with and without YAML document separators, and a JSON file. ```yaml kind: ConfigMap apiVersion: v1 metadata: name: configs data: config1.yml: | config1a: config1a config1b: config1b --- config1c: config1c config2.yml: | rules2a: 123 rules2b: - a - b - c config2.json: '{"rules2a":123,"rules2b":["a","b","c"]}' config3.yml: | config3a: config3a --- config3c: config3c ``` -------------------------------- ### Go Struct with TOML Struct Tags Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/BurntSushi/toml/README.md Define a Go struct with `toml` struct tags to map TOML keys to struct fields when names differ. ```go type TOML struct { ObscureKey string `toml:"some_key_NAME"` } ``` -------------------------------- ### Stage Changes Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/cobra/CONTRIBUTING.md Add modified files to the staging area. This prepares them for the next commit. ```bash git add . ``` -------------------------------- ### Define and Use Custom ytt Function Source: https://github.com/carvel-dev/ytt/blob/develop/pkg/texttemplate/filetests/def.txt Defines a custom ytt function 'lines' that generates a specified number of 'lineX' strings and a function 'other_lines' that outputs a fixed string. Demonstrates calling these functions and interpolating their output. ```ytt (@ def lines(x): @) (@- for i in range(0,x): -@) line(@= str(i) @) (@ end -@) (@ end @) (@- def other_lines(): -@) singleline (@ end -@) before(@= lines(5)+lines(5) @)after +++ beforeline0 line1 line2 line3 line4 line0 line1 line2 line3 line4 after ``` -------------------------------- ### Set Docker Credentials via Environment Variables Source: https://github.com/carvel-dev/ytt/blob/develop/examples/k8s-docker-secret/README.md Export your Docker server, username, and password as environment variables. These will be used by YTT to populate the secret. ```bash export CFG_docker__server=https://docker.io export CFG_docker__username=dkalinin export CFG_docker__password=secret ``` -------------------------------- ### Go Lambda Function for CloudWatch Logs Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/aws/aws-lambda-go/events/README_CloudWatch_Logs.md A sample Go Lambda function that parses incoming CloudWatch Logs event records and prints the message content of each log event. This function demonstrates the basic structure for processing CloudWatch Logs data. ```go import ( "context" "fmt" "github.com/aws/aws-lambda-go/events" ) func handler(ctx context.Context, logsEvent events.CloudwatchLogsEvent) { data, _ := logsEvent.AWSLogs.Parse() for _, logEvent := range data.LogEvents { fmt.Printf("Message = %s\n", logEvent.Message) } } ``` -------------------------------- ### Commit Changes Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/cobra/CONTRIBUTING.md Record your staged changes to the local repository with a descriptive commit message. ```bash git commit -m 'Add some feature' ``` -------------------------------- ### Sample SES Event Handler in Go Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/aws/aws-lambda-go/events/README_SES.md A Go Lambda function that receives and processes Amazon SES event data. It logs mail and receipt details and returns a success status. ```go package main import ( "context" "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func handler(ctx context.Context, sesEvent events.SimpleEmailEvent) error { for _, record := range sesEvent.Records { ses := record.SES fmt.Printf("[%s - %s] Mail = %+v, Receipt = %+v \n", record.EventVersion, record.EventSource, ses.Mail, ses.Receipt) } return nil } func main() { lambda.Start(handler) } ``` -------------------------------- ### Define an integer flag Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/pflag/README.md Declare an integer flag with a name, default value, and help message. The flag's value is stored in a pointer to an integer. ```go var ip *int = flag.Int("flagname", 1234, "help message for flagname") ``` -------------------------------- ### TOML Data with Email Addresses Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/BurntSushi/toml/README.md TOML data containing a list of contact strings, each representing a name and email address. ```toml contacts = [ "Donald Duck ", "Scrooge McDuck ", ] ``` -------------------------------- ### Go Lambda Function for AWS Config Events Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/aws/aws-lambda-go/events/README_Config.md This Go code demonstrates how to create an AWS Lambda function that accepts and processes AWS Config event records. It logs specific details from the event, such as the rule name, invoking event, and version, to CloudWatch Logs. ```go import ( "context" "fmt" "strings" "github.com/aws/aws-lambda-go/events" ) func handleRequest(ctx context.Context, configEvent events.ConfigEvent) { fmt.Printf("AWS Config rule: %s\n", configEvent.ConfigRuleName) fmt.Printf("Invoking event JSON: %s\n", configEvent.InvokingEvent) fmt.Printf("Event version: %s\n", configEvent.Version) } ``` -------------------------------- ### Push Branch Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/spf13/cobra/CONTRIBUTING.md Upload your local feature branch to your fork on GitHub. This makes your changes available for a pull request. ```bash git push origin my-new-feature ``` -------------------------------- ### Go Lambda Function for S3 Batch Job Events Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/aws/aws-lambda-go/events/README_S3_Batch_Job.md This Go function serves as a handler for S3 Batch Job events. It logs key information from the incoming event, such as invocation details, job ID, and task-specific data. It also demonstrates how to format and return a response, including results for each task. Ensure the necessary AWS SDK for Go packages are imported. ```go import ( "fmt" "context" "github.com/aws/aws-lambda-go/events" ) func handler(ctx context.Context, e events.S3BatchJobEvent) (response events.S3BatchJobResponse, err error) { fmt.Printf("InvocationSchemaVersion: %s\n", e.InvocationSchemaVersion) fmt.Printf("InvocationID: %s\n", e.InvocationID) fmt.Printf("Job.ID: %s\n", e.Job.ID) for _, task := range e.Tasks { fmt.Printf("TaskID: %s\n", task.TaskID) fmt.Printf("S3Key: %s\n", task.S3Key) fmt.Printf("S3VersionID: %s\n", task.S3VersionID) fmt.Printf("S3BucketARN: %s\n", task.S3BucketARN) } fmt.Printf("InvocationSchemaVersion: %s\n", response.InvocationSchemaVersion) fmt.Printf("TreatMissingKeysAs: %s\n", response.TreatMissingKeysAs) fmt.Printf("InvocationID: %s\n", response.InvocationID) for _, result := range response.Results { fmt.Printf("TaskID: %s\n", result.TaskID) fmt.Printf("ResultCode: %s\n", result.ResultCode) fmt.Printf("ResultString: %s\n", result.ResultString) } return } ``` -------------------------------- ### Generate HTML Diff Output Source: https://github.com/carvel-dev/ytt/blob/develop/vendor/github.com/k14s/difflib/README.md Call the HTMLDiff function with two string slices to generate an HTML representation of the differences between them. ```go fmt.Println(difflib.HTMLDiff([]string{"one", "two", "three"}, []string{"two", "four", "three"})) ```