### Install Objx Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/stretchr/objx/README.md Install the Objx package using the go get command. ```bash go get github.com/stretchr/objx ``` -------------------------------- ### Install Mergo Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/dario.cat/mergo/README.md Install the Mergo library using go get. ```go go get dario.cat/mergo ``` -------------------------------- ### Install Cobra Library Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/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 multierr Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/go.uber.org/multierr/README.md Use 'go get' to install the latest version of the multierr package. ```bash go get -u go.uber.org/multierr@latest ``` -------------------------------- ### Install Flaggy Go Library Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/integrii/flaggy/README.md Use 'go get' to install the Flaggy library. This command fetches and installs the latest version of the package. ```bash go get -u github.com/integrii/flaggy ``` -------------------------------- ### Install go.yaml.in/yaml/v3 Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/go.yaml.in/yaml/v3/README.md Use 'go get' to install the latest version of the YAML package for Go. ```bash go get go.yaml.in/yaml/v3 ``` -------------------------------- ### Super Simple Flaggy Example Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/integrii/flaggy/README.md Demonstrates the basic usage of Flaggy by declaring a string flag, parsing it, and then printing its value. This is a good starting point for understanding Flaggy's core functionality. ```go // Declare variables and their defaults var stringFlag = "defaultValue" // Add a flag flaggy.String(&stringFlag, "f", "flag", "A test string flag") // Parse the flag flaggy.Parse() // Use the flag print(stringFlag) ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/json-iterator/go/README.md Use the go get command to install the json-iterator/go package into your project. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Install godbus/dbus Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/godbus/dbus/v5/README.md Install the library using the go get command. Requires Go 1.12 or later. ```bash go get github.com/godbus/dbus/v5 ``` -------------------------------- ### Install YAML Package for Go Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/gopkg.in/yaml.v3/README.md Use `go get` to install the `gopkg.in/yaml.v3` package. This command fetches and installs the specified package and its dependencies. ```Go go get gopkg.in/yaml.v3 ``` -------------------------------- ### Example Output for Latest Binaries Source: https://github.com/awslabs/amazon-eks-ami/blob/main/doc/usage/overview.md This is an example of the output from the `hack/latest-binaries.sh` script, showing the resolved Kubernetes version and build date. ```bash > hack/latest-binaries.sh 1.28 us-west-2 kubernetes_version=1.28.1 kubernetes_build_date=2023-10-01 ``` -------------------------------- ### Basic Flaggy Setup and Usage in Go Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/integrii/flaggy/README.md Demonstrates setting program name, description, and parsing flags. Use this for initializing your command-line application with flaggy. ```go package main import "github.com/integrii/flaggy" // Make a variable for the version which will be set at build time. var version = "unknown" // Keep subcommands as globals so you can easily check if they were used later on. var mySubcommand *flaggy.Subcommand // Setup the variables you want your incoming flags to set. var testVar string // If you would like an environment variable as the default for a value, just populate the flag // with the value of the environment by default. If the flag corresponding to this value is not // used, then it will not be changed. var myVar = os.Getenv("MY_VAR") func init() { // Set your program's name and description. These appear in help output. flaggy.SetName("Test Program") flaggy.SetDescription("A little example program") // You can disable various things by changing bools on the default parser // (or your own parser if you have created one). flaggy.DefaultParser.ShowHelpOnUnexpected = false // You can set a help prepend or append on the default parser. flaggy.DefaultParser.AdditionalHelpPrepend = "http://github.com/integrii/flaggy" // Add a flag to the main program (this will be available in all subcommands as well). flaggy.String(&testVar, "tv", "testVariable", "A variable just for testing things!") // Create any subcommands and set their parameters. mySubcommand = flaggy.NewSubcommand("mySubcommand") mySubcommand.Description = "My great subcommand!" // Add a flag to the subcommand. mySubcommand.String(&myVar, "mv", "myVariable", "A variable just for me!") // Set the version and parse all inputs into variables. flaggy.SetVersion(version) flaggy.Parse() } func main(){ if mySubcommand.Used { ... } } ``` -------------------------------- ### Setup Zap Repository Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/go.uber.org/zap/CONTRIBUTING.md Clone the zap repository and set up the upstream remote for contributing. Ensure your GOPATH is correctly configured. ```bash mkdir -p $GOPATH/src/go.uber.org cd $GOPATH/src/go.uber.org git clone git@github.com:your_github_username/zap.git cd zap git remote add upstream https://github.com/uber-go/zap.git git fetch upstream ``` -------------------------------- ### Initialize Procfs and Get Stat Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/prometheus/procfs/README.md Initialize the proc filesystem mount point and read CPU statistics. Use this to get general system CPU metrics. ```go fs, err := procfs.NewFS("/proc") stats, err := fs.Stat() ``` -------------------------------- ### Example of Commented TOML Configuration Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/README.md Demonstrates how go-toml can generate TOML documents with comments and commented-out values, useful for configuration files. ```toml # Host IP to connect to. host = '127.0.0.1' # Port of the remote server. port = 4242 # Encryption parameters (optional) # [TLS] # cipher = 'AEAD-AES128-GCM-SHA256' # version = 'TLS 1.3' ``` -------------------------------- ### Install jsontoml CLI Tool Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/README.md Installs the jsontoml command-line tool. Use this to convert JSON files to TOML. ```bash $ go install github.com/pelletier/go-toml/v2/cmd/jsontoml@latest $ jsontoml --help ``` -------------------------------- ### Install Cobra CLI Generator Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/spf13/cobra/README.md Install the cobra-cli tool for generating Cobra application scaffolding. ```go go install github.com/spf13/cobra-cli@latest ``` -------------------------------- ### Coexisting with klog/v1 and klog/v2 Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/k8s.io/klog/v2/README.md Provides an example of how to manage the coexistence of both klog/v1 and klog/v2 within the same project. ```go // See examples/coexist_klog_v1_and_v2/ ``` -------------------------------- ### Install tomll CLI Tool Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/README.md Installs the tomll command-line tool. Use this to lint and reformat TOML files. ```bash $ go install github.com/pelletier/go-toml/v2/cmd/tomll@latest $ tomll --help ``` -------------------------------- ### Install tomljson CLI Tool Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/README.md Installs the tomljson command-line tool. Use this to convert TOML files to JSON. ```bash $ go install github.com/pelletier/go-toml/v2/cmd/tomljson@latest $ tomljson --help ``` -------------------------------- ### Install Specific golangci-lint Version Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/AGENTS.md Install a specific version of golangci-lint using a provided script. Ensure the version matches the one used in the CI configuration. ```bash # Install specific version (check lint.yml for current version) curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/HEAD/install.sh | sh -s -- -b $(go env GOPATH)/bin ``` -------------------------------- ### Import go-toml/v2 Library Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/README.md Import the go-toml/v2 library to start using its functionalities. ```go import "github.com/pelletier/go-toml/v2" ``` -------------------------------- ### Create Root Logger Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/go-logr/logr/README.md Initialize the root logger early in an application's lifecycle. This example shows creating a logger using a hypothetical 'logimpl' implementation with initial parameters. ```go func main() { // ... other setup code ... // Create the "root" logger. We have chosen the "logimpl" implementation, // which takes some initial parameters and returns a logr.Logger. logger := logimpl.New(param1, param2) // ... other setup code ... } ``` -------------------------------- ### Add or Update Dependencies Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/prometheus/procfs/CONTRIBUTING.md Use `go get` to fetch specific versions of external packages. Ensure your Go environment meets version requirements. ```bash # Pick the latest tagged release. go get example.com/some/module/pkg # Pick a specific version. go get example.com/some/module/pkg@vX.Y.Z ``` -------------------------------- ### Go Client Code Generation Configuration Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/aws/smithy-go/README.md Example smithy-build.json configuration for enabling the `go-codegen` plugin. Specifies the service, module, and Go version for client generation. ```json { "version": "1.0", "sources": [ "models" ], "maven": { "dependencies": [ "software.amazon.smithy.go:smithy-go-codegen:0.1.0" ] }, "plugins": { "go-codegen": { "service": "example.weather#Weather", "module": "github.com/example/weather", "generateGoMod": true, "goDirective": "1.24" } } } ``` -------------------------------- ### Example using TagSet and TagOptions Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/fxamacker/cbor/v2/README.md Shows how to create a TagSet, register custom types with specific CBOR tags, and then use these tags with DecMode and EncMode for unmarshalling and marshalling data. ```go // Use signedCWT struct defined in "Decoding CWT" example. // Create TagSet (safe for concurrency). tags := cbor.NewTagSet() // Register tag COSE_Sign1 18 with signedCWT type. tags.Add( cbor.TagOptions{EncTag: cbor.EncTagRequired, DecTag: cbor.DecTagRequired}, reflect.TypeOf(signedCWT{}), 18) // Create DecMode with immutable tags. dm, _ := cbor.DecOptions{}.DecModeWithTags(tags) // Unmarshal to signedCWT with tag support. var v signedCWT if err := dm.Unmarshal(data, &v); err != nil { return err } // Create EncMode with immutable tags. em, _ := cbor.EncOptions{}.EncModeWithTags(tags) // Marshal signedCWT with tag number. if data, err := em.Marshal(v); err != nil { return err } ``` -------------------------------- ### go-toml v1 Interface Decoding Example Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/README.md Demonstrates how go-toml v1 uses the existing type within an interface to decode TOML data. ```go package main import ( "fmt" "toml" ) type inner struct { B interface{} } type doc struct { A interface{} } func main() { d := doc{ A: inner{ B: "Before", }, } data := ` [A] B = "After" ` toml.Unmarshal([]byte(data), &d) fmt.Printf("toml v1: %#v\n", d) // toml v1: main.doc{A:main.inner{B:"After"}} } ``` -------------------------------- ### Development Panic Example Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/go.uber.org/zap/FAQ.md Use DPanic to catch errors that should not occur in development without crashing production. This example shows how to replace a panic with DPanic. ```go if err != nil { panic(fmt.Sprintf("shouldn't ever get here: %v", err)) } ``` -------------------------------- ### Zap Logger Quick Start Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/go.uber.org/zap/README.md Use the Logger when performance and type safety are critical. It is faster than SugaredLogger and allocates less, supporting only structured logging. ```go logger, _ := zap.NewProduction() deferr logger.Sync() logger.Info("failed to fetch URL", // Structured context as strongly typed Field values. zap.String("url", url), zap.Int("attempt", 3), zap.Duration("backoff", time.Second), ) ``` -------------------------------- ### Expected Go Module Dependency Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/antlr4-go/antlr/v4/README.md This example illustrates the expected and clearer versioning for the ANTLR4 runtime when retrieved from the dedicated Go runtime repository. ```go require ( github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.13.0 ) ``` -------------------------------- ### Build AMI with Specific Kubernetes Binaries Source: https://github.com/awslabs/amazon-eks-ami/blob/main/doc/usage/overview.md Build the AMI using specific Kubernetes version, build date, and architecture values. These parameters override defaults and specify which binaries to install. ```bash make k8s \ kubernetes_version=1.23.9 \ kubernetes_build_date=2022-07-27 \ arch=x86_64 ``` -------------------------------- ### EKS Cluster Configuration for Testing Source: https://github.com/awslabs/amazon-eks-ami/blob/main/doc/CONTRIBUTING.md Example `cluster.yaml` configuration file for creating an EKS cluster using `eksctl`. This is used to test if a newly built AMI can successfully join a cluster. ```yaml apiVersion: eksctl.io/v1alpha5 kind: ClusterConfig metadata: name: basic-cluster region: us-west-2 version: '1.22' nodeGroups: - name: ng instanceType: m5.large ami: [INSERT_AMI_ID] overrideBootstrapCommand: | #!/bin/bash /etc/eks/bootstrap.sh basic-cluster ``` -------------------------------- ### Basic Struct Merge Example Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/dario.cat/mergo/README.md Demonstrates a basic merge operation between two structs, showing how fields from the source struct populate zero-valued fields in the destination struct. ```go package main import ( "fmt" "dario.cat/mergo" ) type Foo struct { A string B int64 } func main() { src := Foo{ A: "one", B: 2, } dest := Foo{ A: "two", } mergo.Merge(&dest, src) fmt.Println(dest) // Will print // {two 2} } ``` -------------------------------- ### go-toml v2 Interface Decoding Example Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/README.md Illustrates how go-toml v2 disregards existing interface values and decodes into a map[string]interface{} to match encoding/json behavior. ```go package main import ( "fmt" "toml" ) type inner struct { B interface{} } type doc struct { A interface{} } func main() { d := doc{ A: inner{ B: "Before", }, } data := ` [A] B = "After" ` toml.Unmarshal([]byte(data), &d) fmt.Printf("toml v2: %#v\n", d) // toml v2: main.doc{A:map[string]interface {}{"B":"After"}} } ``` -------------------------------- ### Example of Contextualized DecodeError Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/README.md Illustrates a typical DecodeError message from go-toml, showing the line number, the problematic part of the TOML document, and the specific decoding issue. ```text 1| [server] 2| path = 100 | ~~~ cannot decode TOML integer into struct field toml_test.Server.Path of type string 3| port = 50 ``` -------------------------------- ### Zap SugaredLogger Quick Start Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/go.uber.org/zap/README.md Use SugaredLogger for contexts where performance is important but not critical. It supports both structured and printf-style APIs and is 4-10x faster than other structured logging packages. ```go logger, _ := zap.NewProduction() deferr logger.Sync() // flushes buffer, if any sugar := logger.Sugar() sugar.Infow("failed to fetch URL", // Structured context as loosely typed key-value pairs. "url", url, "attempt", 3, "backoff", time.Second, ) sugar.Infof("Failed to fetch URL: %s", url) ``` -------------------------------- ### go-toml v1 Array Bounds Error Example Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/README.md Shows how go-toml v1 returns an error when the TOML array length exceeds the destination array capacity. ```go package main import ( "fmt" "toml" ) type doc struct { A [2]string } func main() { d := doc{} err := toml.Unmarshal([]byte(`A = ["one", "two", "many"]`), &d) fmt.Println(err) // (1, 1): unmarshal: TOML array length (3) exceeds destination array length (2) } ``` -------------------------------- ### Serve mkdocs Site Locally Source: https://github.com/awslabs/amazon-eks-ami/blob/main/doc/development.md Run this command to serve the mkdocs generated documentation site locally for development and previewing. ```bash hack/mkdocs.sh serve ``` -------------------------------- ### Incorrect Go Module Dependency Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/antlr4-go/antlr/v4/README.md This example shows how `go get` might resolve ANTLR4 runtime versions when retrieved from the main ANTLR4 repository, leading to unclear versioning. ```go require ( github.com/antlr/antlr4/runtime/Go/antlr/v4 v4.0.0-20230219212500-1f9a474cc2dc ) ``` -------------------------------- ### Get Last Error Directly Example Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/avast/retry-go/v5/README.md Shows how to retrieve the last error directly from a `retry.Error` type, primarily for migration purposes from older versions of retry-go. It's generally recommended to use `errors.Is` or `errors.As` for error checking. ```go if retryErr, ok := err.(retry.Error); ok { lastErr := retryErr.LastError() } ``` -------------------------------- ### InstanceOptions Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/doc/api.md Determines how the node's operating system and devices are configured. ```APIDOC ## InstanceOptions ### Description InstanceOptions determines how the node's operating system and devices are configured. ### Fields - `localStorage` (LocalStorageOptions) - - `environment` (EnvironmentOptions) - - `network` (NetworkOptions) - ``` -------------------------------- ### InstanceOptions Source: https://github.com/awslabs/amazon-eks-ami/blob/main/doc/nodeadm/doc/api.md Determines how the node's operating system and devices are configured. ```APIDOC ## InstanceOptions InstanceOptions determines how the node's operating system and devices are configured. _Appears in:_ - [NodeConfigSpec](#nodeconfigspec) | Field | Description | | --- | --- | | `localStorage` _[LocalStorageOptions](#localstorageoptions)_ | | | `environment` _[EnvironmentOptions](#environmentoptions)_ | | | `network` _[NetworkOptions](#networkoptions)_ | | ``` -------------------------------- ### List Binaries for a Specific Build Date and Platform Source: https://github.com/awslabs/amazon-eks-ami/blob/main/doc/usage/overview.md List available binaries for a specific Kubernetes version, build date, and platform (e.g., linux) by querying the `amazon-eks` S3 bucket. ```bash # List platforms aws s3 ls s3://amazon-eks/1.23.9/2022-07-27/bin/ ``` -------------------------------- ### HTTP GET with Retry Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/avast/retry-go/v5/README.md Performs an HTTP GET request with a specified number of attempts and delay. Handles reading the response body and returns an error if all attempts fail. ```go url := "http://example.com" var body []byte err := retry.New( retry.Attempts(5), retry.Delay(100*time.Millisecond), ).Do( func() error { resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() body, err = ioutil.ReadAll(resp.Body) if err != nil { return err } return nil }, ) if err != nil { // handle error } fmt.Println(string(body)) ``` -------------------------------- ### Configure Pause Container Image Source: https://github.com/awslabs/amazon-eks-ami/blob/main/doc/usage/al2023.md Example of modifying the pause container image reference in containerd's config.toml. This example shows how to switch from an ECR image to a public Kubernetes image. ```diff -.dkr.ecr.." +.dkr.ecr-fips.." ``` -------------------------------- ### HTTP GET with Retry and Data Handling Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/avast/retry-go/v5/README.md Executes an HTTP GET request with retry logic and returns the response body as data. This is useful when the operation needs to return a value upon success. ```go url := "http://example.com" body, err := retry.DoWithData(retry.New(), func() ([]byte, error) { resp, err := http.Get(url) if err != nil { return nil, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } return body, nil }, ) if err != nil { // handle error } fmt.Println(string(body)) ``` -------------------------------- ### Initialize Block Device FS and Get Disk Stats Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/prometheus/procfs/README.md Initialize a filesystem object that requires access to both /proc and /sys, then retrieve block device statistics. Use this for detailed disk I/O metrics. ```go fs, err := blockdevice.NewFS("/proc", "/sys") stats, err := fs.ProcDiskstats() ``` -------------------------------- ### Update Objx Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/stretchr/objx/README.md Update the Objx package to the latest version using the go get -u command. ```bash go get -u github.com/stretchr/objx ``` -------------------------------- ### Troubleshooting `realpath: command not found` Source: https://github.com/awslabs/amazon-eks-ami/blob/main/doc/CONTRIBUTING.md When running `make test`, this error may occur. Installing `coreutils` on OSX can resolve this issue. ```bash test/test-harness.sh: line 41: realpath: command not found /entrypoint.sh: line 13: /test.sh: No such file or directory ``` -------------------------------- ### Logging to a Single File with klog Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/k8s.io/klog/v2/README.md Demonstrates how to configure klog to log to a single file using the 'log_file' flag, an alternative to 'log_dir'. ```go // See examples/log_file/usage_log_file.go ``` -------------------------------- ### Declare and Use Subcommand with Flag Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/integrii/flaggy/README.md Demonstrates how to declare a subcommand, add a string flag to it, and parse arguments. Use this when your application has distinct operational modes represented by subcommands. ```go var stringFlag = "defaultValue" subcommand := flaggy.NewSubcommand("subcommandExample") subcommand.String(&stringFlag, "f", "flag", "A test string flag") flaggy.AttachSubcommand(subcommand, 1) flaggy.Parse() print(stringFlag) ``` -------------------------------- ### Convert Between JSON and YAML Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/sigs.k8s.io/yaml/README.md Provides examples for converting JSON data to YAML using yaml.JSONToYAML and YAML data to JSON using yaml.YAMLToJSON. ```APIDOC ## Convert Between JSON and YAML ### Description This section demonstrates the utility functions `yaml.JSONToYAML` for converting JSON byte slices to YAML byte slices, and `yaml.YAMLToJSON` for converting YAML byte slices to JSON byte slices. ### Usage ```go package main import ( "fmt" "sigs.k8s.io/yaml" ) func main() { j := []byte(`{"name": "John", "age": 30}`) y, err := yaml.JSONToYAML(j) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(string(y)) /* Output: age: 30 name: John */ j2, err := yaml.YAMLToJSON(y) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(string(j2)) /* Output: {"age":30,"name":"John"} */ } ``` ``` -------------------------------- ### Coexisting with glog and klog Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/k8s.io/klog/v2/README.md Illustrates how to initialize and synchronize flags between glog and klog, and redirect output to stderr. ```go // See examples/coexist_glog/coexist_glog.go ``` -------------------------------- ### Get/Set Interface{} Value with reflect2 Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/modern-go/reflect2/README.md Demonstrates how to get and set values of an interface{}. Always use the pointer representation of the type for get/set operations. ```go valType := reflect2.TypeOf(1) i := 1 j := 10 valType.Set(&i, &j) // i will be 10 ``` -------------------------------- ### Create a New Feature Branch Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/go.uber.org/zap/CONTRIBUTING.md Start a new branch for your feature development. It's recommended to rebase on the latest upstream master before branching. ```bash cd $GOPATH/src/go.uber.org/zap git checkout master git fetch upstream git rebase upstream/master git checkout -b cool_new_feature ``` -------------------------------- ### Get Integer Value from FlagSet Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/spf13/pflag/README.md Retrieve the integer value of a flag from a pflag.FlagSet using GetInt(). This method requires the flag to exist and be of type int. ```go i, err := flagset.GetInt("flagname") ``` -------------------------------- ### Build AMI Using Custom Binary Bucket Source: https://github.com/awslabs/amazon-eks-ami/blob/main/doc/usage/overview.md Build the AMI using Kubernetes binaries from your own S3 bucket. Specify the bucket name, region, and the Kubernetes version/build date that corresponds to your binaries. ```bash make k8s \ binary_bucket_name=my-custom-bucket \ binary_bucket_region=eu-west-1 \ kubernetes_version=1.14.9 \ kubernetes_build_date=2020-01-22 ``` -------------------------------- ### Updating Mergo Locally Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/dario.cat/mergo/README.md To update your local copy of Mergo to the latest version, use the 'go get -u' command with the new vanity URL. ```go go get -u dario.cat/mergo ``` -------------------------------- ### Run Go Benchmarks Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/AGENTS.md Execute all benchmarks in the project multiple times to ensure consistent results. This is used to verify performance requirements and detect regressions. ```bash go test ./... -bench=. -count=10 ``` -------------------------------- ### Use tomljson via Docker Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/pelletier/go-toml/v2/README.md Runs the tomljson tool using a Docker container. This is useful for converting TOML to JSON without installing the tool locally. ```bash docker run -i ghcr.io/pelletier/go-toml:v2 tomljson < example.toml ``` -------------------------------- ### Basic Info Log Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/k8s.io/klog/v2/README.md Use glog.Info for standard informational messages. ```go glog.Info("Prepare to repel boarders") ``` -------------------------------- ### Setting Version at Build Time with Go Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/integrii/flaggy/README.md Builds an application and sets the version string using Go's linker flags. This is useful for embedding version information directly into the executable. ```bash # build your app and set the version string $ go build -ldflags='-X main.version=1.0.3-a3db3' $ ./yourApp version Version: 1.0.3-a3db3 $ ./yourApp --help Test Program - A little example program http://github.com/integrii/flaggy ``` -------------------------------- ### List Specific Binaries for an Architecture Source: https://github.com/awslabs/amazon-eks-ami/blob/main/doc/usage/overview.md List specific binaries available for a given Kubernetes version, build date, platform, and architecture by querying the `amazon-eks` S3 bucket. ```bash # List binaries aws s3 ls s3://amazon-eks/1.23.9/2022-07-27/bin/linux/x86_64/ ``` -------------------------------- ### Set Retry Context Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/avast/retry-go/v5/README.md Use the Context option to set a custom context for retry operations. This allows for cancellation or timeouts. Example shows immediate cancellation. ```go ctx, cancel := context.WithCancel(context.Background()) cancel() retry.New().Do( func() error { ... }, retry.Context(ctx), ) ``` -------------------------------- ### Build EKS-Optimized AMI with Packer Source: https://github.com/awslabs/amazon-eks-ami/blob/main/doc/README.md Initiate the AMI build process using the provided Makefile. Specify the desired Kubernetes version and operating system distribution. ```bash make k8s=1.29 os_distro=al2023 ``` ```bash make help ``` -------------------------------- ### Custom Transformer for time.Time Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/dario.cat/mergo/README.md Implement a custom transformer to merge time.Time structs. This example shows how to merge a non-zero time.Time value by checking if the destination is zero. ```go package main import ( "fmt" "dario.cat/mergo" "reflect" "time" ) type timeTransformer struct { } func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { if typ == reflect.TypeOf(time.Time{}) { return func(dst, src reflect.Value) error { if dst.CanSet() { isZero := dst.MethodByName("IsZero") result := isZero.Call([]reflect.Value{}) if result[0].Bool() { dst.Set(src) } } return nil } } return nil } type Snapshot struct { Time time.Time // ... } func main() { src := Snapshot{time.Now()} dest := Snapshot{} mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{})) fmt.Println(dest) // Will print // { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 } } ``` -------------------------------- ### Example Commit Message Source: https://github.com/awslabs/amazon-eks-ami/blob/main/nodeadm/vendor/github.com/godbus/dbus/v5/CONTRIBUTING.md Follow this format for commit messages to clearly indicate what changed and why. The subject line should be concise, followed by a blank line, and then a more detailed explanation. ```git scripts: add the test-cluster command this uses tmux to setup a test cluster that you can easily kill and start for debugging. Fixes #38 ```