Skip to content

Instantly share code, notes, and snippets.

@tuannvm
Last active June 30, 2025 23:58
Show Gist options
  • Save tuannvm/4e1bcc993f683ee275ed36e67c30ac49 to your computer and use it in GitHub Desktop.
Save tuannvm/4e1bcc993f683ee275ed36e67c30ac49 to your computer and use it in GitHub Desktop.

Revisions

  1. tuannvm revised this gist Apr 12, 2025. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion argo.md
    Original file line number Diff line number Diff line change
    @@ -48,7 +48,7 @@
    ## Installation & Setup

    - **Installation:**
    ```bash
    ```shell
    # Install ArgoCD into the argocd namespace
    kubectl create namespace argocd
    kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
  2. tuannvm revised this gist Apr 12, 2025. 2 changed files with 209 additions and 10 deletions.
    209 changes: 209 additions & 0 deletions argo.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,209 @@
    # ArgoCD CheatSheet

    - [ArgoCD CheatSheet](#argocd-cheatsheet)
    - [Overview](#overview)
    - [Architecture & Components](#architecture--components)
    - [Getting Started](#getting-started)
    - [Installation & Setup](#installation--setup)
    - [ArgoCD CLI Commands](#argocd-cli-commands)
    - [Application Management](#application-management)
    - [Defining an Application](#defining-an-application)
    - [Sync Policies & Strategies](#sync-policies--strategies)
    - [Rollback & Diff](#rollback--diff)
    - [Project & RBAC](#project--rbac)
    - [Monitoring & Troubleshooting](#monitoring--troubleshooting)
    - [Advanced Usage & New Features](#advanced-usage--new-features)

    ---

    ## Overview

    - **ArgoCD** is a declarative, GitOps continuous delivery tool for Kubernetes.
    - It continuously monitors Git repositories and automatically applies desired state configurations to clusters.
    - Supports multi-cluster deployments, application rollback, and advanced sync strategies.

    ---

    ## Architecture & Components

    - **API Server:** Hosts the ArgoCD API and UI.
    - **Repository Server:** Clones and tracks Git repositories for application manifests.
    - **Application Controller:** Reconciles declared application state against live clusters.
    - **Dex (optional):** Provides authentication integrations (OIDC, LDAP).
    - **Redis:** Used for caching and managing ArgoCD sessions.
    - **CLI:** A command-line tool to interact with ArgoCD and automate deployment operations.

    *Each component operates together to maintain cluster state according to the GitOps model.*

    ---

    ## Getting Started

    - Familiarize with the ArgoCD GitOps fundamentals to manage Kubernetes deployments.
    - Learn the declarative application model and integration with Git repositories.
    - Use the web UI or CLI to monitor application states, view diffs, and trigger syncs.

    ---

    ## Installation & Setup

    - **Installation:**
    ```bash
    # Install ArgoCD into the argocd namespace
    kubectl create namespace argocd
    kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
    ```
    - **Port Forwarding for Access:**
    ```bash
    kubectl port-forward svc/argocd-server -n argocd 8080:443
    ```
    - **CLI Installation:**
    Download the latest ArgoCD CLI from the [official releases page](https://github.com/argoproj/argo-cd/releases) and add it to your PATH.

    *New versions up to 2025 have streamlined integration with OCI registries, enhanced authentication, and improved RBAC policies.*

    ---

    ## ArgoCD CLI Commands

    Basic commands using the `argocd` CLI:

    ```bash
    # Login to the ArgoCD API server
    argocd login <ARGOCD-SERVER>:<PORT> --username admin --password <password>

    # List all applications
    argocd app list

    # Get detailed information on an application
    argocd app get <app-name>

    # Create a new application from a Git repository
    argocd app create <app-name> \
    --repo https://github.com/your-org/your-repo.git \
    --path <path-to-manifests> \
    --dest-server https://kubernetes.default.svc \
    --dest-namespace <target-namespace>

    # Sync an application to update the live state
    argocd app sync <app-name>

    # View differences between the desired and live state
    argocd app diff <app-name>

    # Rollback an application to a previous revision
    argocd app rollback <app-name> <revision-number>

    # Delete an application (controller will remove the resources)
    argocd app delete <app-name>

    # Refresh to re-fetch Git repo data
    argocd app refresh <app-name>
    ```

    *These commands are available in the latest CLI versions and provide a consistent experience even as new features are added.*

    ---

    ## Application Management

    ### Defining an Application

    An ArgoCD application is declared as a Kubernetes custom resource. A common example:

    ```yaml
    apiVersion: argoproj.io/v1alpha1
    kind: Application
    metadata:
    name: my-app
    namespace: argocd
    spec:
    project: default
    source:
    repoURL: 'https://github.com/your-org/your-repo.git'
    targetRevision: HEAD
    path: overlays/production
    destination:
    server: 'https://kubernetes.default.svc'
    namespace: my-app-namespace
    syncPolicy:
    automated:
    prune: true
    selfHeal: true
    ```
    *This declarative file drives GitOps workflows and supports advanced strategies available up to the most current releases.*
    ### Sync Policies & Strategies
    - **Manual Sync:**
    • Default mode where a user triggers sync via CLI or UI.
    - **Automated Sync:**
    • Automatically applies new changes from Git.
    • Options include:
    - **Prune:** Automatically remove resources that are no longer in Git.
    - **SelfHeal:** Re-sync out-of-compliance resources automatically.
    - **Sync Waves and Hooks:**
    • Define pre-sync, post-sync, sync hooks using annotations such as:
    ```yaml
    metadata:
    annotations:
    argocd.argoproj.io/hook: PreSync
    ```
    • Ensure reliable ordering and execution during application update.
    ### Rollback & Diff
    - **Rollback:**
    • Roll back to a prior successful revision using the CLI or UI.
    • Useful for quickly recovering from a bad deployment.
    - **Diff:**
    • See the changes between the live state and Git state with the `argocd app diff` command.
    • Helps identify configuration drift and troubleshoot sync issues.

    ---

    ## Project & RBAC

    - **Projects:**
    • Group applications under ArgoCD projects for isolation and centralized policy management.
    - **RBAC:**
    • Define fine-grained access rules for users and teams in the ArgoCD configuration.
    • Use ConfigMaps for RBAC policies, allowing controlled access to specific applications, projects, or actions.

    *Newer versions further enhance multi-tenant support and integration with enterprise identity providers.*

    ---

    ## Monitoring & Troubleshooting

    - **UI Dashboard:**
    • Use the ArgoCD web UI to observe application statuses, view diff details, and check logs.
    - **CLI Status & Logs:**
    ```bash
    argocd app get <app-name> # Displays detailed health and sync status
    kubectl logs -n argocd deployment/argocd-application-controller
    ```
    - **Audit & Notifications:**
    • Configure external notifications (e.g., Slack, email) to be alerted on sync failures or policy violations.
    - **Observability:**
    • Integration with Prometheus and Grafana for performance monitoring.

    *With improvements in observability and notification features, troubleshooting is more efficient and proactive in current releases.*

    ---

    ## Advanced Usage & New Features

    - **ApplicationSets:**
    • Dynamically generate multiple ArgoCD applications from a single template, suited for multi-cluster or multi-environment deployments.
    - **Declarative Config Management:**
    • Use Git and YAML to control not only individual applications but also global configuration for ArgoCD.
    - **Enhanced OCI Support:**
    • Deploy applications backed by OCI artifacts directly.
    - **Improved Security:**
    • Enhanced authentication via OIDC and integration with external secrets management.
    - **Custom Resource Definitions:**
    • Leverage extended CRD capabilities to fine-tune application behavior according to custom policies.

    *These advanced features, available up to the latest release, continue to strengthen ArgoCD’s role as a central tool in GitOps continuous delivery.*
    10 changes: 0 additions & 10 deletions tools.md
    Original file line number Diff line number Diff line change
    @@ -1,10 +0,0 @@
    ## Helm

    - helm chart unit test https://github.com/xchapter7x/hcunit?utm_sq=g92df5t58c

    ## Container

    - container test: https://github.com/GoogleContainerTools/container-structure-test

    ## AWS
    - SSO login: https://github.com/wnkz/aws-sso/blob/master/README.md
  3. tuannvm revised this gist Apr 12, 2025. 3 changed files with 486 additions and 498 deletions.
    498 changes: 0 additions & 498 deletions helm-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -1,498 +0,0 @@
    # Helm CheatSheet

    - [Helm CheatSheet](#helm-cheatsheet)
    - [Get Started](#get-started)
    - [Struture](#struture)
    - [General Usage](#general-usage)
    - [Template](#template)
    - [Hooks](#hooks)
    - [Chart Repository](#chart-repository)
    - [Signing](#signing)
    - [Test](#test)
    - [Flow Control](#flow-control)
    - [If/Else](#ifelse)
    - [With](#with)
    - [Range](#range)
    - [Variables](#variables)
    - [Named Templates](#named-templates)
    - [Files inside Templates](#files-inside-templates)
    - [Glob-patterns & encoding](#glob-patterns--encoding)
    - [YAML reference](#yaml-reference)

    ## Get Started

    - https://deis.com/blog/2016/getting-started-authoring-helm-charts/
    - https://docs.bitnami.com/kubernetes/how-to/
    - https://github.com/kubernetes/helm/blob/master/docs/charts.md
    - https://docs.helm.sh/chart-template-guide/
    - http://helm.readthedocs.io/en/latest/architecture/

    ---

    ## Struture

    ```bash
    .
    ├── Chart.yaml --> metadata info
    ├── README.md
    ├── requirements.yaml --> define dependencies
    ├── templates
    │ ├── spark-master-deployment.yaml --> configuration with template supported
    │ ├── spark-worker-deployment.yaml
    │ └── spark-zeppelin-deployment.yaml
    │ └── NOTES.txt --> display when run "helm chart"
    │ └── _helpers.tpl --> template handler
    └── values.yaml --> variable list, will be interpolated on templates file during deployment
    └── charts
    ├── apache/
    ├── Chart.yaml
    ```

    - Chart.yaml

    ```yaml
    name: The name of the chart (required)
    version: A SemVer 2 version (required)
    description: A single-sentence description of this project (optional)
    keywords:
    - A list of keywords about this project (optional)
    home: The URL of this project's home page (optional)
    sources:
    - A list of URLs to source code for this project (optional)
    maintainers: # (optional)
    - name: The maintainer's name (required for each maintainer)
    email: The maintainer's email (optional for each maintainer)
    engine: gotpl # The name of the template engine (optional, defaults to gotpl)
    icon: A URL to an SVG or PNG image to be used as an icon (optional).
    appVersion: The version of the app that this contains (optional). This needn't be SemVer.
    deprecated: Whether or not this chart is deprecated (optional, boolean)
    tillerVersion: The version of Tiller that this chart requires. This should be expressed as a SemVer range: ">2.0.0" (optional)
    ```
    - **requirements.yaml**
    > Adding an `alias` for a dependency chart would put a chart in dependencies using alias as name of new dependency.
    > `Condition` - The condition field holds one or more YAML paths (delimited by commas). If this path exists in the top parent's values and resolves to a boolean value, the chart will be enabled or disabled based on that boolean value. Only the first valid path found in the list is evaluated and if no paths exist then the condition has no effect.
    > `Tags` - The tags field is a YAML list of labels to associate with this chart. In the top parent's values, all charts with tags can be enabled or disabled by specifying the tag and a boolean value.
    > `Conditions` (when set in values) always override `tags`

    ```yaml
    dependencies:
    - name: apache
    version: 1.2.3
    repository: http://example.com/charts
    alias: new-subchart-1
    condition: subchart1.enabled, global.subchart1.enabled
    tags:
    - front-end
    - subchart1
    - name: mysql
    version: 3.2.1
    repository: http://another.example.com/charts
    alias: new-subchart-2
    condition: subchart2.enabled,global.subchart2.enabled
    tags:
    - back-end
    - subchart1
    ```

    ## General Usage

    ```bash
    helm list --all
    helm repo (list|add|update)
    helm search
    helm inspect <chart-name>
    hem install --set a=b -f config.yaml <chart-name> -n <release-name> # --set take precedented, merge into -f
    helm status <deployment-name>
    helm delete <deployment-name>
    helm inspect values <chart-name>
    helm upgrade -f config.yaml <deployment-name> <chart-name>
    helm rollback <deployment-name> <version>
    helm create <chart-name>
    helm package <chart-name>
    helm lint <chart-name>
    helm dep up <chart-name> # update dependency
    helm get manifest <deployment-name> # prints out all of the Kubernetes resources that were uploaded to the server
    helm install --debug --dry-run <deployment-name> # it will return the rendered template to you so you can see the output
    ```

    - --set outer.inner=value is translated into this:

    ```yaml
    outer:
    inner: value
    ```

    - --set servers[0].port=80,servers[0].host=example:

    ```yaml
    servers:
    - port: 80
    host: example
    ```

    - --set name={a, b, c} translates to:

    ```yaml
    name:
    - a
    - b
    - c
    ```

    - --set name=value1\,value2:

    ```yaml
    name: "value1,value2"
    ```

    - --set nodeSelector."kubernetes\.io/role"=master

    ```yaml
    nodeSelector:
    kubernetes.io/role: master
    ```

    - --set livenessProbe.exec.command=[cat,docroot/CHANGELOG.txt] --set livenessProbe.httpGet=null

    ```diff
    livenessProbe:
    - httpGet:
    - path: /user/login
    - port: http
    initialDelaySeconds: 120
    + exec:
    + command:
    + - cat
    + - docroot/CHANGELOG.txt
    ```

    - --timeout
    - --wait
    - --no-hooks
    - --recreate-pods

    ## Template

    > Values that are supplied via a `values.yaml` file (or via the --set flag) are accessible from the `.Values` object in a template

    ```yaml
    Release.Name:
    Release.Time:
    Release.Namespace: The namespace the chart was released to.
    Release.Service: The service that conducted the release. Usually this is Tiller.
    Release.IsUpgrade: This is set to true if the current operation is an upgrade or rollback.
    Release.IsInstall: This is set to true if the current operation is an install.
    Release.Revision: The revision number. It begins at 1, and increments with each helm upgrade.
    Chart: The contents of the Chart.yaml. Thus, the chart version is obtainable as "Chart.Version" and the maintainers are in "Chart.Maintainers".
    Files: Files can be accessed using {{index .Files "file.name"}} or using the "{{.Files.Get name}}" or "{{.Files.GetString name}}" functions. You can also access the contents of the file as []byte using "{{.Files.GetBytes}}"
    Capabilities: "({{.Capabilities.KubeVersion}}", Tiller "({{.Capabilities.TillerVersion}}", and the supported Kubernetes API versions "({{.Capabilities.APIVersions.Has "batch/v1")"
    {{.Files.Get config.ini}}
    {{.Files.GetBytes}} useful for things like images
    {{.Template.Name}}
    {{.Template.BasePath}}
    ```

    - default value

    ```go
    {{default "minio" .Values.storage}}
    //same
    {{ .Values.storage | default "minio" }}
    ```

    - put a quote outside

    ```yaml
    heritage: {{.Release.Service | quote }}
    # same result
    heritage: {{ quote .Release.Service }}
    ```

    - global variable

    ```yaml
    global:
    app: MyWordPress
    // could be access as "{{.Values.global.app}}"
    ```

    - Includes a template called `mytpl.tpl`, then `lowercases` the result, then wraps that in `double quotes`

    ```yaml
    value: {{include "mytpl.tpl" . | lower | quote}}
    ```

    - `required` function declares an entry for `.Values.who` is required, and will print an `error message` when that entry is missing

    ```yaml
    value: {{required "A valid .Values.who entry required!" .Values.who }}
    ```

    - The `sha256sum` function can be used together with the `include` function to ensure a deployments template section is updated if another spec changes

    ```yaml
    kind: Deployment
    spec:
    template:
    metadata:
    annotations:
    checksum/config: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
    [...]
    ```

    - The annotation `"helm.sh/resource-policy":` keep instructs `Tiller` to skip this resource during a helm `delete` operation

    - In the `templates/` directory, any file that begins with an `underscore(_)` is `not` expected to output a Kubernetes manifest file. So by convention, `helper templates` and `partials` are placed in a `_helpers.tpl` file.

    ## Hooks

    Read [more](https://github.com/kubernetes/helm/blob/master/docs/charts_hooks.md)

    - include these annotation inside hook yaml file, for e.g `templates/post-install-job.yaml`

    ```yaml
    apiVersion: batch/v1
    kind: Job
    metadata:
    annotations:
    # This is what defines this resource as a hook. Without this line, the
    # job is considered part of the release.
    "helm.sh/hook": post-install, post-upgrade
    "helm.sh/hook-weight": "-5"
    ```

    ## Chart Repository

    Read [more](https://github.com/kubernetes/helm/blob/master/docs/chart_repository.md#the-index-file)

    ## Signing

    Read [more](https://github.com/kubernetes/helm/blob/master/docs/provenance.md)

    ## Test

    Read [more](https://github.com/kubernetes/helm/blob/master/docs/chart_tests.md)

    ## Flow Control

    ---

    ### If/Else

    ```yaml
    {{ if PIPELINE }}
    # Do something
    {{ else if OTHER PIPELINE }}
    # Do something else
    {{ else }}
    # Default case
    {{ end }}
    data:
    myvalue: "Hello World"
    drink: {{ .Values.favorite.drink | default "tea" | quote }}
    food: {{ .Values.favorite.food | upper | quote }}
    {{- if eq .Values.favorite.drink "lemonade" }}
    mug: true
    {{- end }} # notice the "-" in the left, if will help eliminate newline before variable
    ```

    ### With

    > `with` can allow you to set the current `scope` (.) to a particular object

    ```yaml
    data:
    myvalue: "Hello World"
    {{- with .Values.favorite }}
    drink: {{ .drink | default "tea" | quote }}
    food: {{ .food | upper | quote }}
    {{- end }} # instead of writing ".Values.favorite.drink"
    ```

    > `Inside` of the `restricted scope`, you will `not` be able to access the other objects from the `parent scope`

    ### Range

    ```yaml
    # predefined variable
    pizzaToppings:
    - mushrooms
    - cheese
    - peppers
    - onions
    toppings: |-
    {{- range $i, $val := .Values.pizzaTopping }}
    - {{ . | title | quote }} # upper first character, then quote
    {{- end }}
    sizes: |-
    {{- range tuple "small" "medium" "large" }}
    - {{ . }}
    {{- end }} # make a quick list
    ```

    ### Variables

    > It follows the form `$name`. Variables are assigned with a special assignment operator: `:=`

    ```yaml
    data:
    myvalue: "Hello World"
    {{- $relname := .Release.Name -}}
    {{- with .Values.favorite }}
    drink: {{ .drink | default "tea" | quote }}
    food: {{ .food | upper | quote }}
    release: {{ $relname }}
    {{- end }}
    # use variable in range
    toppings: |-
    {{- range $index, $topping := .Values.pizzaToppings }}
    {{ $index }}: {{ $topping }}
    {{- end }}
    #toppings: |-
    # 0: mushrooms
    # 1: cheese
    # 2: peppers
    # 3: onions
    {{- range $key,$value := .Values.favorite }}
    {{ $key }}: {{ $value }}
    {{- end }} # instead of specify the key, we can actually loop through the values.yaml file and print values
    ```

    > There is one variable that is always global - $ - this variable will always point to the root context

    ```yaml
    ...
    labels:
    # Many helm templates would use `.` below, but that will not work,
    # however `$` will work here
    app: {{ template "fullname" $ }}
    # I cannot reference .Chart.Name, but I can do $.Chart.Name
    chart: "{{ $.Chart.Name }}-{{ $.Chart.Version }}"
    release: "{{ $.Release.Name }}"
    heritage: "{{ $.Release.Service }}"
    ...
    ```

    ### Named Templates

    > template names are **`global`**
    ```yaml
    # _helpers.tpl
    {{/* Generate basic labels */}}
    {{- define "my_labels" }}
    labels:
    generator: helm
    date: {{ now | htmlDate }}
    version: {{ .Chart.Version }}
    name: {{ .Chart.Name }}
    {{- end }}
    ```

    > When a named template (created with define) is rendered, it will receive the scope passed in by the template call.
    ```yaml
    # configmap.yaml
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: {{ .Release.Name }}-configmap
    {{- template "my_labels" . }} # Notice the final dot, it will pass the global scope inside template file. Without it version & name will not be generated.
    {{- include "my_labels" . | indent 2 }} # similar to "template" directive, have the ability to control indentation
    ```

    > referable to use `include` over `template`. Because `template` is an `action`, and not a `function`, there is no way to pass the output of a template call to other functions; the data is simply inserted `inline`.
    ### Files inside Templates

    ```yaml
    # file located at parent folder
    # config1.toml: |-
    # message = config 1 here
    # config2.toml: |-
    # message = config 2 here
    # config3.toml: |-
    # message = config 3 here

    data:
    {{- $file := .Files }} # set variable
    {{- range tuple "config1.toml" "config2.toml" "config3.toml" }} # create list
    {{ . }}: |- # config file name
    {{ $file.Get . }} # get file's content
    {{- end }}
    ```

    ### Glob-patterns & encoding

    ```diff
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: conf
    data:
    +{{ (.Files.Glob "foo/*").AsConfig | indent 2 }}
    ---
    apiVersion: v1
    kind: Secret
    metadata:
    name: very-secret
    type: Opaque
    data:
    +{{ (.Files.Glob "bar/*").AsSecrets | indent 2 }}

    +token: |-
    + {{ .Files.Get "config1.toml" | b64enc }}
    ```

    ## YAML reference

    ```yaml
    # Force type
    age: !!str 21
    port: !!int "80"

    # Fake first line to preserve integrity
    coffee: | # no strip
    # Commented first line
    Latte
    Cappuccino
    Espresso
    coffee: |- # strip off trailing newline
    Latte
    Cappuccino
    Espresso
    coffee: |+ # preserve trailing newline
    Latte
    Cappuccino
    Espresso
    another: value

    myfile: | # insert static file
    {{ .Files.Get "myfile.txt" | indent 2 }}

    coffee: > # treat as one long line
    Latte
    Cappuccino
    Espresso
    ```
    486 changes: 486 additions & 0 deletions helm.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,486 @@
    # Helm CheatSheet

    - [Helm CheatSheet](#helm-cheatsheet)
    - [Get Started](#get-started)
    - [Struture](#struture)
    - [General Usage](#general-usage)
    - [Template](#template)
    - [Hooks](#hooks)
    - [Chart Repository](#chart-repository)
    - [Signing](#signing)
    - [Test](#test)
    - [Flow Control](#flow-control)
    - [If/Else](#ifelse)
    - [With](#with)
    - [Range](#range)
    - [Variables](#variables)
    - [Named Templates](#named-templates)
    - [Files inside Templates](#files-inside-templates)
    - [Glob-patterns & Encoding](#glob-patterns--encoding)
    - [YAML Reference](#yaml-reference)
    - [New Features and Enhancements (up to v3.17.3)](#new-features-and-enhancements-up-to-v3173)

    ---

    ## Get Started

    - Useful introductory materials:
    - [Getting Started Authoring Helm Charts](https://deis.com/blog/2016/getting-started-authoring-helm-charts/)
    - [Bitnami Kubernetes How-To](https://docs.bitnami.com/kubernetes/how-to/)
    - [Helm Chart Template Guide](https://docs.helm.sh/chart-template-guide/)
    - [Helm Architecture Documentation](http://helm.readthedocs.io/en/latest/architecture/)

    *Helm v3 removed Tiller, improved security, and introduced native OCI registry support. These changes simplify chart management and enhance release practices.*

    ---

    ## Struture

    ```bash
    .
    ├── Chart.yaml # Metadata info
    ├── README.md
    ├── requirements.yaml # For defining dependencies (now largely replaced by Chart.yaml 'dependencies')
    ├── templates # Contains Kubernetes manifests with templating support
    │ ├── spark-master-deployment.yaml
    │ ├── spark-worker-deployment.yaml
    │ ├── spark-zeppelin-deployment.yaml
    │ ├── NOTES.txt # Displayed after helm install
    │ └── _helpers.tpl # Helper templates / partials
    ├── values.yaml # Variables used during template rendering
    └── charts # Directory for dependent charts
    └── apache/
    └── Chart.yaml
    ```

    - **Chart.yaml**

    ```yaml
    name: <chart-name> # Required chart name
    version: <semver-2-version> # Follows SemVer 2; required
    description: A one-sentence description (optional)
    keywords:
    - helm
    - chart
    home: https://example.com # Homepage URL (optional)
    sources:
    - https://example.com/source # Source code URLs (optional)
    maintainers: # One or more maintainers for the chart
    - name: "Your Name" # Required for each maintainer
    email: [email protected] # Optional for each maintainer
    engine: gotpl # Template engine (defaults to gotpl)
    icon: https://example.com/icon.png # Icon URL, preferably SVG or PNG
    appVersion: "1.2.3" # Version of the application contained in the chart (optional)
    deprecated: false # Mark chart as deprecated (boolean)
    tillerVersion: ">2.0.0" # REQUIRED only in legacy contexts; not needed in Helm v3+
    ```
    - **requirements.yaml (deprecated in favor of `dependencies` key in Chart.yaml)**

    Use the following syntax for adding dependencies, including alias and conditions:

    ```yaml
    dependencies:
    - name: apache
    version: 1.2.3
    repository: "http://example.com/charts"
    alias: new-subchart-1
    condition: subchart1.enabled,global.subchart1.enabled
    tags:
    - front-end
    - subchart1
    - name: mysql
    version: 3.2.1
    repository: "http://another.example.com/charts"
    alias: new-subchart-2
    condition: subchart2.enabled,global.subchart2.enabled
    tags:
    - back-end
    ```

    *Recent Helm versions (v3.17.3 included) consolidate dependency management into Chart.yaml’s "dependencies" key, simplifying chart packaging and updates.*

    ---

    ## General Usage

    ```bash
    helm list --all
    helm repo (list|add|update)
    helm search <chart-name>
    helm inspect <chart-name>
    helm install --set a=b -f config.yaml <chart-name> -n <release-name>
    helm status <release-name>
    helm delete <release-name>
    helm inspect values <chart-name>
    helm upgrade -f config.yaml <release-name> <chart-name>
    helm rollback <release-name> <revision>
    helm create <chart-name>
    helm package <chart-name>
    helm lint <chart-name>
    helm dep update <chart-name> # Updates chart dependencies
    helm get manifest <release-name> # Prints all Kubernetes resources rendered for the release
    helm install --debug --dry-run <release-name> <chart-name>
    ```

    *Notes on value substitution:*

    - `--set outer.inner=value` translates to:

    ```yaml
    outer:
    inner: value
    ```

    - `--set servers[0].port=80,servers[0].host=example` becomes:

    ```yaml
    servers:
    - port: 80
    host: example
    ```

    - List creation with `--set name={a,b,c}` produces:

    ```yaml
    name:
    - a
    - b
    - c
    ```

    - Escaping commas (e.g., `--set name=value1\,value2`) preserves commas in strings.

    - Dot notation in keys, for example using `--set nodeSelector."kubernetes\.io/role"=master`, produces:

    ```yaml
    nodeSelector:
    kubernetes.io/role: master
    ```

    ---

    ## Template

    Values defined in your `values.yaml` or via the `--set` flag are available in templates through the `.Values` object. Helm also exposes useful built-in objects such as:

    - **Release:**
    • `.Release.Name`, `.Release.Time`, `.Release.Namespace`, `.Release.IsUpgrade`, `.Release.Revision`
    - **Chart:**
    • `.Chart.Name`, `.Chart.Version`, `.Chart.Maintainers`
    - **Files:**
    • Access static files via `{{ .Files.Get "file.name" }}` or `{{ .Files.GetString "file.name" }}`
    - **Capabilities:**
    • For example, check supported Kubernetes API versions using `.Capabilities.APIVersions.Has`

    Other useful functions include:
    - `default` for providing fallback values:
    ```go
    {{ default "minio" .Values.storage }}
    ```
    - `quote` to wrap strings in quotes:
    ```yaml
    heritage: {{ .Release.Service | quote }}
    ```

    - Using **include** to call named templates and then manipulate their output:

    ```yaml
    value: {{ include "mytpl.tpl" . | lower | quote }}
    ```

    - The `required` function to print an error if a needed value is missing:

    ```yaml
    value: {{ required "A valid .Values.who entry is required!" .Values.who }}
    ```

    - Generating a checksum on an included file to trigger rolling updates, for example:

    ```yaml
    annotations:
    checksum/config: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
    ```

    *The annotation `"helm.sh/resource-policy": keep` instructs Helm to skip a resource during deletion, ensuring persistent resources are not accidentally removed.*

    Files in the `templates/` directory that begin with an underscore (such as `_helpers.tpl`) are treated as helper files and are not rendered as full Kubernetes manifests.

    ---

    ## Hooks

    Hooks let you execute resources at specific phases in a release lifecycle. They are defined by annotations in the manifest files.

    For example, a hook job defined with post-install and post-upgrade phases:

    ```yaml
    apiVersion: batch/v1
    kind: Job
    metadata:
    annotations:
    "helm.sh/hook": post-install,post-upgrade
    "helm.sh/hook-weight": "-5" # Defines the order in which hooks are executed
    spec:
    template:
    spec:
    restartPolicy: Never
    containers:
    - name: hook
    image: busybox
    command: ["echo", "This is a hook!"]
    ```

    *Recent improvements in Helm v3 allow hooks to integrate better with release lifecycles and help with automated testing and pre-/post-upgrade validations.*

    ---

    ## Chart Repository

    - Helm supports chart repositories with an index file that describes available charts.
    - Use commands such as `helm repo add`, `helm repo update`, and `helm search repo` to manage and find charts.

    For more details refer to the [chart repository documentation](https://github.com/kubernetes/helm/blob/master/docs/chart_repository.md#the-index-file).

    ---

    ## Signing

    Chart signing helps verify the integrity and provenance of a chart.

    - Use `helm package --sign <chart-name>` to sign a chart.
    - Helm v3 improves signing workflows and integrates with provenance files.
    - For more details, see the [Helm provenance documentation](https://github.com/kubernetes/helm/blob/master/docs/provenance.md).

    ---

    ## Test

    Helm provides a mechanism to run tests on deployed charts. Test hooks are defined as Kubernetes test Pods which are executed after a release is installed or upgraded.

    - Define test hooks by adding the `helm.sh/hook: test-success` annotation.
    - Run tests with `helm test <release-name>`.

    For further details, see [chart tests documentation](https://github.com/kubernetes/helm/blob/master/docs/chart_tests.md).

    ---

    ## Flow Control

    ### If/Else

    ```yaml
    {{ if .Values.someCondition }}
    # Execute this if .Values.someCondition is true
    {{ else if .Values.otherCondition }}
    # Else if condition
    {{ else }}
    # Default case
    {{ end }}
    data:
    drink: {{ .Values.favorite.drink | default "tea" | quote }}
    food: {{ .Values.favorite.food | upper | quote }}
    {{- if eq .Values.favorite.drink "lemonade" }}
    mug: true
    {{- end }}
    ```

    ---

    ### With

    `with` changes the current scope to an object:

    ```yaml
    data:
    {{- with .Values.favorite }}
    drink: {{ .drink | default "tea" | quote }}
    food: {{ .food | upper | quote }}
    {{- end }}
    ```

    *Inside the restricted scope, access to objects outside the scope is not available unless using the global variable `$`.*

    ---

    ### Range

    ```yaml
    # Sample from values.yaml:
    # pizzaToppings:
    # - mushrooms
    # - cheese
    # - peppers
    # - onions
    toppings: |-
    {{- range $i, $val := .Values.pizzaToppings }}
    - {{ $val | title | quote }}
    {{- end }}
    # Using a quick tuple to list sizes
    sizes: |-
    {{- range tuple "small" "medium" "large" }}
    - {{ . }}
    {{- end }}
    ```

    ---

    ### Variables

    Variables are defined with the `:=` operator and referenced with `$`.

    ```yaml
    data:
    myvalue: "Hello World"
    {{- $relname := .Release.Name -}}
    {{- with .Values.favorite }}
    drink: {{ .drink | default "tea" | quote }}
    food: {{ .food | upper | quote }}
    release: {{ $relname }}
    {{- end }}
    # In a range loop:
    toppings: |-
    {{- range $index, $topping := .Values.pizzaToppings }}
    {{ $index }}: {{ $topping }}
    {{- end }}
    # Global scope variable:
    labels:
    app: {{ template "fullname" $ }}
    release: "{{ $.Release.Name }}"
    chart: "{{ $.Chart.Name }}-{{ $.Chart.Version }}"
    ```

    ---

    ### Named Templates

    Define reusable snippets in your helper files (e.g. `_helpers.tpl`):

    ```yaml
    {{/* _helpers.tpl */}}
    {{- define "my_labels" -}}
    labels:
    generator: helm
    date: {{ now | htmlDate }}
    version: {{ .Chart.Version }}
    name: {{ .Chart.Name }}
    {{- end -}}
    ```

    Call a named template inside another manifest:

    ```yaml
    # configmap.yaml
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: {{ .Release.Name }}-configmap
    {{- include "my_labels" . | indent 2 }}
    ```

    *Use `include` rather than `template` when you need to pass the output to other functions.*

    ---

    ### Files inside Templates

    Access chart files in templates with `.Files`:

    ```yaml
    data:
    {{- $files := .Files }}
    {{- range tuple "config1.toml" "config2.toml" "config3.toml" }}
    {{ . }}: |-
    {{ $files.Get . }}
    {{- end }}
    ```

    ---

    ### Glob-patterns & Encoding

    Using the Glob functionality, you can load multiple files with a pattern:

    ```yaml
    apiVersion: v1
    kind: ConfigMap
    metadata:
    name: conf
    data:
    {{ (.Files.Glob "foo/*").AsConfig | indent 2 }}
    ---
    apiVersion: v1
    kind: Secret
    metadata:
    name: very-secret
    type: Opaque
    data:
    {{ (.Files.Glob "bar/*").AsSecrets | indent 2 }}
    token: |-
    {{ .Files.Get "config1.toml" | b64enc }}
    ```

    ---

    ## YAML Reference

    ```yaml
    # Forcing a type:
    age: !!str 21
    port: !!int "80"
    # Literal block (keeps formatting and newlines)
    coffee: |
    # Commented first line
    Latte
    Cappuccino
    Espresso
    # Literal block with stripping of trailing newlines:
    coffee: |-
    Latte
    Cappuccino
    Espresso
    # Literal block with extra trailing newline preservation:
    coffee: |+
    Latte
    Cappuccino
    Espresso
    another: value
    # Inserting a static file:
    myfile: |
    {{ .Files.Get "myfile.txt" | indent 2 }}
    # Folded block (combines lines):
    coffee: >
    Latte
    Cappuccino
    Espresso
    ```

    ---

    ## New Features and Enhancements (up to v3.17.3)

    - **OCI Registry Support:**
    Helm v3.7 and later introduced full OCI support. You can now store and retrieve charts directly from OCI-compliant registries. Commands like `helm registry login` and `helm pull oci://<registry>/<chart>` are fully supported.

    - **Improved Dependency Management:**
    Enhancements allow for enhanced resolution of chart dependencies. The consolidation of dependency definitions into the `Chart.yaml` file along with automatic updates via `helm dep update` leads to a simpler, more robust dependency management experience.

    - **Enhanced Security and Chart Signing:**
    Chart signing and provenance verification have been further strengthened. Helm now produces a dedicated provenance file alongside packaged charts, and additional signature verification options are available during installation and upgrades.

    - **Refined Hooks and Test Support:**
    Hooks have received more precise control in execution order and behavior (such as using custom hook weights), and testing has been made more seamless through improved integration with test hooks and release lifecycle management.

    - **Template Engine Improvements:**
    New built-in functions, better error reporting with the `required` function, and enhanced support for global context (`$`) in templating have been added. These features bring more power and flexibility to chart templating.
    File renamed without changes.
  4. tuannvm revised this gist Apr 12, 2025. 1 changed file with 331 additions and 495 deletions.
    826 changes: 331 additions & 495 deletions cka.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    # Kubernetes cheatsheet
    ## Kubernetes cheatsheet

    - [Kubernetes cheatsheet](#kubernetes-cheatsheet)
    - [Getting Started](#getting-started)
    @@ -35,6 +35,7 @@
    - [Persistent volumes](#persistent-volumes)
    - [Role-Based Access Control (RBAC)](#role-based-access-control-rbac)
    - [Custom Resource Definitions](#custom-resource-definitions)
    - [New Features and Objects (up until Kubernetes v1.32)](#new-features-and-objects-up-until-kubernetes-v132)
    - [Notes](#notes)
    - [Basic commands](#basic-commands)
    - [jsonpath](#jsonpath)
    @@ -43,95 +44,93 @@
    - [Memory](#memory)
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)
    - [Downward API](#downward-api)
    - [2025 Updates & Deprecations](#2025-updates--deprecations)
    - [Labs](#labs)
    - [Guaranteed Scheduling For Critical Add-On Pods](#guaranteed-scheduling-for-critical-add-on-pods)
    - [Set command or arguments via env](#set-command-or-arguments-via-env)

    ---

    ## Getting Started

    - Fault tolerance
    - Rollback
    - Auto-healing
    - Auto-scaling
    - Load-balancing
    - Fault tolerance
    - Rollback
    - Auto-healing
    - Auto-scaling
    - Load-balancing
    - Isolation (sandbox)

    *Tip: With rapid Kubernetes evolution through versions 1.32 and beyond, built-in resilience features are continuously enhanced to support modern cloud-native workflows.*

    ---

    ## Sample yaml

    ```yaml
    apiVersion: <>
    kind: <>
    apiVersion: <apiVersion> # Use stable versions (e.g., apps/v1 for Deployments)
    kind: <Kind> # Pod, Service, Deployment, etc.
    metadata:
    name: <>
    name: <object-name>
    labels:
    ...
    key: value
    annotations:
    ...
    key: value
    spec:
    containers:
    ...
    initContainers:
    ...
    priorityClassName: <>
    - name: <container-name>
    image: <container-image>
    initContainers: # Optional: initialization containers run before main containers
    - name: <init-container-name>
    image: <init-container-image>
    priorityClassName: <priority-class>
    ```
    *Adopt a declarative approach to ensure repeatability and auditability of your deployments.*
    ---
    ## Workflow
    Credit: https://www.reddit.com/user/__brennerm/
    Credit: Based on community insights from 2025
    ![](https://i.redd.it/cqud3rjkss361.png)
    - (kube-scheduler, controller-manager, etcd) --443--> API Server
    - API Server --10055--> kubelet
    - non-verified certificate
    - MITM
    - Solution:
    - set kubelet-certificate-authority
    - ssh tunneling
    - (kube-scheduler, controller-manager, etcd) --443--> API Server
    - API Server --10055--> kubelet
    • *Issues such as non-verified certificates and MITM are mitigated by configuring a proper kubelet-certificate-authority or using SSH tunneling.*
    - API server --> (nodes, pods, services) via plain HTTP (verify this against your network security policies)
    - API server --> (nodes, pods, services)
    - Plain HTTP (unsafe)
    ---
    ## Physical components
    ### Master
    - API Server (443)
    - kube-scheduler
    - controller-manager
    - cloud-controller-manager
    - kube-controller-manager
    - etcd
    - **API Server (443)**
    - **Kube-scheduler**
    - **Controller-manager**
    • Consolidated into a unified control plane managing process groups (cloud-controller-manager and kube-controller-manager).
    - **etcd**
    Other components talk to API server, no direct communication
    *All interactions among components occur via the API server, reducing direct cross-component communication.*
    ### Node
    - Kubelet
    - Container Engine
    - CRI
    - The protocol which used to connect between Kubelet & container engine
    - **Kubelet**
    - **Container Engine**
    • Uses the Container Runtime Interface (CRI) to interact with container runtimes.
    - **Kube-proxy**
    • *2025 note: The deprecated field “status.nodeInfo.kubeProxyVersion” is no longer present.*
    - Kube-proxy
    ---
    ## Everything is an object - persistent entities
    - maintained in etcd, identified using
    - names: client-given
    - UIDs: system-generated
    - Both need to be unique
    - three management methods
    - Imperative commands (kubectl)
    - Imperative object configuration (kubectl + yaml)
    - repeatable
    - observable
    - auditable
    - Declarative object configuration (yaml + config files)
    - Live object configuration
    - Current object configuration file
    - Last-applied object configuration file
    - Stored in **etcd** with unique client-assigned names and system-generated UIDs.
    - **Management methods:**
    • Imperative commands via kubectl
    • Imperative configuration objects (using YAML)
    • Declarative object configuration stored in version control
    ```text
    Node Capacity
    @@ -150,86 +149,56 @@ Other components talk to API server, no direct communication
    ---------------------------
    ```

    ---

    ### Namespaces

    - Three pre-defined
    - default
    - kube-system
    - kube-public: auto-readable by all users
    - **Pre-defined namespaces:**
    _default_
    _kube-system_
    _kube-public_ (auto-accessible)
    - Certain objects (Nodes, PersistentVolumes, Namespaces) remain cluster-scoped.

    - Objects without namespaces
    - Nodes
    - PersistentVolumes
    - Namespaces
    ---

    ### Labels

    - key / value
    - loose coupling via selectors
    - need not be unique
    - Key/value pairs for grouping and selection.
    - Not required to be unique.

    #### ClusterIP

    - Independent of lifespan of any backend pod
    - Service object has a static port assigned to it
    - **ClusterIP** provides a static service endpoint that remains unchanged regardless of pod lifecycle changes.

    ---

    ### Controller manager

    - ReplicaSet, deployment, daemonset, statefulSet
    - Actual state <-> desired state
    - reconciliation loop
    - Maintains consistency between desired and actual state via objects like ReplicaSets, Deployments, DaemonSets, and StatefulSets.

    ---

    ### Kube-scheduler

    - nodeSelector
    - Affinity & Anti-Affinity
    - Node
    - Steer pod to node
    - Pod
    - Steer pod towards or away from pods
    - Taints & tolerations (anti-affinity between node and pod!)
    - Base on predefined configuration (env=dev:NoSchedule)
    ```yaml
    ...
    tolerations:
    - key: "dev"
    operator: "equal"
    value: "env"
    effect: NoSchedule
    ...
    ```
    - Base on node condition (alpha in v1.8)
    - taints added by node controller
    - Uses **nodeSelector**, **affinity/anti-affinity**, and **taints & tolerations** to determine pod placement.
    - *Enhanced in v1.32 with improved matching rules and more granular constraint definitions.*

    ---

    ### Pod

    Create a pod with:

    ```bash
    kubectl run name --image=<image>
    kubectl run mypod --image=<image>
    ```

    What's available inside the container?
    Inside a pod you can access:

    - File system
    - Image
    - Associated Volumes
    - ordinary
    - persistent
    - Container
    - Hostname
    - Pod
    - Pod name
    - User-defined envs
    - Services
    - List of all services
    - **Filesystem** (from the image and attached volumes)
    - **Container and Pod Info** (such as hostname, environment variables, pod name, and service details)

    Access with:

    - Symlink (important):

    - /etc/podinfo/labels
    - /etc/podinfo/annotations

    - Or:
    Access pod metadata via symlinked files or Downward API volumes:

    ```yaml
    volumes:
    @@ -244,476 +213,352 @@ volumes:
    fieldPath: metadata.annotations
    ```
    ---
    #### Status
    - Pending
    - Running
    - Succeeded
    - Failed
    - Unknown
    - **Pod status:** Pending, Running, Succeeded, Failed, Unknown.
    #### Probe
    - Liveness
    - Failed? Restart policy applied
    - Readiness
    - Failed? Removed from service
    - **Liveness probe:** Triggers restarts on failure.
    - **Readiness probe:** Removes the pod from service endpoints on failure.
    ---
    #### Pod priorities
    - available since 1.8
    - PriorityClass object
    - Affect scheduling order
    - High priority pods could jump the queue
    - Preemption
    - Low priority pods could be pre-empted to make way for higher one (if no node is available for high priority)
    - These preempted pods would have a graceful termination period
    - Managed via **PriorityClass** objects.
    - Higher priority pods may preempt lower-priority ones, with advanced scheduling controls enhanced in recent versions.
    #### Multi-Container Pods
    ---
    - Share access to memory space
    - Connect to each other using localhost
    - Share access to the same volume
    - entire pod is host on the same node
    - all in or nothing
    - no auto healing or scaling
    #### Multi-Container Pods
    #### Init containers
    - Share memory, localhost networking, and volumes.
    - Designed as a unit for scaling and scheduling.
    - run before app containers
    - always run to completion
    - run serially
    ---
    #### Lifecycle hooks
    #### Init containers
    - PostStart
    - PreStop (blocking)
    - Run sequentially before app containers are launched, ensuring required setup tasks are completed.
    Handlers:
    ---
    - Exec
    - HTTP
    #### Lifecycle hooks
    ```yaml
    ...
    spec:
    containers:
    lifecycle:
    postStart:
    exec:
    command: <>
    preStop:
    http:
    ...
    ```
    - **PostStart** – triggered after a container starts
    - **PreStop** – invoked before a graceful termination
    ```yaml
    lifecycle:
    postStart:
    exec:
    command: ["/bin/setup"]
    preStop:
    httpGet:
    path: "/cleanup"
    port: 8080
    ```
    Could invoke multiple times
    ---
    #### Quality of Service (QoS)
    When Kubernetes creates a Pod it assigns one of these QoS classes to the Pod:
    Kubernetes assigns one of the following QoS classes:
    - Guaranteed (all containers have limits == requests)
    - **Guaranteed:** All containers have matching requests and limits.
    - **Burstable:** At least one container specifies a resource limit or request.
    - **BestEffort:** No resource configurations are provided.
    >If a Container specifies its own memory limit, but does not specify a memory request, Kubernetes automatically assigns a memory request that matches the limit. Similarly, if a Container specifies its own cpu limit, but does not specify a cpu request, Kubernetes automatically assigns a cpu request that matches the limit.
    *Automatic adjustments (e.g., setting memory requests to match limits) are now standard.*
    - Burstable (at least 1 has limits or requests)
    - BestEffort (no limits or requests)
    ---
    #### PodPreset
    You can use a podpreset object to inject information like secrets, volume mounts, and environment variables etc into pods at creation time. This task shows some examples on using the PodPreset resource
    - Enables injection of secrets, environment variables, or volume mounts at pod creation time.
    ```yaml
    apiVersion: settings.k8s.io/v1alpha1
    kind: PodPreset
    metadata:
    name: allow-database
    spec:
    selector:
    matchLabels:
    role: frontend
    env:
    - name: DB_PORT
    value: "6379"
    volumeMounts:
    - mountPath: /cache
    name: cache-volume
    volumes:
    - name: cache-volume
    emptyDir: {}
    ```
    ```yaml
    apiVersion: settings.k8s.io/v1alpha1
    kind: PodPreset
    metadata:
    name: allow-database
    spec:
    selector:
    matchLabels:
    role: frontend
    env:
    - name: DB_PORT
    value: "6379"
    volumeMounts:
    - mountPath: /cache
    name: cache-volume
    volumes:
    - name: cache-volume
    emptyDir: {}
    ```
    ---
    ### ReplicaSet
    Features:

    - Scaling and healing
    - Pod template
    - number of replicas
    - Oversees a fixed number of pod replicas using a defined pod template and selectors.
    - Use `--cascade=false` to delete a ReplicaSet without removing its pods.

    Components:

    - Pod template
    - Pod selector (could use matchExpressions)
    - Label of replicaSet
    - Number of replica

    - Could delete replicaSet without its pods using `--cascade =false`
    - Isolating pods from replicaSet by changing its labels
    ---

    ### Deployments

    - versioning and rollback
    - Contains spec of replicaSet within it
    - advanced deployment
    - blue-green
    - canary

    - Update containers --> new replicaSet & new pods created --> old RS still exists --> reduced to zero
    - Every change is tracked

    - Append `--record` in kubectl to keep history
    - Update strategy
    - Recreate
    - Old pods would be killed before new pods come up
    - RollingUpdate
    - progressDeadlineSeconds
    - minReadySeconds
    - rollbackTo
    - revisionHistoryLimit
    - paused
    - spec.Paused

    - `kubectl rollout undo deployment/<> --to-revision=<>`
    - `kubectl rollout statua deployment/<>`
    - `kubectl set image deployment/<> <>=<>:<>`
    - `kubectl rollout resume/pause <>`
    - Supports versioning, rollback, and advanced update strategies (blue-green, canary, rolling updates).
    - On changes, new ReplicaSets are created while scaling down older ones.
    - *Commands include:*
    • `kubectl rollout undo deployment/<name> --to-revision=<number>`
    • `kubectl set image deployment/<name> <container>=<new-image>`

    ### ReplicationController
    ---

    - RC = ( RS + deployment ) before
    - Obsolete
    ### ReplicationController

    ### DaemonSet
    - Predecessor to ReplicaSets and Deployments and now largely deprecated.

    - Ensure all nodes run a copy of pod
    - Cluster storage, log collection, node monitor ...
    ---

    ### StatefulSet
    ### DaemonSet

    - Maintains a sticky identity
    - Not interchangeable
    - Identifier maintains across any rescheduling
    - Runs a copy of a pod on every node or specific subsets of nodes.
    - Commonly used for log collection, monitoring, and node-level services.

    Limitation
    ---

    - volumes must be pre-provisioned
    - Deleting / Scaling will not delete associated volumes
    ### StatefulSet

    Flow
    - Provides stable identities and persistent storage associations for pods.
    - Volumes remain tied to pods even when scaled down or rescheduled.

    - Deployed 0 --> (n-1)
    - Deleted (n-1) --> 0 (successor must be completely shutdown before proceed)
    - Must be all ready and running before scaling happens
    ---

    ### Job (batch/v1)

    - Non-parallel jobs
    - Parallel jobs
    - Fixed completion count
    - job completes when number of completions reaches target
    - With work queue
    - requires coordination
    - Use spec.activeDeadlineSeconds to prevent infinite loop
    - Manages short-lived, batch-oriented workloads in both parallel and non-parallel forms.
    - `spec.activeDeadlineSeconds` can prevent runaway jobs.

    ---

    ### Cronjob

    - Job should be idempotent
    - Schedules jobs to run at specific times or intervals.
    - The jobs should be idempotent for reliable operation.

    ---

    ### Horizontal pod autoscaler

    - Targets: replicaControllers, deployments, replicaSets
    - CPU or custom metrics
    - Won't work with non-scaling objects: daemonSets
    - Prevent thrashing (upscale/downscale-delay)
    - Scales controllers like Deployments, ReplicaSets, and ReplicaControllers based on CPU or custom metrics.
    - Includes safeguards to avoid scaling thrashing.

    ---

    ### Services

    Credit: https://www.reddit.com/user/__brennerm/
    Credit: Community insights

    ![](https://i.redd.it/brjcbq9xk7261.png)

    - Logical set of backend pods + frontend
    - Frontend: static IP + port + dns name
    - Backend: set of backend pods (via selector)

    - Static IP and networking.
    - Kube-proxy route traffic to VIP.
    - Automatically create endpoint based on selector.

    - CluterIP
    - NodePort
    - external --> NodeIP + NodePort --> kube-proxy --> ClusterIP
    - LoadBalancer
    - Need to have cloud-controller-manager
    - Node controller
    - Route controller
    - Service controller
    - Volume controller
    - external --> LB --> NodeIP + NodePort --> kube-proxy --> ClusterIP
    - ExternalName
    - Can only resolve with kube-dns
    - No selector

    `Service discovery`

    - SRV record for named port
    - port-name.port-protocol.service-name.namespace.svc.cluster.local
    - Pod domain
    - pod-ip-address.namespace.pod.cluster.local
    - hostname is `metadata.name`

    `spec.dnsPolicy`

    - default
    - inherit node's name resolution
    - ClusterFirst
    - Any DNS query that does not match the configured cluster domain suffix, such as “www.kubernetes.io”, is forwarded to the upstream nameserver inherited from the node
    - ClusterFirstWithHostNet
    - if host network = true
    - None (since k8s 1.9)
    - Allow custom dns server usage

    Headless service

    - with selector? --> associate with pods in cluster
    - without selector? --> forward to externalName

    Could specify externalIP to service
    - A Service defines both a logical set of pods and a policy to access them.
    - **Types:**
    - **ClusterIP:** Internal connectivity only.
    - **NodePort:** Exposes a service on every Node’s IP.
    - **LoadBalancer:** Integrates with external load balancers managed by cloud-controller-manager.
    - **ExternalName:** Maps a service to a DNS name.
    - **Service discovery:**
    • Uses SRV records for named ports and established pod domain naming conventions.

    ---

    ### Volumes

    Credit: https://www.reddit.com/user/__brennerm/
    Credit: Community contributions

    ![](https://i.redd.it/iaflueca8m261.png)

    Lifetime longer than any containers inside a pod.

    4 types:

    - configMap

    - emptyDir
    - share space / state across containers in same pod
    - containers can mount at different times
    - pod crash --> data lost
    - container crash --> ok
    - gitRepo
    - Volumes persist data beyond the lifecycle of individual pods.
    - **Types include:**
    • configMap
    • emptyDir – shares space among containers in a pod (data is lost on pod crash)
    • gitRepo (deprecated)
    • secret – typically stored in memory
    • hostPath

    - secret
    - store on RAM
    #### Persistent volumes

    - hostPath
    - Offer long-term storage solutions decoupled from pod lifecycles.

    #### Persistent volumes
    ---

    ### Role-Based Access Control (RBAC)

    Credit: https://www.reddit.com/user/__brennerm/
    Credit: Community insights

    ![](https://i.redd.it/868lf3pp70361.png)

    - Role
    - Apply on namespace resources
    - ClusterRole
    - cluster-scoped resources (nodes,...)
    - non-resources endpoint (/healthz)
    - namespace resources across all namespaces
    - **Role:**
    • Grants permissions within a specific namespace.
    - **ClusterRole:**
    • Applies cluster-wide or to resources spanning multiple namespaces.

    ---

    ### Custom Resource Definitions

    CustomResourceDefinitions themselves are non-namespaced and are available to all namespaces.
    - With Kubernetes evolution, use `apiextensions.k8s.io/v1` instead of the older `v1beta1` API.
    ```yaml
    apiVersion: apiextensions.k8s.io/v1
    kind: CustomResourceDefinition
    metadata:
    name: crontabs.stable.example.com
    spec:
    group: stable.example.com
    versions:
    - name: v1
    served: true
    storage: true
    schema:
    openAPIV3Schema:
    type: object
    properties:
    spec:
    type: object
    properties:
    cronSpec:
    type: string
    pattern: '^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$'
    replicas:
    type: integer
    minimum: 1
    maximum: 10
    subresources:
    status: {}
    scale:
    specReplicasPath: .spec.replicas
    statusReplicasPath: .status.replicas
    labelSelectorPath: .status.labelSelector
    scope: Namespaced
    names:
    plural: crontabs
    singular: crontab
    kind: CronTab
    shortNames:
    - ct
    categories:
    - all
    ```

    ```yaml
    apiVersion: apiextensions.k8s.io/v1beta1
    kind: CustomResourceDefinition
    metadata:
    # name must match the spec fields below, and be in the form: <plural>.<group>
    name: crontabs.stable.example.com
    spec:
    # group name to use for REST API: /apis/<group>/<version>
    group: stable.example.com
    # version name to use for REST API: /apis/<group>/<version>
    version: v1
    # either Namespaced or Cluster
    scope: Namespaced
    names:
    # plural name to be used in the URL: /apis/<group>/<version>/<plural>
    plural: crontabs
    # singular name to be used as an alias on the CLI and for display
    singular: crontab
    # kind is normally the CamelCased singular type. Your resource manifests use this.
    kind: CronTab
    # shortNames allow shorter string to match your resource on the CLI
    shortNames:
    - ct
    # categories is a list of grouped resources the custom resource belongs to.
    categories:
    - all
    validation:
    # openAPIV3Schema is the schema for validating custom objects.
    openAPIV3Schema:
    properties:
    spec:
    properties:
    cronSpec:
    type: string
    pattern: '^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$'
    replicas:
    type: integer
    minimum: 1
    maximum: 10
    # subresources describes the subresources for custom resources.
    subresources:
    # status enables the status subresource.
    status: {}
    # scale enables the scale subresource.
    scale:
    # specReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Spec.Replicas.
    specReplicasPath: .spec.replicas
    # statusReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Replicas.
    statusReplicasPath: .status.replicas
    # labelSelectorPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Selector.
    labelSelectorPath: .status.labelSelector
    ```
    ---

    ### New Features and Objects (up until Kubernetes v1.32)

    - **Ephemeral Containers:**
    • Allow you to attach temporary containers into a running pod for debugging purposes without modifying the pod’s specification. This has become an essential tool for in-cluster troubleshooting.

    - **PodDisruptionBudget (PDB):**
    • Enables you to specify the minimum number of pods that should remain available during voluntary disruptions (such as node maintenance), ensuring service continuity.

    - **EndpointSlices:**
    • Provide a scalable alternative to Endpoints, improving service discovery performance in large clusters by grouping endpoints into smaller subsets.

    - **VolumeSnapshot & CSI Volume Expansion:**
    • VolumeSnapshot objects allow you to capture the state of a persistent volume while the CSI migration and volume expansion features let you dynamically increase storage—all fully supported in the latest releases.

    *These objects and features contribute to improved security, scalability, and observability of your Kubernetes clusters.*

    ---

    ## Notes

    ### Basic commands

    ```bash
    # show current context
    # Show the current context
    kubectl config current-context
    # get specific resource
    kubectl get (pod|svc|deployment|ingress) <resource-name>
    # Get a specific resource (pod|svc|deployment|ingress)
    kubectl get <resource> <resource-name>
    # Get pod logs
    # View pod logs (follow mode)
    kubectl logs -f <pod-name>
    # Get nodes list
    kubectl get no -o custom-columns=NAME:.metadata.name,AWS-INSTANCE:.spec.externalID,AGE:.metadata.creationTimestamp
    # List nodes with custom columns:
    kubectl get nodes -o custom-columns=NAME:.metadata.name,EXTERNAL_ID:.spec.externalID,AGE:.metadata.creationTimestamp
    # Run specific command | Drop to shell
    kubectl exec -it <pod-name> <command>
    # Execute a command in a pod or get an interactive shell:
    kubectl exec -it <pod-name> -- <command>
    # Describe specific resource
    kubectl describe (pod|svc|deployment|ingress) <resource-name>
    # Describe a specific resource
    kubectl describe <resource> <resource-name>
    # Set context
    # Set the current namespace in the context
    kubectl config set-context $(kubectl config current-context) --namespace=<namespace-name>
    # Run a test pod
    # Run a test pod using the Alpine image
    kubectl run -it --rm --generator=run-pod/v1 --image=alpine:3.6 tuan-shell -- sh
    ```

    - from @so0k [link](https://gist.github.com/so0k/42313dbb3b547a0f51a547bb968696ba#gistcomment-2040702)
    *Quick references from community experts remain popular for both learning and troubleshooting.*

    - access dashboard
    To access the Kubernetes dashboard:

    ```bash
    # bash
    # For bash:
    kubectl -n kube-system port-forward $(kubectl get pods -n kube-system -o wide | grep dashboard | awk '{print $1}') 9090
    # fish
    # For fish:
    kubectl -n kube-system port-forward (kubectl get pods -n kube-system -o wide | grep dashboard | awk '{print $1}') 9090
    ```

    ### jsonpath
    ---

    From [link](https://github.com/kubernetes/website/blob/master/content/en/docs/reference/kubectl/jsonpath.md)

    ```json
    {
    "kind": "List",
    "items":[
    {
    "kind":"None",
    "metadata":{"name":"127.0.0.1"},
    "status":{
    "capacity":{"cpu":"4"},
    "addresses":[{"type": "LegacyHostIP", "address":"127.0.0.1"}]
    }
    },
    {
    "kind":"None",
    "metadata":{"name":"127.0.0.2"},
    "status":{
    "capacity":{"cpu":"8"},
    "addresses":[
    {"type": "LegacyHostIP", "address":"127.0.0.2"},
    {"type": "another", "address":"127.0.0.3"}
    ]
    }
    }
    ],
    "users":[
    {
    "name": "myself",
    "user": {}
    },
    {
    "name": "e2e",
    "user": {"username": "admin", "password": "secret"}
    }
    ]
    }
    ```
    ### jsonpath

    | Function | Description | Example | Result |
    |-------------------|---------------------------|---------------------------------------------------------------|-------------------------------------------------|
    | text | the plain text | kind is {.kind} | kind is List |
    | @ | the current object | {@} | the same as input |
    | . or [] | child operator | {.kind} or {['kind']} | List |
    | .. | recursive descent | {..name} | 127.0.0.1 127.0.0.2 myself e2e |
    | \* | wildcard. Get all objects | {.items[*].metadata.name} | [127.0.0.1 127.0.0.2] |
    | [start:end :step] | subscript operator | {.users[0].name} | myself |
    | [,] | union operator | {.items[*]['metadata.name', 'status.capacity']} | 127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8] |
    | ?() | filter | {.users[?(@.name=="e2e")].user.password} | secret |
    | range, end | iterate list | {range .items[*]}[{.metadata.name}, {.status.capacity}] {end} | [127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]] |
    | '' | quote interpreted string | {range .items[*]}{.metadata.name}{'\t'}{end} | 127.0.0.1 127.0.0.2 |

    Below are some examples using jsonpath:
    JSONPath expressions let you filter and extract specific fields from JSON output. Examples include:

    ```shell
    $ kubectl get pods -o json
    $ kubectl get pods -o=jsonpath='{@}'
    $ kubectl get pods -o=jsonpath='{.items[0]}'
    $ kubectl get pods -o=jsonpath='{.items[0].metadata.name}'
    $ kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.startTime}{"\n"}{end}'
    kubectl get pods -o json
    kubectl get pods -o=jsonpath='{.items[0].metadata.name}'
    kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.startTime}{"\n"}{end}'
    ```

    | Function | Description | Example | Result |
    |--------------------|-------------------------------------|-------------------------------------------------------------|-----------------------------------------|
    | text | Plain text output | `{.kind}` | List |
    | @ | Current object | `{@}` | Same as input |
    | . or [] | Child operator | `{.metadata.name}` | Pod name |
    | .. | Recursive descent | `{..name}` | All occurrences of "name" |
    | * | Wildcard expansion | `{.items[*].metadata.name}` | List of pod names |
    | [start:end:step] | Subscript operator | `{.items[0].metadata.name}` | First pod name |
    | [,] | Union operator | `{.items[*]['metadata.name','status.capacity']}` | Selected fields from each item |
    | ?() | Filter | `{.items[?(@.metadata.name=="mypass")].status.phase}` | Phase for matching pod |

    ---

    ### Resource limit

    #### CPU

    The CPU resource is measured in cpu units. One cpu, in Kubernetes, is equivalent to:

    - 1 AWS vCPU
    - 1 GCP Core
    - 1 Azure vCore
    - 1 Hyperthread on a bare-metal Intel processor with Hyperthreading
    - One CPU is equivalent to one AWS vCPU, one GCP Core, one Azure vCore, or one hyperthread in a modern Intel processor.

    #### Memory

    The memory resource is measured in bytes. You can express memory as a plain integer or a fixed-point integer with one of these suffixes: E, P, T, G, M, K, Ei, Pi, Ti, Gi, Mi, Ki. For example, the following represent approximately the same value:
    - Memory can be specified in bytes, using suffixes such as K, M, G or Ki, Mi, Gi.
    *Example:* `129M` or `123Mi` yield similar memory requirements.

    128974848, 129e6, 129M , 123Mi
    ---

    ### Chapter 13. Integrating storage solutions and Kubernetes

    - External service without selector (access with `external-database.svc.default.cluster` endpoint)
    **External services:**
    Use an ExternalName Service or manually configure endpoints if you need to integrate with external systems.

    **Example: External service without selector:**

    ```yaml
    kind: Service
    @@ -722,78 +567,69 @@ metadata:
    name: external-database
    spec:
    type: ExternalName
    externalName: "database.company.com
    externalName: "database.company.com"
    ```

    - external service with IP only
    **Example: External service with fixed IP:**

    ```yaml
    kind: Service
    apiVersion: v1
    metadata:
    name: external-ip-database
    spec:
    type: ClusterIP
    ---
    kind: Endpoints
    apiVersion: v1
    metadata:
    name: external-ip-database
    subsets:
    - addresses:
    - ip: 192.168.0.1
    - ip: 192.168.0.1
    ports:
    - port: 3306
    - port: 3306
    ```

    #### Downward API

    The following information is available to containers through environment variables and downwardAPI volumes:
    Expose pod metadata (e.g., name, namespace, labels, annotations) to containers via environment variables or volumes using the Downward API.

    Information available via fieldRef:
    ---

    - spec.nodeName - the node’s name
    - status.hostIP - the node’s IP
    - metadata.name - the pod’s name
    - metadata.namespace - the pod’s namespace
    - status.podIP - the pod’s IP address
    - spec.serviceAccountName - the pod’s service account name
    - metadata.uid - the pod’s UID
    - metadata.labels['<KEY>'] - the value of the pod’s label <KEY> (for example, metadata.labels['mylabel']); available in Kubernetes 1.9+
    - metadata.annotations['<KEY>'] - the value of the pod’s annotation <KEY> (for example, metadata.annotations['myannotation']); available in Kubernetes 1.9+
    - Information available via resourceFieldRef:
    - A Container’s CPU limit
    - A Container’s CPU request
    - A Container’s memory limit
    - A Container’s memory request
    ### 2025 Updates & Deprecations

    In addition, the following information is available through downwardAPI volume fieldRef:
    - **Kubernetes v1.33:**
    • The Endpoints API is superseded by EndpointSlices for better scalability.
    • The field `status.nodeInfo.kubeProxyVersion` is removed.
    • Enhanced scheduling options and dynamic resource allocation (including GPUs and FPGAs) are now available.
    • Windows pods no longer support host network mode; review your networking configuration if using Windows containers.

    - metadata.labels - all of the pod’s labels, formatted as label-key="escaped-label-value" with one label per line
    - metadata.annotations - all of the pod’s annotations, formatted as annotation-key="escaped-annotation-value" with one annotation per line
    - **CRD Updates:**
    • Use `apiextensions.k8s.io/v1` as the stable API version for custom resource definitions.

    ## Labs
    *Staying updated with these changes keeps your clusters secure, scalable, and ready for modern workloads.*

    ### Guaranteed Scheduling For Critical Add-On Pods
    ---

    See [link](https://kubernetes.io/docs/tasks/administer-cluster/guaranteed-scheduling-critical-addon-pods/)
    ## Labs

    - Marking pod as critical when using Rescheduler. To be considered critical, the pod has to:
    - Run in the `kube-system` namespace (configurable via flag)
    - Have the `scheduler.alpha.kubernetes.io/critical-pod` annotation set to empty string
    - Have the PodSpec’s tolerations field set to `[{"key":"CriticalAddonsOnly", "operator":"Exists"}]`.
    ### Guaranteed Scheduling For Critical Add-On Pods

    > The first one marks a pod a critical. The second one is required by Rescheduler algorithm.
    Review the official guide for [Guaranteed Scheduling for Critical Add-On Pods](https://kubernetes.io/docs/tasks/administer-cluster/guaranteed-scheduling-critical-addon-pods/).
    Key aspects include:
    - The pod must run in the `kube-system` namespace.
    - It must have the `scheduler.alpha.kubernetes.io/critical-pod` annotation set (typically an empty string).
    - When priorities are enabled, assign the pod a `priorityClass` of `system-cluster-critical` or `system-node-critical`.

    - Marking pod as critical when priorites are enabled. To be considered critical, the pod has to:
    - Run in the `kube-system` namespace (configurable via flag)
    - Have the priorityClass set as `system-cluster-critical` or `system-node-critical`, the latter being the highest for entire cluster
    - `scheduler.alpha.kubernetes.io/critical-pod` annotation set to empty string(This will be deprecated too).
    ---

    ### Set command or arguments via env

    ```yaml
    env:
    - name: MESSAGE
    value: "hello world"
    - name: MESSAGE
    value: "hello world"
    command: ["/bin/echo"]
    args: ["$(MESSAGE)"]
    ```
    ```
  5. tuannvm renamed this gist Dec 16, 2021. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  6. tuannvm revised this gist Dec 13, 2020. 1 changed file with 4 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -77,6 +77,10 @@ spec:
    ## Workflow
    Credit: https://www.reddit.com/user/__brennerm/
    ![](https://i.redd.it/cqud3rjkss361.png)
    - (kube-scheduler, controller-manager, etcd) --443--> API Server
    - API Server --10055--> kubelet
  7. tuannvm revised this gist Dec 13, 2020. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions helm-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -6,7 +6,7 @@
    - [General Usage](#general-usage)
    - [Template](#template)
    - [Hooks](#hooks)
    - [Chart repository](#chart-repository)
    - [Chart Repository](#chart-repository)
    - [Signing](#signing)
    - [Test](#test)
    - [Flow Control](#flow-control)
    @@ -272,7 +272,7 @@ metadata:
    "helm.sh/hook-weight": "-5"
    ```

    ## Chart repository
    ## Chart Repository

    Read [more](https://github.com/kubernetes/helm/blob/master/docs/chart_repository.md#the-index-file)

  8. tuannvm revised this gist Dec 13, 2020. 1 changed file with 4 additions and 8 deletions.
    12 changes: 4 additions & 8 deletions helm-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -1,9 +1,7 @@
    # Helm cheatsheet
    # Helm CheatSheet

    <!-- TOC -->

    - [Helm cheatsheet](#helm-cheatsheet)
    - [Get started](#get-started)
    - [Helm CheatSheet](#helm-cheatsheet)
    - [Get Started](#get-started)
    - [Struture](#struture)
    - [General Usage](#general-usage)
    - [Template](#template)
    @@ -21,9 +19,7 @@
    - [Glob-patterns & encoding](#glob-patterns--encoding)
    - [YAML reference](#yaml-reference)

    <!-- /TOC -->

    ## Get started
    ## Get Started

    - https://deis.com/blog/2016/getting-started-authoring-helm-charts/
    - https://docs.bitnami.com/kubernetes/how-to/
  9. tuannvm revised this gist Dec 13, 2020. 1 changed file with 46 additions and 1 deletion.
    47 changes: 46 additions & 1 deletion kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,51 @@
    # Kubernetes cheatsheet

    <!-- TOC -->autoauto- [Kubernetes cheatsheet](#kubernetes-cheatsheet)auto - [Getting Started](#getting-started)auto - [Sample yaml](#sample-yaml)auto - [Workflow](#workflow)auto - [Physical components](#physical-components)auto - [Master](#master)auto - [Node](#node)auto - [Everything is an object - persistent entities](#everything-is-an-object---persistent-entities)auto - [Namespaces](#namespaces)auto - [Labels](#labels)auto - [ClusterIP](#clusterip)auto - [Controller manager](#controller-manager)auto - [Kube-scheduler](#kube-scheduler)auto - [Pod](#pod)auto - [Status](#status)auto - [Probe](#probe)auto - [Pod priorities](#pod-priorities)auto - [Multi-Container Pods](#multi-container-pods)auto - [Init containers](#init-containers)auto - [Lifecycle hooks](#lifecycle-hooks)auto - [Quality of Service (QoS)](#quality-of-service-qos)auto - [PodPreset](#podpreset)auto - [ReplicaSet](#replicaset)auto - [Deployments](#deployments)auto - [ReplicationController](#replicationcontroller)auto - [DaemonSet](#daemonset)auto - [StatefulSet](#statefulset)auto - [Job (batch/v1)](#job-batchv1)auto - [Cronjob](#cronjob)auto - [Horizontal pod autoscaler](#horizontal-pod-autoscaler)auto - [Services](#services)auto - [Volumes](#volumes)auto - [Persistent volumes](#persistent-volumes)auto - [Role-Based Access Control (RBAC)](#role-based-access-control-rbac)auto - [Custom Resource Definitions](#custom-resource-definitions)auto - [Notes](#notes)auto - [Basic commands](#basic-commands)auto - [jsonpath](#jsonpath)auto - [Resource limit](#resource-limit)auto - [CPU](#cpu)auto - [Memory](#memory)auto - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)auto - [Downward API](#downward-api)auto - [Labs](#labs)auto - [Guaranteed Scheduling For Critical Add-On Pods](#guaranteed-scheduling-for-critical-add-on-pods)auto - [Set command or arguments via env](#set-command-or-arguments-via-env)autoauto<!-- /TOC -->
    - [Kubernetes cheatsheet](#kubernetes-cheatsheet)
    - [Getting Started](#getting-started)
    - [Sample yaml](#sample-yaml)
    - [Workflow](#workflow)
    - [Physical components](#physical-components)
    - [Master](#master)
    - [Node](#node)
    - [Everything is an object - persistent entities](#everything-is-an-object---persistent-entities)
    - [Namespaces](#namespaces)
    - [Labels](#labels)
    - [ClusterIP](#clusterip)
    - [Controller manager](#controller-manager)
    - [Kube-scheduler](#kube-scheduler)
    - [Pod](#pod)
    - [Status](#status)
    - [Probe](#probe)
    - [Pod priorities](#pod-priorities)
    - [Multi-Container Pods](#multi-container-pods)
    - [Init containers](#init-containers)
    - [Lifecycle hooks](#lifecycle-hooks)
    - [Quality of Service (QoS)](#quality-of-service-qos)
    - [PodPreset](#podpreset)
    - [ReplicaSet](#replicaset)
    - [Deployments](#deployments)
    - [ReplicationController](#replicationcontroller)
    - [DaemonSet](#daemonset)
    - [StatefulSet](#statefulset)
    - [Job (batch/v1)](#job-batchv1)
    - [Cronjob](#cronjob)
    - [Horizontal pod autoscaler](#horizontal-pod-autoscaler)
    - [Services](#services)
    - [Volumes](#volumes)
    - [Persistent volumes](#persistent-volumes)
    - [Role-Based Access Control (RBAC)](#role-based-access-control-rbac)
    - [Custom Resource Definitions](#custom-resource-definitions)
    - [Notes](#notes)
    - [Basic commands](#basic-commands)
    - [jsonpath](#jsonpath)
    - [Resource limit](#resource-limit)
    - [CPU](#cpu)
    - [Memory](#memory)
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)
    - [Downward API](#downward-api)
    - [Labs](#labs)
    - [Guaranteed Scheduling For Critical Add-On Pods](#guaranteed-scheduling-for-critical-add-on-pods)
    - [Set command or arguments via env](#set-command-or-arguments-via-env)

    ## Getting Started

  10. tuannvm revised this gist Dec 6, 2020. 1 changed file with 4 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -445,6 +445,10 @@ Could specify externalIP to service

    ### Volumes

    Credit: https://www.reddit.com/user/__brennerm/

    ![](https://i.redd.it/iaflueca8m261.png)

    Lifetime longer than any containers inside a pod.

    4 types:
  11. tuannvm revised this gist Dec 6, 2020. 1 changed file with 7 additions and 49 deletions.
    56 changes: 7 additions & 49 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -1,54 +1,6 @@
    # Kubernetes cheatsheet

    <!-- TOC -->

    - [Kubernetes cheatsheet](#kubernetes-cheatsheet)
    - [Getting Started](#getting-started)
    - [Sample yaml](#sample-yaml)
    - [Workflow](#workflow)
    - [Physical components](#physical-components)
    - [Master](#master)
    - [Node](#node)
    - [Everything is an object - persistent entities](#everything-is-an-object---persistent-entities)
    - [Namespaces](#namespaces)
    - [Labels](#labels)
    - [ClusterIP](#clusterip)
    - [Controller manager](#controller-manager)
    - [Kube-scheduler](#kube-scheduler)
    - [Pod](#pod)
    - [Status](#status)
    - [Probe](#probe)
    - [Pod priorities](#pod-priorities)
    - [Multi-Container Pods](#multi-container-pods)
    - [Init containers](#init-containers)
    - [Lifecycle hooks](#lifecycle-hooks)
    - [Quality of Service (QoS)](#quality-of-service-qos)
    - [PodPreset](#podpreset)
    - [ReplicaSet](#replicaset)
    - [Deployments](#deployments)
    - [ReplicationController](#replicationcontroller)
    - [DaemonSet](#daemonset)
    - [StatefulSet](#statefulset)
    - [Job (batch/v1)](#job-batchv1)
    - [Cronjob](#cronjob)
    - [Horizontal pod autoscaler](#horizontal-pod-autoscaler)
    - [Services](#services)
    - [Volumes](#volumes)
    - [Persistent volumes](#persistent-volumes)
    - [Role-Based Access Control (RBAC)](#role-based-access-control-rbac)
    - [Notes](#notes)
    - [Basic commands](#basic-commands)
    - [jsonpath](#jsonpath)
    - [Resource limit](#resource-limit)
    - [CPU](#cpu)
    - [Memory](#memory)
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)
    - [Downward API](#downward-api)
    - [Labs](#labs)
    - [Guaranteed Scheduling For Critical Add-On Pods](#guaranteed-scheduling-for-critical-add-on-pods)
    - [Set command or arguments via env](#set-command-or-arguments-via-env)

    <!-- /TOC -->
    <!-- TOC -->autoauto- [Kubernetes cheatsheet](#kubernetes-cheatsheet)auto - [Getting Started](#getting-started)auto - [Sample yaml](#sample-yaml)auto - [Workflow](#workflow)auto - [Physical components](#physical-components)auto - [Master](#master)auto - [Node](#node)auto - [Everything is an object - persistent entities](#everything-is-an-object---persistent-entities)auto - [Namespaces](#namespaces)auto - [Labels](#labels)auto - [ClusterIP](#clusterip)auto - [Controller manager](#controller-manager)auto - [Kube-scheduler](#kube-scheduler)auto - [Pod](#pod)auto - [Status](#status)auto - [Probe](#probe)auto - [Pod priorities](#pod-priorities)auto - [Multi-Container Pods](#multi-container-pods)auto - [Init containers](#init-containers)auto - [Lifecycle hooks](#lifecycle-hooks)auto - [Quality of Service (QoS)](#quality-of-service-qos)auto - [PodPreset](#podpreset)auto - [ReplicaSet](#replicaset)auto - [Deployments](#deployments)auto - [ReplicationController](#replicationcontroller)auto - [DaemonSet](#daemonset)auto - [StatefulSet](#statefulset)auto - [Job (batch/v1)](#job-batchv1)auto - [Cronjob](#cronjob)auto - [Horizontal pod autoscaler](#horizontal-pod-autoscaler)auto - [Services](#services)auto - [Volumes](#volumes)auto - [Persistent volumes](#persistent-volumes)auto - [Role-Based Access Control (RBAC)](#role-based-access-control-rbac)auto - [Custom Resource Definitions](#custom-resource-definitions)auto - [Notes](#notes)auto - [Basic commands](#basic-commands)auto - [jsonpath](#jsonpath)auto - [Resource limit](#resource-limit)auto - [CPU](#cpu)auto - [Memory](#memory)auto - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)auto - [Downward API](#downward-api)auto - [Labs](#labs)auto - [Guaranteed Scheduling For Critical Add-On Pods](#guaranteed-scheduling-for-critical-add-on-pods)auto - [Set command or arguments via env](#set-command-or-arguments-via-env)autoauto<!-- /TOC -->

    ## Getting Started

    @@ -439,6 +391,10 @@ Flow

    ### Services

    Credit: https://www.reddit.com/user/__brennerm/

    ![](https://i.redd.it/brjcbq9xk7261.png)

    - Logical set of backend pods + frontend
    - Frontend: static IP + port + dns name
    - Backend: set of backend pods (via selector)
    @@ -511,6 +467,8 @@ Lifetime longer than any containers inside a pod.

    ### Role-Based Access Control (RBAC)

    Credit: https://www.reddit.com/user/__brennerm/

    ![](https://i.redd.it/868lf3pp70361.png)

    - Role
  12. tuannvm revised this gist Dec 6, 2020. 1 changed file with 25 additions and 23 deletions.
    48 changes: 25 additions & 23 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -135,17 +135,17 @@ Other components talk to API server, no direct communication
    ```text
    Node Capacity
    ---------------------------
    | kube-reserved |
    |-------------------------|
    | system-reserved |
    |-------------------------|
    | eviction-threshold |
    |-------------------------|
    | |
    | allocatable |
    | (available for pods) |
    | |
    | |
    | kube-reserved |
    |---------------------------|
    | system-reserved |
    | ------------------------- |
    | eviction-threshold |
    | ------------------------- |
    | |
    | allocatable |
    | (available for pods) |
    | |
    | |
    ---------------------------
    ```

    @@ -511,6 +511,8 @@ Lifetime longer than any containers inside a pod.

    ### Role-Based Access Control (RBAC)

    ![](https://i.redd.it/868lf3pp70361.png)

    - Role
    - Apply on namespace resources
    - ClusterRole
    @@ -658,18 +660,18 @@ From [link](https://github.com/kubernetes/website/blob/master/content/en/docs/re
    }
    ```

    Function | Description | Example | Result
    ---------|--------------------|--------------------|------------------
    text | the plain text | kind is {.kind} | kind is List
    @ | the current object | {@} | the same as input
    . or [] | child operator | {.kind} or {['kind']}| List
    .. | recursive descent | {..name} | 127.0.0.1 127.0.0.2 myself e2e
    \* | wildcard. Get all objects| {.items[*].metadata.name} | [127.0.0.1 127.0.0.2]
    [start:end :step] | subscript operator | {.users[0].name}| myself
    [,] | union operator | {.items[*]['metadata.name', 'status.capacity']} | 127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8]
    ?() | filter | {.users[?(@.name=="e2e")].user.password} | secret
    range, end | iterate list | {range .items[*]}[{.metadata.name}, {.status.capacity}] {end} | [127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]]
    '' | quote interpreted string | {range .items[*]}{.metadata.name}{'\t'}{end} | 127.0.0.1 127.0.0.2
    | Function | Description | Example | Result |
    |-------------------|---------------------------|---------------------------------------------------------------|-------------------------------------------------|
    | text | the plain text | kind is {.kind} | kind is List |
    | @ | the current object | {@} | the same as input |
    | . or [] | child operator | {.kind} or {['kind']} | List |
    | .. | recursive descent | {..name} | 127.0.0.1 127.0.0.2 myself e2e |
    | \* | wildcard. Get all objects | {.items[*].metadata.name} | [127.0.0.1 127.0.0.2] |
    | [start:end :step] | subscript operator | {.users[0].name} | myself |
    | [,] | union operator | {.items[*]['metadata.name', 'status.capacity']} | 127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8] |
    | ?() | filter | {.users[?(@.name=="e2e")].user.password} | secret |
    | range, end | iterate list | {range .items[*]}[{.metadata.name}, {.status.capacity}] {end} | [127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]] |
    | '' | quote interpreted string | {range .items[*]}{.metadata.name}{'\t'}{end} | 127.0.0.1 127.0.0.2 |

    Below are some examples using jsonpath:

  13. tuannvm revised this gist Dec 15, 2019. 1 changed file with 8 additions and 1 deletion.
    9 changes: 8 additions & 1 deletion tools.md
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,10 @@
    ## Helm

    - helm chart unit test https://github.com/xchapter7x/hcunit?utm_sq=g92df5t58c
    - helm chart unit test https://github.com/xchapter7x/hcunit?utm_sq=g92df5t58c

    ## Container

    - container test: https://github.com/GoogleContainerTools/container-structure-test

    ## AWS
    - SSO login: https://github.com/wnkz/aws-sso/blob/master/README.md
  14. tuannvm revised this gist Dec 15, 2019. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion tools.md
    Original file line number Diff line number Diff line change
    @@ -1 +1,3 @@
    c
    ## Helm

    - helm chart unit test https://github.com/xchapter7x/hcunit?utm_sq=g92df5t58c
  15. tuannvm revised this gist Dec 15, 2019. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions tools.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    c
  16. tuannvm revised this gist May 22, 2018. 1 changed file with 57 additions and 0 deletions.
    57 changes: 57 additions & 0 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -518,6 +518,63 @@ Lifetime longer than any containers inside a pod.
    - non-resources endpoint (/healthz)
    - namespace resources across all namespaces

    ### Custom Resource Definitions

    CustomResourceDefinitions themselves are non-namespaced and are available to all namespaces.

    ```yaml
    apiVersion: apiextensions.k8s.io/v1beta1
    kind: CustomResourceDefinition
    metadata:
    # name must match the spec fields below, and be in the form: <plural>.<group>
    name: crontabs.stable.example.com
    spec:
    # group name to use for REST API: /apis/<group>/<version>
    group: stable.example.com
    # version name to use for REST API: /apis/<group>/<version>
    version: v1
    # either Namespaced or Cluster
    scope: Namespaced
    names:
    # plural name to be used in the URL: /apis/<group>/<version>/<plural>
    plural: crontabs
    # singular name to be used as an alias on the CLI and for display
    singular: crontab
    # kind is normally the CamelCased singular type. Your resource manifests use this.
    kind: CronTab
    # shortNames allow shorter string to match your resource on the CLI
    shortNames:
    - ct
    # categories is a list of grouped resources the custom resource belongs to.
    categories:
    - all
    validation:
    # openAPIV3Schema is the schema for validating custom objects.
    openAPIV3Schema:
    properties:
    spec:
    properties:
    cronSpec:
    type: string
    pattern: '^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$'
    replicas:
    type: integer
    minimum: 1
    maximum: 10
    # subresources describes the subresources for custom resources.
    subresources:
    # status enables the status subresource.
    status: {}
    # scale enables the scale subresource.
    scale:
    # specReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Spec.Replicas.
    specReplicasPath: .spec.replicas
    # statusReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Replicas.
    statusReplicasPath: .status.replicas
    # labelSelectorPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Selector.
    labelSelectorPath: .status.labelSelector
    ```

    ## Notes

    ### Basic commands
  17. tuannvm revised this gist May 19, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -23,6 +23,7 @@
    - [Init containers](#init-containers)
    - [Lifecycle hooks](#lifecycle-hooks)
    - [Quality of Service (QoS)](#quality-of-service-qos)
    - [PodPreset](#podpreset)
    - [ReplicaSet](#replicaset)
    - [Deployments](#deployments)
    - [ReplicationController](#replicationcontroller)
    @@ -318,7 +319,6 @@ When Kubernetes creates a Pod it assigns one of these QoS classes to the Pod:
    - Burstable (at least 1 has limits or requests)
    - BestEffort (no limits or requests)


    #### PodPreset

    You can use a podpreset object to inject information like secrets, volume mounts, and environment variables etc into pods at creation time. This task shows some examples on using the PodPreset resource
  18. tuannvm revised this gist May 19, 2018. 1 changed file with 24 additions and 0 deletions.
    24 changes: 24 additions & 0 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -319,6 +319,30 @@ When Kubernetes creates a Pod it assigns one of these QoS classes to the Pod:
    - BestEffort (no limits or requests)


    #### PodPreset

    You can use a podpreset object to inject information like secrets, volume mounts, and environment variables etc into pods at creation time. This task shows some examples on using the PodPreset resource

    ```yaml
    apiVersion: settings.k8s.io/v1alpha1
    kind: PodPreset
    metadata:
    name: allow-database
    spec:
    selector:
    matchLabels:
    role: frontend
    env:
    - name: DB_PORT
    value: "6379"
    volumeMounts:
    - mountPath: /cache
    name: cache-volume
    volumes:
    - name: cache-volume
    emptyDir: {}
    ```

    ### ReplicaSet

    Features:
  19. tuannvm revised this gist May 19, 2018. 1 changed file with 4 additions and 2 deletions.
    6 changes: 4 additions & 2 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -42,6 +42,7 @@
    - [CPU](#cpu)
    - [Memory](#memory)
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)
    - [Downward API](#downward-api)
    - [Labs](#labs)
    - [Guaranteed Scheduling For Critical Add-On Pods](#guaranteed-scheduling-for-critical-add-on-pods)
    - [Set command or arguments via env](#set-command-or-arguments-via-env)
    @@ -669,10 +670,11 @@ Information available via fieldRef:
    - A Container’s CPU request
    - A Container’s memory limit
    - A Container’s memory request

    In addition, the following information is available through downwardAPI volume fieldRef:

    metadata.labels - all of the pod’s labels, formatted as label-key="escaped-label-value" with one label per line
    metadata.annotations - all of the pod’s annotations, formatted as annotation-key="escaped-annotation-value" with one annotation per line
    - metadata.labels - all of the pod’s labels, formatted as label-key="escaped-label-value" with one label per line
    - metadata.annotations - all of the pod’s annotations, formatted as annotation-key="escaped-annotation-value" with one annotation per line

    ## Labs

  20. tuannvm revised this gist May 19, 2018. 1 changed file with 25 additions and 0 deletions.
    25 changes: 25 additions & 0 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -649,6 +649,31 @@ subsets:
    - port: 3306
    ```

    #### Downward API

    The following information is available to containers through environment variables and downwardAPI volumes:

    Information available via fieldRef:

    - spec.nodeName - the node’s name
    - status.hostIP - the node’s IP
    - metadata.name - the pod’s name
    - metadata.namespace - the pod’s namespace
    - status.podIP - the pod’s IP address
    - spec.serviceAccountName - the pod’s service account name
    - metadata.uid - the pod’s UID
    - metadata.labels['<KEY>'] - the value of the pod’s label <KEY> (for example, metadata.labels['mylabel']); available in Kubernetes 1.9+
    - metadata.annotations['<KEY>'] - the value of the pod’s annotation <KEY> (for example, metadata.annotations['myannotation']); available in Kubernetes 1.9+
    - Information available via resourceFieldRef:
    - A Container’s CPU limit
    - A Container’s CPU request
    - A Container’s memory limit
    - A Container’s memory request
    In addition, the following information is available through downwardAPI volume fieldRef:

    metadata.labels - all of the pod’s labels, formatted as label-key="escaped-label-value" with one label per line
    metadata.annotations - all of the pod’s annotations, formatted as annotation-key="escaped-annotation-value" with one annotation per line

    ## Labs

    ### Guaranteed Scheduling For Critical Add-On Pods
  21. tuannvm revised this gist May 19, 2018. 1 changed file with 11 additions and 0 deletions.
    11 changes: 11 additions & 0 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -44,6 +44,7 @@
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)
    - [Labs](#labs)
    - [Guaranteed Scheduling For Critical Add-On Pods](#guaranteed-scheduling-for-critical-add-on-pods)
    - [Set command or arguments via env](#set-command-or-arguments-via-env)

    <!-- /TOC -->

    @@ -665,3 +666,13 @@ See [link](https://kubernetes.io/docs/tasks/administer-cluster/guaranteed-schedu
    - Run in the `kube-system` namespace (configurable via flag)
    - Have the priorityClass set as `system-cluster-critical` or `system-node-critical`, the latter being the highest for entire cluster
    - `scheduler.alpha.kubernetes.io/critical-pod` annotation set to empty string(This will be deprecated too).

    ### Set command or arguments via env

    ```yaml
    env:
    - name: MESSAGE
    value: "hello world"
    command: ["/bin/echo"]
    args: ["$(MESSAGE)"]
    ```
  22. tuannvm revised this gist May 19, 2018. 1 changed file with 0 additions and 2 deletions.
    2 changes: 0 additions & 2 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,3 @@


    # Kubernetes cheatsheet

    <!-- TOC -->
  23. tuannvm revised this gist May 19, 2018. 1 changed file with 35 additions and 0 deletions.
    35 changes: 35 additions & 0 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@


    # Kubernetes cheatsheet

    <!-- TOC -->
    @@ -22,6 +24,7 @@
    - [Multi-Container Pods](#multi-container-pods)
    - [Init containers](#init-containers)
    - [Lifecycle hooks](#lifecycle-hooks)
    - [Quality of Service (QoS)](#quality-of-service-qos)
    - [ReplicaSet](#replicaset)
    - [Deployments](#deployments)
    - [ReplicationController](#replicationcontroller)
    @@ -37,6 +40,9 @@
    - [Notes](#notes)
    - [Basic commands](#basic-commands)
    - [jsonpath](#jsonpath)
    - [Resource limit](#resource-limit)
    - [CPU](#cpu)
    - [Memory](#memory)
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)
    - [Labs](#labs)
    - [Guaranteed Scheduling For Critical Add-On Pods](#guaranteed-scheduling-for-critical-add-on-pods)
    @@ -301,6 +307,18 @@ spec:

    Could invoke multiple times

    #### Quality of Service (QoS)

    When Kubernetes creates a Pod it assigns one of these QoS classes to the Pod:

    - Guaranteed (all containers have limits == requests)

    >If a Container specifies its own memory limit, but does not specify a memory request, Kubernetes automatically assigns a memory request that matches the limit. Similarly, if a Container specifies its own cpu limit, but does not specify a cpu request, Kubernetes automatically assigns a cpu request that matches the limit.

    - Burstable (at least 1 has limits or requests)
    - BestEffort (no limits or requests)


    ### ReplicaSet

    Features:
    @@ -582,6 +600,23 @@ $ kubectl get pods -o=jsonpath='{.items[0].metadata.name}'
    $ kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.startTime}{"\n"}{end}'
    ```

    ### Resource limit

    #### CPU

    The CPU resource is measured in cpu units. One cpu, in Kubernetes, is equivalent to:

    - 1 AWS vCPU
    - 1 GCP Core
    - 1 Azure vCore
    - 1 Hyperthread on a bare-metal Intel processor with Hyperthreading

    #### Memory

    The memory resource is measured in bytes. You can express memory as a plain integer or a fixed-point integer with one of these suffixes: E, P, T, G, M, K, Ei, Pi, Ti, Gi, Mi, Ki. For example, the following represent approximately the same value:

    128974848, 129e6, 129M , 123Mi

    ### Chapter 13. Integrating storage solutions and Kubernetes

    - External service without selector (access with `external-database.svc.default.cluster` endpoint)
  24. tuannvm revised this gist May 17, 2018. 1 changed file with 21 additions and 0 deletions.
    21 changes: 21 additions & 0 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -38,6 +38,8 @@
    - [Basic commands](#basic-commands)
    - [jsonpath](#jsonpath)
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)
    - [Labs](#labs)
    - [Guaranteed Scheduling For Critical Add-On Pods](#guaranteed-scheduling-for-critical-add-on-pods)

    <!-- /TOC -->

    @@ -123,6 +125,23 @@ Other components talk to API server, no direct communication
    - Current object configuration file
    - Last-applied object configuration file
    ```text
    Node Capacity
    ---------------------------
    | kube-reserved |
    |-------------------------|
    | system-reserved |
    |-------------------------|
    | eviction-threshold |
    |-------------------------|
    | |
    | allocatable |
    | (available for pods) |
    | |
    | |
    ---------------------------
    ```

    ### Namespaces

    - Three pre-defined
    @@ -600,6 +619,8 @@ subsets:

    ### Guaranteed Scheduling For Critical Add-On Pods

    See [link](https://kubernetes.io/docs/tasks/administer-cluster/guaranteed-scheduling-critical-addon-pods/)

    - Marking pod as critical when using Rescheduler. To be considered critical, the pod has to:
    - Run in the `kube-system` namespace (configurable via flag)
    - Have the `scheduler.alpha.kubernetes.io/critical-pod` annotation set to empty string
  25. tuannvm revised this gist May 16, 2018. 1 changed file with 16 additions and 0 deletions.
    16 changes: 16 additions & 0 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -595,3 +595,19 @@ subsets:
    ports:
    - port: 3306
    ```

    ## Labs

    ### Guaranteed Scheduling For Critical Add-On Pods

    - Marking pod as critical when using Rescheduler. To be considered critical, the pod has to:
    - Run in the `kube-system` namespace (configurable via flag)
    - Have the `scheduler.alpha.kubernetes.io/critical-pod` annotation set to empty string
    - Have the PodSpec’s tolerations field set to `[{"key":"CriticalAddonsOnly", "operator":"Exists"}]`.

    > The first one marks a pod a critical. The second one is required by Rescheduler algorithm.

    - Marking pod as critical when priorites are enabled. To be considered critical, the pod has to:
    - Run in the `kube-system` namespace (configurable via flag)
    - Have the priorityClass set as `system-cluster-critical` or `system-node-critical`, the latter being the highest for entire cluster
    - `scheduler.alpha.kubernetes.io/critical-pod` annotation set to empty string(This will be deprecated too).
  26. tuannvm revised this gist May 13, 2018. 1 changed file with 13 additions and 12 deletions.
    25 changes: 13 additions & 12 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -37,6 +37,7 @@
    - [Notes](#notes)
    - [Basic commands](#basic-commands)
    - [jsonpath](#jsonpath)
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)

    <!-- /TOC -->

    @@ -539,18 +540,18 @@ From [link](https://github.com/kubernetes/website/blob/master/content/en/docs/re
    }
    ```

    Function | Description | Example | Result
    ----------------- | ------------------------- | ------------------------------------------------------------- | -----------------------------------------------
    text | the plain text | kind is {.kind} | kind is List
    @ | the current object | {@} | the same as input
    . or [] | child operator | {.kind} or {['kind']} | List
    .. | recursive descent | {..name} | 127.0.0.1 127.0.0.2 myself e2e
    \* | wildcard. Get all objects | {.items[*].metadata.name} | [127.0.0.1 127.0.0.2]
    [start:end :step] | subscript operator | {.users[0].name} | myself
    [,] | union operator | {.items[*]['metadata.name', 'status.capacity']} | 127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8]
    ?() | filter | {.users[?(@.name=="e2e")].user.password} | secret
    range, end | iterate list | {range .items[*]}[{.metadata.name}, {.status.capacity}] {end} | [127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]]
    '' | quote interpreted string | {range .items[*]}{.metadata.name}{'\t'}{end} | 127.0.0.1 127.0.0.2
    Function | Description | Example | Result
    ---------|--------------------|--------------------|------------------
    text | the plain text | kind is {.kind} | kind is List
    @ | the current object | {@} | the same as input
    . or [] | child operator | {.kind} or {['kind']}| List
    .. | recursive descent | {..name} | 127.0.0.1 127.0.0.2 myself e2e
    \* | wildcard. Get all objects| {.items[*].metadata.name} | [127.0.0.1 127.0.0.2]
    [start:end :step] | subscript operator | {.users[0].name}| myself
    [,] | union operator | {.items[*]['metadata.name', 'status.capacity']} | 127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8]
    ?() | filter | {.users[?(@.name=="e2e")].user.password} | secret
    range, end | iterate list | {range .items[*]}[{.metadata.name}, {.status.capacity}] {end} | [127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]]
    '' | quote interpreted string | {range .items[*]}{.metadata.name}{'\t'}{end} | 127.0.0.1 127.0.0.2

    Below are some examples using jsonpath:

  27. tuannvm revised this gist May 13, 2018. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -551,7 +551,6 @@ text | the plain text | kind is {.kind}
    ?() | filter | {.users[?(@.name=="e2e")].user.password} | secret
    range, end | iterate list | {range .items[*]}[{.metadata.name}, {.status.capacity}] {end} | [127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]]
    '' | quote interpreted string | {range .items[*]}{.metadata.name}{'\t'}{end} | 127.0.0.1 127.0.0.2
    ```

    Below are some examples using jsonpath:

  28. tuannvm revised this gist May 13, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -37,7 +37,6 @@
    - [Notes](#notes)
    - [Basic commands](#basic-commands)
    - [jsonpath](#jsonpath)
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)

    <!-- /TOC -->

    @@ -552,6 +551,7 @@ text | the plain text | kind is {.kind}
    ?() | filter | {.users[?(@.name=="e2e")].user.password} | secret
    range, end | iterate list | {range .items[*]}[{.metadata.name}, {.status.capacity}] {end} | [127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]]
    '' | quote interpreted string | {range .items[*]}{.metadata.name}{'\t'}{end} | 127.0.0.1 127.0.0.2
    ```

    Below are some examples using jsonpath:

  29. tuannvm revised this gist May 13, 2018. 1 changed file with 65 additions and 0 deletions.
    65 changes: 65 additions & 0 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -36,6 +36,7 @@
    - [Role-Based Access Control (RBAC)](#role-based-access-control-rbac)
    - [Notes](#notes)
    - [Basic commands](#basic-commands)
    - [jsonpath](#jsonpath)
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)

    <!-- /TOC -->
    @@ -498,6 +499,70 @@ kubectl -n kube-system port-forward $(kubectl get pods -n kube-system -o wide |
    kubectl -n kube-system port-forward (kubectl get pods -n kube-system -o wide | grep dashboard | awk '{print $1}') 9090
    ```

    ### jsonpath

    From [link](https://github.com/kubernetes/website/blob/master/content/en/docs/reference/kubectl/jsonpath.md)

    ```json
    {
    "kind": "List",
    "items":[
    {
    "kind":"None",
    "metadata":{"name":"127.0.0.1"},
    "status":{
    "capacity":{"cpu":"4"},
    "addresses":[{"type": "LegacyHostIP", "address":"127.0.0.1"}]
    }
    },
    {
    "kind":"None",
    "metadata":{"name":"127.0.0.2"},
    "status":{
    "capacity":{"cpu":"8"},
    "addresses":[
    {"type": "LegacyHostIP", "address":"127.0.0.2"},
    {"type": "another", "address":"127.0.0.3"}
    ]
    }
    }
    ],
    "users":[
    {
    "name": "myself",
    "user": {}
    },
    {
    "name": "e2e",
    "user": {"username": "admin", "password": "secret"}
    }
    ]
    }
    ```

    Function | Description | Example | Result
    ----------------- | ------------------------- | ------------------------------------------------------------- | -----------------------------------------------
    text | the plain text | kind is {.kind} | kind is List
    @ | the current object | {@} | the same as input
    . or [] | child operator | {.kind} or {['kind']} | List
    .. | recursive descent | {..name} | 127.0.0.1 127.0.0.2 myself e2e
    \* | wildcard. Get all objects | {.items[*].metadata.name} | [127.0.0.1 127.0.0.2]
    [start:end :step] | subscript operator | {.users[0].name} | myself
    [,] | union operator | {.items[*]['metadata.name', 'status.capacity']} | 127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8]
    ?() | filter | {.users[?(@.name=="e2e")].user.password} | secret
    range, end | iterate list | {range .items[*]}[{.metadata.name}, {.status.capacity}] {end} | [127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]]
    '' | quote interpreted string | {range .items[*]}{.metadata.name}{'\t'}{end} | 127.0.0.1 127.0.0.2

    Below are some examples using jsonpath:

    ```shell
    $ kubectl get pods -o json
    $ kubectl get pods -o=jsonpath='{@}'
    $ kubectl get pods -o=jsonpath='{.items[0]}'
    $ kubectl get pods -o=jsonpath='{.items[0].metadata.name}'
    $ kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.startTime}{"\n"}{end}'
    ```

    ### Chapter 13. Integrating storage solutions and Kubernetes

    - External service without selector (access with `external-database.svc.default.cluster` endpoint)
  30. tuannvm revised this gist May 13, 2018. 1 changed file with 7 additions and 4 deletions.
    11 changes: 7 additions & 4 deletions kubernetes-cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -34,8 +34,9 @@
    - [Volumes](#volumes)
    - [Persistent volumes](#persistent-volumes)
    - [Role-Based Access Control (RBAC)](#role-based-access-control-rbac)
    - [Basic commands](#basic-commands)
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)
    - [Notes](#notes)
    - [Basic commands](#basic-commands)
    - [Chapter 13. Integrating storage solutions and Kubernetes](#chapter-13-integrating-storage-solutions-and-kubernetes)

    <!-- /TOC -->

    @@ -455,7 +456,9 @@ Lifetime longer than any containers inside a pod.
    - non-resources endpoint (/healthz)
    - namespace resources across all namespaces

    ## Basic commands
    ## Notes

    ### Basic commands

    ```bash
    # show current context
    @@ -495,7 +498,7 @@ kubectl -n kube-system port-forward $(kubectl get pods -n kube-system -o wide |
    kubectl -n kube-system port-forward (kubectl get pods -n kube-system -o wide | grep dashboard | awk '{print $1}') 9090
    ```

    ## Chapter 13. Integrating storage solutions and Kubernetes
    ### Chapter 13. Integrating storage solutions and Kubernetes

    - External service without selector (access with `external-database.svc.default.cluster` endpoint)