├── exam-assets ├── current-version │ ├── templates │ │ ├── configmap.yaml │ │ ├── serviceaccount.yaml │ │ ├── service.yaml │ │ └── deployment.yaml │ ├── Chart.yaml │ └── values.yaml ├── nightly-build │ ├── templates │ │ ├── configmap.yaml │ │ ├── serviceaccount.yaml │ │ ├── service.yaml │ │ └── deployment.yaml │ ├── Chart.yaml │ └── values.yaml ├── view-app │ ├── templates │ │ ├── serviceaccount.yaml │ │ ├── service.yaml │ │ └── deployment.yaml │ ├── .helmignore │ ├── Chart.yaml │ └── values.yaml ├── filter-app │ ├── templates │ │ ├── serviceaccount.yaml │ │ ├── service.yaml │ │ └── deployment.yaml │ ├── .helmignore │ ├── Chart.yaml │ └── values.yaml ├── catalog-app │ ├── templates │ │ ├── serviceaccount.yaml │ │ ├── service.yaml │ │ └── deployment.yaml │ ├── .helmignore │ ├── Chart.yaml │ └── values.yaml ├── secrets-app │ ├── templates │ │ ├── serviceaccount.yaml │ │ ├── service.yaml │ │ └── deployment.yaml │ ├── .helmignore │ ├── Chart.yaml │ └── values.yaml ├── q11.sh ├── app-namespaces.yaml └── q10.sh ├── 99 - Useful Links ├── 2. StenlyTU.md ├── 3. ahmetb.md └── 1. stretchcloud.md ├── 04 - Application Lifecycle Management └── Use Describe.md ├── 05 - Cluster Maintenance ├── Kubernetes API.md └── ETCD Help.md ├── 07 - Storage └── PVCs-in-PODs.md ├── 08 - Networking ├── CNI-Plugin.md └── Annotations-Nginx.md ├── 01 - Core Concepts ├── ETCD - Commands.md └── Imperative.md ├── 02- Scheduling └── Object Editing.md └── 06 - Security └── basic-auth.md /exam-assets/current-version/templates/configmap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | metadata: 3 | name: {{ .Values.configMap.name }} 4 | kind: ConfigMap 5 | data: 6 | ROCKET_SIZE: big 7 | -------------------------------------------------------------------------------- /exam-assets/nightly-build/templates/configmap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | metadata: 3 | name: {{ .Values.configMap.name }} 4 | kind: ConfigMap 5 | data: 6 | ROCKET_SIZE: small 7 | -------------------------------------------------------------------------------- /99 - Useful Links/2. StenlyTU.md: -------------------------------------------------------------------------------- 1 | https://github.com/StenlyTU/K8s-training-official 2 | > 50 задачек для самостоятельного выполнения, на любой вкус (так же выполняются на своей инфре) 3 | -------------------------------------------------------------------------------- /exam-assets/view-app/templates/serviceaccount.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: {{ .Values.serviceAccount.name }} 5 | labels: 6 | app: view-global-app 7 | -------------------------------------------------------------------------------- /exam-assets/filter-app/templates/serviceaccount.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: {{ .Values.serviceAccount.name }} 5 | labels: 6 | app: filtration-east-app 7 | -------------------------------------------------------------------------------- /exam-assets/catalog-app/templates/serviceaccount.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: {{ .Values.serviceAccount.name }} 5 | labels: 6 | app: catalog-eu-only-app 7 | -------------------------------------------------------------------------------- /exam-assets/nightly-build/templates/serviceaccount.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: {{ .Values.serviceAccount.name }} 5 | labels: 6 | app: messenger-front-02-sa 7 | -------------------------------------------------------------------------------- /exam-assets/secrets-app/templates/serviceaccount.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: {{ .Values.serviceAccount.name }} 5 | labels: 6 | app: "secrets-global-app" 7 | -------------------------------------------------------------------------------- /exam-assets/current-version/templates/serviceaccount.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: {{ .Values.serviceAccount.name }} 5 | labels: 6 | app: messenger-front-01-sa 7 | -------------------------------------------------------------------------------- /99 - Useful Links/3. ahmetb.md: -------------------------------------------------------------------------------- 1 | https://github.com/ahmetb/kubernetes-network-policy-recipes 2 | >Хороший материал по `networkpolicies` с наглядными примерами (нельзя использовать ссылку на экз., но потренироваться по ней стоит) 3 | -------------------------------------------------------------------------------- /99 - Useful Links/1. stretchcloud.md: -------------------------------------------------------------------------------- 1 | https://github.com/stretchcloud/cka-lab-practice 2 | > Хорошие задачки для самостоятельного выполнения (единственный момент: инфраструктуру под лабы создаёте сами (можно он премис, можно в облаках, на своё усмотрение)) 3 | -------------------------------------------------------------------------------- /exam-assets/current-version/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: {{ .Values.service.name }} 5 | spec: 6 | ports: 7 | - port: 8080 8 | protocol: TCP 9 | targetPort: 8080 10 | selector: 11 | version: v1-cds 12 | type: {{ .Values.service.type }} 13 | -------------------------------------------------------------------------------- /exam-assets/nightly-build/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: {{ .Values.service.name }} 5 | spec: 6 | ports: 7 | - port: 8080 8 | protocol: TCP 9 | targetPort: 8080 10 | selector: 11 | version: v2-cds 12 | type: {{ .Values.service.type }} 13 | -------------------------------------------------------------------------------- /exam-assets/q11.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd /tmp/.script/exam-assets 4 | 5 | # Define the commands to deploy the helm chart 6 | helm install messenger-front-01 --namespace=default ./current-version 7 | 8 | # Moving the new version app directory 9 | mv /tmp/.script/exam-assets/nightly-build /root/ 10 | 11 | # Removing the script 12 | rm -rf /tmp/.script 13 | -------------------------------------------------------------------------------- /exam-assets/view-app/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: {{ .Values.service.name }} 5 | labels: 6 | app: view-global-app-svc 7 | spec: 8 | type: {{ .Values.service.type }} 9 | ports: 10 | - port: {{ .Values.service.port }} 11 | targetPort: http 12 | protocol: TCP 13 | name: http 14 | selector: 15 | app: view-global-app 16 | -------------------------------------------------------------------------------- /exam-assets/app-namespaces.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Namespace 4 | metadata: 5 | name: filtration-east 6 | 7 | --- 8 | apiVersion: v1 9 | kind: Namespace 10 | metadata: 11 | name: secrets-global 12 | 13 | --- 14 | apiVersion: v1 15 | kind: Namespace 16 | metadata: 17 | name: view-global 18 | 19 | --- 20 | apiVersion: v1 21 | kind: Namespace 22 | metadata: 23 | name: catalog-eu-only 24 | -------------------------------------------------------------------------------- /exam-assets/filter-app/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: {{ .Values.service.name }} 5 | labels: 6 | app: filtration-east-pd-svc 7 | spec: 8 | type: {{ .Values.service.type }} 9 | ports: 10 | - port: {{ .Values.service.port }} 11 | targetPort: http 12 | protocol: TCP 13 | name: http 14 | selector: 15 | app: filtration-east-app 16 | -------------------------------------------------------------------------------- /exam-assets/secrets-app/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: {{ .Values.service.name }} 5 | labels: 6 | app: secrets-global-app-svc 7 | spec: 8 | type: {{ .Values.service.type }} 9 | ports: 10 | - port: {{ .Values.service.port }} 11 | targetPort: http 12 | protocol: TCP 13 | name: http 14 | selector: 15 | app: secrets-global-app 16 | -------------------------------------------------------------------------------- /exam-assets/catalog-app/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: {{ .Values.service.name }} 5 | labels: 6 | app: catalog-eu-only-app-svc 7 | spec: 8 | type: {{ .Values.service.type }} 9 | ports: 10 | - port: {{ .Values.service.port }} 11 | targetPort: http 12 | protocol: TCP 13 | name: http 14 | selector: 15 | app: catalog-eu-only-app 16 | -------------------------------------------------------------------------------- /exam-assets/view-app/.helmignore: -------------------------------------------------------------------------------- 1 | # Patterns to ignore when building packages. 2 | # This supports shell glob matching, relative path matching, and 3 | # negation (prefixed with !). Only one pattern per line. 4 | .DS_Store 5 | # Common VCS dirs 6 | .git/ 7 | .gitignore 8 | .bzr/ 9 | .bzrignore 10 | .hg/ 11 | .hgignore 12 | .svn/ 13 | # Common backup files 14 | *.swp 15 | *.bak 16 | *.tmp 17 | *.orig 18 | *~ 19 | # Various IDEs 20 | .project 21 | .idea/ 22 | *.tmproj 23 | .vscode/ 24 | -------------------------------------------------------------------------------- /exam-assets/catalog-app/.helmignore: -------------------------------------------------------------------------------- 1 | # Patterns to ignore when building packages. 2 | # This supports shell glob matching, relative path matching, and 3 | # negation (prefixed with !). Only one pattern per line. 4 | .DS_Store 5 | # Common VCS dirs 6 | .git/ 7 | .gitignore 8 | .bzr/ 9 | .bzrignore 10 | .hg/ 11 | .hgignore 12 | .svn/ 13 | # Common backup files 14 | *.swp 15 | *.bak 16 | *.tmp 17 | *.orig 18 | *~ 19 | # Various IDEs 20 | .project 21 | .idea/ 22 | *.tmproj 23 | .vscode/ 24 | -------------------------------------------------------------------------------- /exam-assets/filter-app/.helmignore: -------------------------------------------------------------------------------- 1 | # Patterns to ignore when building packages. 2 | # This supports shell glob matching, relative path matching, and 3 | # negation (prefixed with !). Only one pattern per line. 4 | .DS_Store 5 | # Common VCS dirs 6 | .git/ 7 | .gitignore 8 | .bzr/ 9 | .bzrignore 10 | .hg/ 11 | .hgignore 12 | .svn/ 13 | # Common backup files 14 | *.swp 15 | *.bak 16 | *.tmp 17 | *.orig 18 | *~ 19 | # Various IDEs 20 | .project 21 | .idea/ 22 | *.tmproj 23 | .vscode/ 24 | -------------------------------------------------------------------------------- /exam-assets/secrets-app/.helmignore: -------------------------------------------------------------------------------- 1 | # Patterns to ignore when building packages. 2 | # This supports shell glob matching, relative path matching, and 3 | # negation (prefixed with !). Only one pattern per line. 4 | .DS_Store 5 | # Common VCS dirs 6 | .git/ 7 | .gitignore 8 | .bzr/ 9 | .bzrignore 10 | .hg/ 11 | .hgignore 12 | .svn/ 13 | # Common backup files 14 | *.swp 15 | *.bak 16 | *.tmp 17 | *.orig 18 | *~ 19 | # Various IDEs 20 | .project 21 | .idea/ 22 | *.tmproj 23 | .vscode/ 24 | -------------------------------------------------------------------------------- /04 - Application Lifecycle Management/Use Describe.md: -------------------------------------------------------------------------------- 1 | # A Small Tip 2 | ## Вот небольшой совет 3 | 4 | На экзамене ты не узнаешь, правильно ли ты все сделал. Это отличается от того, как происходит в наших лабораторных тестах. Тебе нужно приучить себя самому проверять свою работу. 5 | 6 | Например, если вопрос заключается в создании POD с определенным образом, привыкни сразу же после создания запускать команду 7 | ```sh 8 | kubectl describe pod 9 | ``` 10 | чтобы убедиться, что POD создан с правильным именем и правильным образом 11 | -------------------------------------------------------------------------------- /exam-assets/nightly-build/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | labels: 5 | version: v2-cds 6 | name: {{ .Values.name }} 7 | spec: 8 | replicas: {{ .Values.replicaCount }} 9 | selector: 10 | matchLabels: 11 | version: v2-cds 12 | template: 13 | metadata: 14 | labels: 15 | version: v2-cds 16 | spec: 17 | containers: 18 | - image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" 19 | name: messenger-front-02 20 | envFrom: 21 | - configMapRef: 22 | name: {{ .Values.configMap.name }} 23 | -------------------------------------------------------------------------------- /exam-assets/current-version/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | labels: 5 | version: v1-cds 6 | name: {{ .Values.name }} 7 | spec: 8 | replicas: {{ .Values.replicaCount }} 9 | selector: 10 | matchLabels: 11 | version: v1-cds 12 | template: 13 | metadata: 14 | labels: 15 | version: v1-cds 16 | spec: 17 | containers: 18 | - image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" 19 | name: messenger-front-01 20 | envFrom: 21 | - configMapRef: 22 | name: {{ .Values.configMap.name }} 23 | -------------------------------------------------------------------------------- /exam-assets/view-app/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: view-global-app 5 | labels: 6 | app: view-global-app 7 | spec: 8 | replicas: {{ .Values.replicaCount }} 9 | selector: 10 | matchLabels: 11 | app: view-global-app 12 | template: 13 | metadata: 14 | labels: 15 | app: view-global-app 16 | spec: 17 | serviceAccountName: {{ .Values.serviceAccount.name }} 18 | containers: 19 | - name: {{ .Chart.Name }} 20 | image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" 21 | imagePullPolicy: {{ .Values.image.pullPolicy }} 22 | -------------------------------------------------------------------------------- /exam-assets/secrets-app/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: secrets-global-app 5 | labels: 6 | app: secrets-global-app 7 | spec: 8 | replicas: {{ .Values.replicaCount }} 9 | selector: 10 | matchLabels: 11 | app: secrets-global-app 12 | template: 13 | metadata: 14 | labels: 15 | app: secrets-global-app 16 | spec: 17 | serviceAccountName: {{ .Values.serviceAccount.name }} 18 | containers: 19 | - name: {{ .Chart.Name }} 20 | image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" 21 | imagePullPolicy: {{ .Values.image.pullPolicy }} 22 | -------------------------------------------------------------------------------- /exam-assets/catalog-app/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: catalog-eu-only-app 5 | labels: 6 | app: catalog-eu-only-app 7 | spec: 8 | replicas: {{ .Values.replicaCount }} 9 | selector: 10 | matchLabels: 11 | app: catalog-eu-only-app 12 | template: 13 | metadata: 14 | labels: 15 | app: catalog-eu-only-app 16 | spec: 17 | serviceAccountName: {{ .Values.serviceAccount.name }} 18 | containers: 19 | - name: {{ .Chart.Name }} 20 | image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" 21 | imagePullPolicy: {{ .Values.image.pullPolicy }} 22 | -------------------------------------------------------------------------------- /exam-assets/filter-app/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: filtration-east-app 5 | labels: 6 | app: filtration-east-app 7 | spec: 8 | replicas: {{ .Values.replicaCount }} 9 | selector: 10 | matchLabels: 11 | app: filtration-east-app 12 | template: 13 | metadata: 14 | labels: 15 | app: filtration-east-app 16 | spec: 17 | serviceAccountName: {{ .Values.serviceAccount.name }} 18 | containers: 19 | - name: {{ .Chart.Name }} 20 | image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" 21 | imagePullPolicy: {{ .Values.image.pullPolicy }} 22 | -------------------------------------------------------------------------------- /05 - Cluster Maintenance/Kubernetes API.md: -------------------------------------------------------------------------------- 1 | # Kubernetes API 2 | 3 | Здесь несколько ссылок, они не нужны для экзамена 4 | 5 | Но если тебе интересны принципы развития Kubernetes, посмотри на досуге 6 | 7 | [https://kubernetes.io/docs/concepts/overview/kubernetes-api/](https://kubernetes.io/docs/concepts/overview/kubernetes-api/) 8 | 9 | [https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md) 10 | 11 | [https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api_changes.md](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api_changes.md) 12 | -------------------------------------------------------------------------------- /exam-assets/nightly-build/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v2 2 | name: webpage-server-02 3 | description: A Helm chart for Rockets messenger 4 | type: application 5 | 6 | # This is the chart version. This version number should be incremented each time you make changes 7 | # to the chart and its templates, including the app version. 8 | # Versions are expected to follow Semantic Versioning (https://semver.org/) 9 | version: 0.1.1 10 | 11 | # This is the version number of the application being deployed. This version number should be 12 | # incremented each time you make changes to the application. Versions are not expected to 13 | # follow Semantic Versioning. They should reflect the version the application is using. 14 | # It is recommended to use it with quotes. 15 | appVersion: "v2" 16 | -------------------------------------------------------------------------------- /exam-assets/current-version/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v2 2 | name: messenger-front-01 3 | description: A Helm chart for Rockets messenger 4 | type: application 5 | 6 | # This is the chart version. This version number should be incremented each time you make changes 7 | # to the chart and its templates, including the app version. 8 | # Versions are expected to follow Semantic Versioning (https://semver.org/) 9 | version: 0.1.0 10 | 11 | # This is the version number of the application being deployed. This version number should be 12 | # incremented each time you make changes to the application. Versions are not expected to 13 | # follow Semantic Versioning. They should reflect the version the application is using. 14 | # It is recommended to use it with quotes. 15 | appVersion: "v1" 16 | -------------------------------------------------------------------------------- /07 - Storage/PVCs-in-PODs.md: -------------------------------------------------------------------------------- 1 | # Using PVCs in PODs 2 | После создания PVC используй его в файле определения POD, указав имя PVC в разделе persistentVolumeClaim в секции `volumes` следующим образом: 3 | ``` 4 | apiVersion: v1 5 | kind: Pod 6 | metadata: 7 | name: mypod 8 | spec: 9 | containers: 10 | - name: myfrontend 11 | image: nginx 12 | volumeMounts: 13 | - mountPath: "/var/www/html" 14 | name: mypd 15 | volumes: 16 | - name: mypd 17 | persistentVolumeClaim: 18 | claimName: myclaim 19 | ``` 20 | 21 | То же самое верно для ReplicaSets или Deployments. Добавь это в раздел template POD 22 | 23 | [https://kubernetes.io/docs/concepts/storage/persistent-volumes/#claims-as-volumes](https://kubernetes.io/docs/concepts/storage/persistent-volumes/#claims-as-volumes) 24 | -------------------------------------------------------------------------------- /exam-assets/current-version/values.yaml: -------------------------------------------------------------------------------- 1 | # Default values for webapp-rockets. 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | 5 | replicaCount: 2 6 | 7 | image: 8 | repository: rotorocloud/simple-webapp-rockets 9 | pullPolicy: IfNotPresent 10 | # Overrides the image tag whose default is the chart appVersion. 11 | tag: "v1" 12 | 13 | imagePullSecrets: [] 14 | 15 | name: messenger-front-01 16 | 17 | serviceAccount: 18 | # Specifies whether a service account should be created 19 | create: false 20 | # Annotations to add to the service account 21 | annotations: {} 22 | # The name of the service account to use. 23 | # If not set and create is true, a name is generated using the fullname template 24 | name: messenger-front-01-sa 25 | 26 | service: 27 | name: messenger-front-01-svc 28 | type: ClusterIP 29 | port: 8080 30 | 31 | environment: development 32 | 33 | configMap: 34 | name: messenger-configmap-10 35 | -------------------------------------------------------------------------------- /exam-assets/nightly-build/values.yaml: -------------------------------------------------------------------------------- 1 | # Default values for webapp-rockets. 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | 5 | replicaCount: 3 6 | 7 | image: 8 | repository: rotorocloud/simple-webapp-rockets 9 | pullPolicy: IfNotPresent 10 | # Overrides the image tag whose default is the chart appVersion. 11 | tag: "v2" 12 | 13 | imagePullSecrets: [] 14 | 15 | name: messenger-front-02 16 | 17 | serviceAccount: 18 | # Specifies whether a service account should be created 19 | create: false 20 | # Annotations to add to the service account 21 | annotations: {} 22 | # The name of the service account to use. 23 | # If not set and create is true, a name is generated using the fullname template 24 | name: messenger-sa-app 25 | 26 | service: 27 | name: messenger-front-02-svc 28 | type: NodePort 29 | port: 8080 30 | 31 | 32 | environment: development 33 | 34 | 35 | configMap: 36 | name: messenger-configmap-11 37 | -------------------------------------------------------------------------------- /exam-assets/q10.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd /tmp/.ques10/exam-assets/ 4 | 5 | # Define the commands to be executed 6 | command1="helm install filtration-east-app --namespace=filtration-east ./filter-app" 7 | command2="helm install secrets-global-app --namespace=secrets-global ./secrets-app" 8 | command3="helm install view-global-app --namespace=view-global ./view-app" 9 | command4="helm install catalog-eu-only --namespace=catalog-eu-only ./catalog-app" 10 | 11 | sleep 2 12 | 13 | # Loop until all commands have executed successfully 14 | while true; do 15 | # Execute the commands 16 | $command1 && $command2 && $command3 && $command4 17 | 18 | # Check if any command failed 19 | if [ $? -ne 0 ]; then 20 | # If a command failed, print an error message and try once again and then exit the loop 21 | echo "One or more commands failed. Retrying..." 22 | $command1 && $command2 && $command3 && $command4 23 | break 24 | 25 | else 26 | # If all commands succeeded, exit the loop 27 | break 28 | fi 29 | done 30 | 31 | echo "All commands executed successfully." 32 | 33 | rm -rf /tmp/.ques10 34 | -------------------------------------------------------------------------------- /exam-assets/view-app/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v2 2 | name: view-app 3 | description: A Helm chart for Kubernetes 4 | 5 | # A chart can be either an 'application' or a 'library' chart. 6 | # 7 | # Application charts are a collection of templates that can be packaged into versioned archives 8 | # to be deployed. 9 | # 10 | # Library charts provide useful utilities or functions for the chart developer. They're included as 11 | # a dependency of application charts to inject those utilities and functions into the rendering 12 | # pipeline. Library charts do not define any templates and therefore cannot be deployed. 13 | type: application 14 | 15 | # This is the chart version. This version number should be incremented each time you make changes 16 | # to the chart and its templates, including the app version. 17 | # Versions are expected to follow Semantic Versioning (https://semver.org/) 18 | version: 0.1.0 19 | 20 | # This is the version number of the application being deployed. This version number should be 21 | # incremented each time you make changes to the application. Versions are not expected to 22 | # follow Semantic Versioning. They should reflect the version the application is using. 23 | # It is recommended to use it with quotes. 24 | appVersion: "0.0.1" 25 | -------------------------------------------------------------------------------- /exam-assets/catalog-app/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v2 2 | name: catalog-app 3 | description: A Helm chart for Kubernetes 4 | 5 | # A chart can be either an 'application' or a 'library' chart. 6 | # 7 | # Application charts are a collection of templates that can be packaged into versioned archives 8 | # to be deployed. 9 | # 10 | # Library charts provide useful utilities or functions for the chart developer. They're included as 11 | # a dependency of application charts to inject those utilities and functions into the rendering 12 | # pipeline. Library charts do not define any templates and therefore cannot be deployed. 13 | type: application 14 | 15 | # This is the chart version. This version number should be incremented each time you make changes 16 | # to the chart and its templates, including the app version. 17 | # Versions are expected to follow Semantic Versioning (https://semver.org/) 18 | version: 0.1.0 19 | 20 | # This is the version number of the application being deployed. This version number should be 21 | # incremented each time you make changes to the application. Versions are not expected to 22 | # follow Semantic Versioning. They should reflect the version the application is using. 23 | # It is recommended to use it with quotes. 24 | appVersion: "0.0.1" 25 | -------------------------------------------------------------------------------- /exam-assets/filter-app/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v2 2 | name: filter-app 3 | description: A Helm chart for Kubernetes 4 | 5 | # A chart can be either an 'application' or a 'library' chart. 6 | # 7 | # Application charts are a collection of templates that can be packaged into versioned archives 8 | # to be deployed. 9 | # 10 | # Library charts provide useful utilities or functions for the chart developer. They're included as 11 | # a dependency of application charts to inject those utilities and functions into the rendering 12 | # pipeline. Library charts do not define any templates and therefore cannot be deployed. 13 | type: application 14 | 15 | # This is the chart version. This version number should be incremented each time you make changes 16 | # to the chart and its templates, including the app version. 17 | # Versions are expected to follow Semantic Versioning (https://semver.org/) 18 | version: 0.1.0 19 | 20 | # This is the version number of the application being deployed. This version number should be 21 | # incremented each time you make changes to the application. Versions are not expected to 22 | # follow Semantic Versioning. They should reflect the version the application is using. 23 | # It is recommended to use it with quotes. 24 | appVersion: "0.0.1" 25 | -------------------------------------------------------------------------------- /exam-assets/secrets-app/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v2 2 | name: secrets-app 3 | description: A Helm chart for Kubernetes 4 | 5 | # A chart can be either an 'application' or a 'library' chart. 6 | # 7 | # Application charts are a collection of templates that can be packaged into versioned archives 8 | # to be deployed. 9 | # 10 | # Library charts provide useful utilities or functions for the chart developer. They're included as 11 | # a dependency of application charts to inject those utilities and functions into the rendering 12 | # pipeline. Library charts do not define any templates and therefore cannot be deployed. 13 | type: application 14 | 15 | # This is the chart version. This version number should be incremented each time you make changes 16 | # to the chart and its templates, including the app version. 17 | # Versions are expected to follow Semantic Versioning (https://semver.org/) 18 | version: 0.1.0 19 | 20 | # This is the version number of the application being deployed. This version number should be 21 | # incremented each time you make changes to the application. Versions are not expected to 22 | # follow Semantic Versioning. They should reflect the version the application is using. 23 | # It is recommended to use it with quotes. 24 | appVersion: "0.0.2" 25 | -------------------------------------------------------------------------------- /05 - Cluster Maintenance/ETCD Help.md: -------------------------------------------------------------------------------- 1 | # ETCDCTL 2 | `etcdctl` - это клиент командной строки для ETCD 3 | 4 | Во всех наших практических занятиях Kubernetes, база данных типа "ключ-значение" ETCD развернута как static pod на мастер-узле. Используемая версия - v3 5 | 6 | Чтобы использовать etcdctl для таких задач, как резервное копирование и восстановление, убедись, что вы установил переменную `ETCDCTL_API` в `3`. 7 | 8 | Добиться этого можно, экспортировав переменную `ETCDCTL_API` перед использованием клиента `etcdctl`. Это можно сделать следующим образом: 9 | ```sh 10 | export ETCDCTL_API=3 11 | ``` 12 | 13 | Чтобы увидеть все опции для подкоманды, используй флаг `-h` или `--help` 14 | 15 | Например, если ты хочешь сделать snapshot, используй: 16 | ```sh 17 | etcdctl snapshot save -h 18 | ``` 19 | и запомни обязательные параметры из вывода команды 20 | # 21 | Поскольку у база данных ETCD включен TLS, следующие параметры являются обязательными: 22 | 23 | `--cacert` проверяет сертификаты серверов с поддержкой TLS с CA 24 | 25 | `--cert` идентифицировать клиента с помощью этого файла сертификата TLS 26 | 27 | `--endpoints` = **[127.0.0.1:2379]**. Это значение по умолчанию, поскольку ETCD работает на мастере узле и доступна на `localhost:2379` 28 | 29 | `--key` идентифицировать клиента с помощью этого файла ключа TLS 30 | # 31 | Аналогичным образом используйте параметр справки для восстановления из моментального снимка, чтобы увидеть все доступные параметры для восстановления резервной копии 32 | ```sh 33 | etcdctl snapshot restore -h 34 | ``` 35 | 36 | Подробное объяснение того, как использовать инструмент `etcdctl` и работать с флагами `-h`, можно найти в видеоролике-решении лабораторой о резервном копировании и восстановлении 37 | -------------------------------------------------------------------------------- /08 - Networking/CNI-Plugin.md: -------------------------------------------------------------------------------- 1 | # About CNI and CKA Exam 2 | 3 | ## Важный совет по развертыванию сетевых плагинов в кластере Kubernetes 4 | 5 | Далее в лабораторных работах мы будем работать с сетевыми аддонами. Это включает установку сетевого плагина в кластер. Хотя мы использовали `weave-net` в качестве примера, имей в виду, что можно использовать любой из описанных здесь плагинов: 6 | 7 | [https://kubernetes.io/docs/concepts/cluster-administration/addons/](https://kubernetes.io/docs/concepts/cluster-administration/addons/) 8 | 9 | [https://kubernetes.io/docs/concepts/cluster-administration/networking/#how-to-implement-the-kubernetes-networking-model](https://kubernetes.io/docs/concepts/cluster-administration/networking/#how-to-implement-the-kubernetes-networking-model) 10 | 11 | На экзамене CKA для ответа на вопрос, требующий развертывания сетевого дополнения, если не будет указано иное, можно использовать любое из решений, описанных в приведенной выше ссылке 12 | 13 | Однако в настоящее время документация не содержит прямых ссылок на точную команду, которая будет использоваться для развертывания стороннего сетевого дополнения 14 | 15 | Приведенные выше ссылки перенаправляют на сторонние сайты или репозитории GitHub, которые нельзя использовать на экзамене. Это было сделано намеренно, чтобы содержание документации Kubernetes не зависело от поставщика. 16 | 17 | На данный момент в документации есть еще одно место, где можно найти точную команду для развертывания плагина `Weave Network`: 18 | 19 | [https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/high-availability/#steps-for-the-first-control-plane-node](https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/high-availability/#steps-for-the-first-control-plane-node) 20 | 21 | Там в поле `step 2` 22 | -------------------------------------------------------------------------------- /exam-assets/view-app/values.yaml: -------------------------------------------------------------------------------- 1 | # Default values for view-global-app. 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | 5 | replicaCount: 1 6 | 7 | image: 8 | repository: rotorocloud/simple-webapp-rockets 9 | pullPolicy: IfNotPresent 10 | # Overrides the image tag whose default is the chart appVersion. 11 | tag: "v3" 12 | 13 | serviceAccount: 14 | # Specifies whether a service account should be created 15 | create: true 16 | # Annotations to add to the service account 17 | annotations: {} 18 | # The name of the service account to use. 19 | # If not set and create is true, a name is generated using the fullname template 20 | name: "view-global-sa" 21 | 22 | podAnnotations: {} 23 | 24 | podSecurityContext: {} 25 | # fsGroup: 2000 26 | 27 | securityContext: {} 28 | # capabilities: 29 | # drop: 30 | # - ALL 31 | # readOnlyRootFilesystem: true 32 | # runAsNonRoot: true 33 | # runAsUser: 1000 34 | 35 | service: 36 | name: view-global-svc 37 | type: NodePort 38 | port: 80 39 | 40 | 41 | resources: {} 42 | # We usually recommend not to specify default resources and to leave this as a conscious 43 | # choice for the user. This also increases chances charts run on environments with little 44 | # resources, such as Minikube. If you do want to specify resources, uncomment the following 45 | # lines, adjust them as necessary, and remove the curly braces after 'resources:'. 46 | # limits: 47 | # cpu: 100m 48 | # memory: 128Mi 49 | # requests: 50 | # cpu: 100m 51 | # memory: 128Mi 52 | 53 | autoscaling: 54 | enabled: false 55 | minReplicas: 1 56 | maxReplicas: 100 57 | targetCPUUtilizationPercentage: 80 58 | # targetMemoryUtilizationPercentage: 80 59 | 60 | nodeSelector: {} 61 | 62 | tolerations: [] 63 | 64 | affinity: {} 65 | -------------------------------------------------------------------------------- /exam-assets/catalog-app/values.yaml: -------------------------------------------------------------------------------- 1 | # Default values for catalog-eu-only-apd. 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | 5 | replicaCount: 4 6 | 7 | image: 8 | repository: rotorocloud/simple-webapp-rockets 9 | pullPolicy: IfNotPresent 10 | # Overrides the image tag whose default is the chart appVersion. 11 | tag: "v1" 12 | 13 | imagePullSecrets: [] 14 | nameOverride: "" 15 | fullnameOverride: "" 16 | 17 | serviceAccount: 18 | # Specifies whether a service account should be created 19 | create: true 20 | # Annotations to add to the service account 21 | annotations: {} 22 | # The name of the service account to use. 23 | # If not set and create is true, a name is generated using the fullname template 24 | name: "catalog-eu-only-sa" 25 | 26 | podAnnotations: {} 27 | 28 | podSecurityContext: {} 29 | # fsGroup: 2000 30 | 31 | securityContext: {} 32 | # capabilities: 33 | # drop: 34 | # - ALL 35 | # readOnlyRootFilesystem: true 36 | # runAsNonRoot: true 37 | # runAsUser: 1000 38 | 39 | service: 40 | name: "catalog-eu-only-svc" 41 | type: NodePort 42 | port: 80 43 | 44 | resources: {} 45 | # We usually recommend not to specify default resources and to leave this as a conscious 46 | # choice for the user. This also increases chances charts run on environments with little 47 | # resources, such as Minikube. If you do want to specify resources, uncomment the following 48 | # lines, adjust them as necessary, and remove the curly braces after 'resources:'. 49 | # limits: 50 | # cpu: 100m 51 | # memory: 128Mi 52 | # requests: 53 | # cpu: 100m 54 | # memory: 128Mi 55 | 56 | autoscaling: 57 | enabled: false 58 | minReplicas: 1 59 | maxReplicas: 100 60 | targetCPUUtilizationPercentage: 80 61 | # targetMemoryUtilizationPercentage: 80 62 | 63 | nodeSelector: {} 64 | 65 | tolerations: [] 66 | 67 | affinity: {} 68 | -------------------------------------------------------------------------------- /exam-assets/secrets-app/values.yaml: -------------------------------------------------------------------------------- 1 | # Default values for secrets-global-app. 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | 5 | replicaCount: 2 6 | 7 | image: 8 | repository: rotorocloud/simple-webapp-rockets 9 | pullPolicy: IfNotPresent 10 | # Overrides the image tag whose default is the chart appVersion. 11 | tag: "v2" 12 | 13 | imagePullSecrets: [] 14 | nameOverride: "" 15 | fullnameOverride: "" 16 | 17 | serviceAccount: 18 | # Specifies whether a service account should be created 19 | create: true 20 | # Annotations to add to the service account 21 | annotations: {} 22 | # The name of the service account to use. 23 | # If not set and create is true, a name is generated using the fullname template 24 | name: "secrets-global-sa" 25 | 26 | podAnnotations: {} 27 | 28 | podSecurityContext: {} 29 | # fsGroup: 2000 30 | 31 | securityContext: {} 32 | # capabilities: 33 | # drop: 34 | # - ALL 35 | # readOnlyRootFilesystem: true 36 | # runAsNonRoot: true 37 | # runAsUser: 1000 38 | 39 | service: 40 | name: "secrets-global-svc" 41 | type: NodePort 42 | port: 80 43 | 44 | resources: {} 45 | # We usually recommend not to specify default resources and to leave this as a conscious 46 | # choice for the user. This also increases chances charts run on environments with little 47 | # resources, such as Minikube. If you do want to specify resources, uncomment the following 48 | # lines, adjust them as necessary, and remove the curly braces after 'resources:'. 49 | # limits: 50 | # cpu: 100m 51 | # memory: 128Mi 52 | # requests: 53 | # cpu: 100m 54 | # memory: 128Mi 55 | 56 | autoscaling: 57 | enabled: false 58 | minReplicas: 1 59 | maxReplicas: 100 60 | targetCPUUtilizationPercentage: 80 61 | # targetMemoryUtilizationPercentage: 80 62 | 63 | nodeSelector: {} 64 | 65 | tolerations: [] 66 | 67 | affinity: {} 68 | -------------------------------------------------------------------------------- /exam-assets/filter-app/values.yaml: -------------------------------------------------------------------------------- 1 | # Default values for filtration-east-app. 2 | # This is a YAML-formatted file. 3 | # Declare variables to be passed into your templates. 4 | 5 | replicaCount: 1 6 | 7 | image: 8 | repository: rotorocloud/rocket-counter 9 | pullPolicy: IfNotPresent 10 | # Overrides the image tag whose default is the chart appVersion. 11 | tag: "latest" 12 | 13 | imagePullSecrets: [] 14 | nameOverride: "" 15 | fullnameOverride: "" 16 | 17 | serviceAccount: 18 | # Specifies whether a service account should be created 19 | create: true 20 | # Annotations to add to the service account 21 | annotations: {} 22 | # The name of the service account to use. 23 | # If not set and create is true, a name is generated using the fullname template 24 | name: "filtration-east-sa" 25 | 26 | podAnnotations: {} 27 | 28 | podSecurityContext: {} 29 | # fsGroup: 2000 30 | 31 | securityContext: {} 32 | # capabilities: 33 | # drop: 34 | # - ALL 35 | # readOnlyRootFilesystem: true 36 | # runAsNonRoot: true 37 | # runAsUser: 1000 38 | 39 | service: 40 | name: filtration-east-app-svc 41 | type: ClusterIP 42 | port: 8080 43 | 44 | resources: {} 45 | # We usually recommend not to specify default resources and to leave this as a conscious 46 | # choice for the user. This also increases chances charts run on environments with little 47 | # resources, such as Minikube. If you do want to specify resources, uncomment the following 48 | # lines, adjust them as necessary, and remove the curly braces after 'resources:'. 49 | # limits: 50 | # cpu: 100m 51 | # memory: 128Mi 52 | # requests: 53 | # cpu: 100m 54 | # memory: 128Mi 55 | 56 | autoscaling: 57 | enabled: false 58 | minReplicas: 1 59 | maxReplicas: 100 60 | targetCPUUtilizationPercentage: 80 61 | # targetMemoryUtilizationPercentage: 80 62 | 63 | nodeSelector: {} 64 | 65 | tolerations: [] 66 | 67 | affinity: {} 68 | -------------------------------------------------------------------------------- /01 - Core Concepts/ETCD - Commands.md: -------------------------------------------------------------------------------- 1 | # ETCD - Commands 2 | 3 | Здесь дополнительная информация об утилите ETCDCTL. 4 | 5 | ETCDCTL - это CLI-инструмент, используемый для взаимодействия с ETCD. 6 | 7 | ETCDCTL может взаимодействовать с сервером ETCD, используя 2 версии API - версию 2 и версию 3. По умолчанию используется версия 2. Каждая версия имеет разные наборы команд. 8 | 9 | Например, ETCDCTL версии 2 поддерживает следующие команды: 10 | 11 | ```sh 12 | etcdctl backup 13 | etcdctl cluster-health 14 | etcdctl mk 15 | etcdctl mkdir 16 | etcdctl set 17 | ``` 18 | В то время как в версии 3 команды другие: 19 | 20 | ```sh 21 | etcdctl snapshot save 22 | etcdctl endpoint health 23 | etcdctl get 24 | etcdctl put 25 | ``` 26 | 27 | Чтобы установить правильную версию API, установи переменную среды `ETCDCTL_API` командой 28 | 29 | ```sh 30 | export ETCDCTL_API = 3 31 | ``` 32 | Когда версия API не установлена в переменной, в некоторых релизах ETCD она будет по умолчанию версией 2, в других - 3. И перечисленные выше команды версии 3 могут не работать. 33 | Если явно задать `ETCDCTL_API`, то ETCD будет работать с требуемой ожидаемой версией API. 34 | 35 | Кроме того, тебе также потребуется указать путь к файлам сертификатов, чтобы ETCDCTL мог аутентифицироваться на сервере ETCD API. Файлы сертификатов доступны в **etcd-controlplane** по следующему пути. Мы обсудим больше о сертификатах в разделе безопасности этого курса. Так что не волнуйся, если это пока сложно для тебя: 36 | 37 | ```sh 38 | --cacert /etc/kubernetes/pki/etcd/ca.crt 39 | --cert /etc/kubernetes/pki/etcd/server.crt 40 | --key /etc/kubernetes/pki/etcd/server.key 41 | ``` 42 | 43 | Итак, чтобы все работало как надо, нужно указать версию API для ETCDCTL и путь к файлам сертификатов. Ниже представлена окончательная команда: 44 | 45 | ```sh 46 | kubectl exec etcd-master -n kube-system -- sh -c "ETCDCTL_API=3 etcdctl get / --prefix --keys-only --limit=10 --cacert /etc/kubernetes/pki/etcd/ca.crt --cert /etc/kubernetes/pki/etcd/server.crt --key /etc/kubernetes/pki/etcd/server.key" 47 | ``` 48 | -------------------------------------------------------------------------------- /02- Scheduling/Object Editing.md: -------------------------------------------------------------------------------- 1 | # Editing PODs and Deployments 2 | 3 | ## Редактирование POD 4 | 5 | Помните, что у тебя **не получится** редактировать спецификации существующего POD, кроме указанных ниже: 6 | 7 | ```sh 8 | spec.containers[*].image 9 | 10 | spec.initContainers[*].image 11 | 12 | spec.activeDeadlineSeconds 13 | 14 | spec.tolerations 15 | ``` 16 | 17 | Например, ты не можешь редактировать переменные среды, учетные записи служб, ограничения ресурсов (все это мы обсудим позже) у работающего POD. Но если очень хочется, то есть 2 варианта: 18 | 19 | ### 1. kubectl edit pod 20 | Запусти команду 21 | ```sh 22 | kubectl edit pod 23 | ``` 24 | Это откроет спецификацию POD в редакторе (обычно `vi`). Затем отредактируй необходимые свойства. Когда ты решишь его сохранить, тебе будет отказано. Это связано с тем, что ты пытаешься изменить недоступные для редактирования поля POD. 25 | 26 | > Копия файла с товими изменениями сохранится в `/tmp`-директории. 27 | 28 | Теперь можно удалить это существующий POD, выполнив команду: 29 | ```sh 30 | kubectl delete pod myapp 31 | ``` 32 | Затем создай новый POD с сделанными изменениями, используя временный файл 33 | ```sh 34 | kubectl create -f /tmp/kubectl-edit-fttha.yaml 35 | ``` 36 | ### 2. Извлечь определение в YAML 37 | 38 | Извлечем определение POD в формате YAML в файл с помощью команды 39 | ```sh 40 | kubectl get pod webapp -o yaml > new-pod.yaml 41 | ``` 42 | Затем внесем изменения в этот экспортированный файл с помощью текстового редактора 43 | 44 | Сохраним изменения `new-pod.yaml` 45 | 46 | Удалим существующий POD 47 | 48 | ```sh 49 | kubectl delete pod myapp 50 | ``` 51 | 52 | Затем создадим из отредактированного файла новый POD 53 | ```sh 54 | kubectl create -f new-pod.yaml 55 | ``` 56 | 57 | ## Редактирование Deployment 58 | 59 | У deployments можно легко редактировать любое поле / свойство шаблона POD. Поскольку шаблон POD является дочерним по отношению к спецификации deployment, при каждом изменении deployment будет сам автоматически удалять и создавать новый POD с новыми изменениями. 60 | 61 | Т.е. для редактирования свойств POD, которые являются частями развертываний, мы можем использовать команду 62 | ```sh 63 | kubectl edit deployment some-deployment 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /06 - Security/basic-auth.md: -------------------------------------------------------------------------------- 1 | # Setting up Basic Authentication 2 | > Внимание, basic authentication Deprecated in Kubernetes 1.19++ 3 | 4 | Это является устаревшим и не должно использоваться в производстве. Тем не менее очень хорошо помогает новичку разобраться в аутентификации в Kubernetes 5 | 6 | ## Следуя инструкциями настроим `basic authentication` в `kubeadm`-установке 7 | 8 | Создай файл с данными пользователей локально по `/tmp/users/user-details.csv` 9 | 10 | ``` 11 | # User File Contents 12 | password123,user1,u0001 13 | password123,user2,u0002 14 | password123,user3,u0003 15 | password123,user4,u0004 16 | password123,user5,u0005 17 | ``` 18 | 19 | Измени static POD настроенный `kubeadm` для `kube-apiserver`, на получение списка пользователей. Файл-манифест в размещении `/etc/kubernetes/manifests/kube-apiserver.yaml` 20 | 21 | ``` 22 | apiVersion: v1 23 | kind: Pod 24 | metadata: 25 | name: kube-apiserver 26 | namespace: kube-system 27 | spec: 28 | containers: 29 | - command: 30 | - kube-apiserver 31 | 32 | image: k8s.gcr.io/kube-apiserver-amd64:v1.11.3 33 | name: kube-apiserver 34 | volumeMounts: 35 | - mountPath: /tmp/users 36 | name: usr-details 37 | readOnly: true 38 | volumes: 39 | - hostPath: 40 | path: /tmp/users 41 | type: DirectoryOrCreate 42 | name: usr-details 43 | ``` 44 | Измени опции старта `kube-apiserver`, подключив файл для `basic-auth` 45 | 46 | ``` 47 | apiVersion: v1 48 | kind: Pod 49 | metadata: 50 | creationTimestamp: null 51 | name: kube-apiserver 52 | namespace: kube-system 53 | spec: 54 | containers: 55 | - command: 56 | - kube-apiserver 57 | - --authorization-mode=Node,RBAC 58 | 59 | - --basic-auth-file=/tmp/users/user-details.csv 60 | ``` 61 | Создай необходимые `roles` и `rolebindings` для этих пользователей: 62 | ``` 63 | --- 64 | kind: Role 65 | apiVersion: rbac.authorization.k8s.io/v1 66 | metadata: 67 | namespace: default 68 | name: pod-reader 69 | rules: 70 | - apiGroups: [""] # "" indicates the core API group 71 | resources: ["pods"] 72 | verbs: ["get", "watch", "list"] 73 | ``` 74 | ``` 75 | --- 76 | # This role binding allows "jane" to read pods in the "default" namespace. 77 | kind: RoleBinding 78 | apiVersion: rbac.authorization.k8s.io/v1 79 | metadata: 80 | name: read-pods 81 | namespace: default 82 | subjects: 83 | - kind: User 84 | name: user1 # Name is case sensitive 85 | apiGroup: rbac.authorization.k8s.io 86 | roleRef: 87 | kind: Role 88 | name: pod-reader 89 | apiGroup: rbac.authorization.k8s.io 90 | ``` 91 | 92 | После создания, ты можешь аутентифицироваться в `kube-apiserver` используя их данные: 93 | ``` 94 | curl -v -k https://localhost:6443/api/v1/pods -u "user1:password123" 95 | ``` 96 | -------------------------------------------------------------------------------- /08 - Networking/Annotations-Nginx.md: -------------------------------------------------------------------------------- 1 | # Annotations and rewrite-target 2 | Различные `ingress controllers` имеют разные параметры, которые можно использовать для их настройки под свои нужды. Контроллер `NGINX Ingress controller` имеет множество опций, которые можно увидеть [https://kubernetes.github.io/ingress-nginx/examples/](https://kubernetes.github.io/ingress-nginx/examples/). 3 | Я хотел бы объяснить одну из этих опций, которую мы будем использовать в наших лабораторных. Параметр "Rewrite target" 4 | 5 | Наше приложение `meet` показывает страницу конференций по адресу: `http://:/` 6 | 7 | Наше приложение `meet` показывает страницу магазина по адресу: `http://:/` 8 | 9 | Мы должны настроить `Ingress` для достижения следующего. Когда пользователь посещает URL-адрес, его запрос должен быть перенаправлен внутрь на URL-адрес после стрелки. 10 | # 11 | `http://:/shop` 12 | -->> 13 | `http://:/` 14 | 15 | `http://:/conference` 16 | -->> 17 | `http://:/` 18 | # 19 | Обрати внимание, что в URL путь `/shop` и `/conference` - это то, что мы настраиваем на `ingress controller`, поэтому мы можем перенаправлять пользователей в соответствующие приложения в бэкенде. 20 | Пока для приложений не настроен этот путь. 21 | И без заданной опции `rewrite-target` мы получим что-то вроде: 22 | # 23 | `http://:/shop` 24 | -->> 25 | `http://:/shop` 26 | 27 | `http://:/conference` 28 | -->> 29 | `http://:/conference` 30 | # 31 | Обрати внимание на `shop` и `conference` в конце целевых URL. Целевые приложения не настроены с работать путями `/shop` или `/conference`. 32 | 33 | Это разные приложения, созданные специально для своих целей, поэтому они не ожидают `/shop` и `/conference` в адресе. Поэтому такие запросы будут терпеть неудачу и возвращать `404 not found`. 34 | 35 | Чтобы исправить это, мы хотим "переписать" (`rewrite`) URL-адрес, когда запрос передается в приложение `store` и `meet`. Мы не хотим передавать тот путь, который ввел пользователь. Поэтому мы указываем опцию `rewrite-target`. 36 | 37 | Она перезаписывает URL-адрес, заменяя все, что находится в `rules-> http-> paths-> path`, который в данном случае является `/pay`, на значение в `rewrite-target`. 38 | 39 | Это работает так же, как функция поиска и замены: 40 | replace(path, rewrite-target). В нашем случае: replace("/path","/") 41 | ``` 42 | apiVersion: extensions/v1beta1 43 | kind: Ingress 44 | metadata: 45 | name: test-ingress 46 | namespace: critical-space 47 | annotations: 48 | nginx.ingress.kubernetes.io/rewrite-target: / 49 | spec: 50 | rules: 51 | - http: 52 | paths: 53 | - path: /pay 54 | backend: 55 | serviceName: pay-service 56 | servicePort: 8282 57 | ``` 58 | В другом примере, это также может быть: 59 | ``` 60 | apiVersion: extensions/v1beta1 61 | kind: Ingress 62 | metadata: 63 | annotations: 64 | nginx.ingress.kubernetes.io/rewrite-target: /$2 65 | name: rewrite 66 | namespace: default 67 | spec: 68 | rules: 69 | - host: rewrite.bar.com 70 | http: 71 | paths: 72 | - backend: 73 | serviceName: http-svc 74 | servicePort: 80 75 | path: /something(/|$)(.*) 76 | ``` 77 | -------------------------------------------------------------------------------- /01 - Core Concepts/Imperative.md: -------------------------------------------------------------------------------- 1 | # Imperative Commands with Kubectl 2 | 3 | Хотя ты будешь работать в основном декларативным способом - используя файлы определений, императивные команды могут помочь в быстром выполнении одноразовых задач, а также в легком создании шаблона для файла определения. Это поможет значительно сэкономить время во время экзамена. 4 | 5 | Прежде чем мы начнем, ознакомься с двумя опциями, которые могут пригодиться при работе с приведенными ниже командами. 6 | ```sh 7 | --dry-run=client 8 | ``` 9 | Обычно, как только команда запущена, ресурс сразу создается. Но если тебе хочетьбся лишь протестировать свою команду, используй параметр `--dry-run=client`. Это не создаст ресурс, а сообщит нам, можно ли это выполнить в данном кластере и верна ли твоя команда. 10 | ```sh 11 | -o yaml 12 | ``` 13 | Это выведет на экран определение ресурса в формате YAML. 14 | 15 | Используй два этих сочетания для быстрого создания файла определения ресурса, который затем можно изменять и создавать ресурсы по мере необходимости, вместо написания файлов с нуля. 16 | 17 | ## POD 18 | ### Создать POD NGINX 19 | ```sh 20 | kubectl run nginx --image=nginx 21 | ``` 22 | ### Создать YAML-манифест POD 23 | Используем `-o yaml`, чтобы не создавать в кластере `--dry-run` 24 | ```sh 25 | kubectl run nginx --image=nginx --dry-run=client -o yaml 26 | ``` 27 | 28 | ## Deployment 29 | ### Создать Deployment 30 | ```sh 31 | kubectl create deployment --image=nginx nginx 32 | ``` 33 | ### Создать YAML-манифест Deployment 34 | Используем `-o yaml`, чтобы не создавать в кластере `--dry-run` 35 | ```sh 36 | kubectl create deployment --image=nginx nginx --dry-run=client -o yaml 37 | ``` 38 | ### Создать YAML-манифест Deployment с 4 replicas 39 | Используем `-o yaml`, чтобы не создавать в кластере `--dry-run`, и параметр `--replicas=4` 40 | ```sh 41 | kubectl create deployment nginx --image=nginx --replicas=4 42 | ``` 43 | ### Масштабирование Deployment 44 | Используем команду `scale` и параметр `--replicas=3` 45 | ```sh 46 | kubectl scale deployment nginx --replicas=3 47 | ``` 48 | Другой способ сделать это - сохранить определение YAML в файл и изменить его там. 49 | ```sh 50 | kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx-deployment.yaml 51 | ``` 52 | Теперь нам нужно лишь обновить файл `nginx-deployment.yaml`, добавив туда реплик или изменив любые другие полея перед созданием deployment. 53 | 54 | ## Services 55 | ### Создать Service для `redis`-POD 56 | ```sh 57 | kubectl expose pod redis --port=6379 58 | ``` 59 | или тоже самое, но если POD еще нет 60 | ```sh 61 | kubectl expose pod redis --port=6379 --name redis-service --dry-run=client -o yaml 62 | ``` 63 | > Это автоматически будет использовать метки POD в качестве селекторов для Service 64 | 65 | или, если нам нужны дополнительные селекторы 66 | ```sh 67 | kubectl create service clusterip redis --tcp=6379:6379 --dry-run=client -o yaml 68 | ``` 69 | > Это не будет использовать метки POD в качестве селекторов, вместо этого он будет использовать селекторы как `app=redis`. 70 | 71 | Мы не можем передавать селекторы в качестве опциий для команды. Таким образом, он не будет работать с POD `redis` как ожидалось, если у него другой набор меток. Поэтому, мы зайдем в файл и отредактируем как нам нужно, перед созданием Service 72 | 73 | ### Создать Service с именем `nginx` типа `NodePort` 74 | 75 | И еще открыть порт 80 в nginx-POD на портах 30080 на узлах кластера 76 | 77 | ```sh 78 | kubectl expose pod nginx --type=NodePort --port=80 --name=nginx-service --dry-run=client -o yaml 79 | ``` 80 | > Это будет автоматически использовать метки POD в качестве селекторов, но мы не сможете указать `NodePort`. Необходимо сгенерировать файл определения, а затем попроавить `NodePort` вручную перед созданием службы. 81 | 82 | Или мы можем зайти с другой стороны 83 | ```sh 84 | kubectl create service nodeport nginx --tcp=80:80 --node-port=30080 --dry-run=client -o yaml 85 | ``` 86 | > Это не будет использовать метки POD в качестве селекторов Service, поэтому файл все равно придется править 87 | 88 | У обеих этих команд есть свои проблемы. Хотя одна из них не может принять селектор, другая не может принять nodeport. Я бы рекомендовал использовать команду kubectl expose. 89 | 90 | Если тебе нужно указать порт узла, сгенерируй файл определения с помощью той же команды и вручную измени его, введя `nodePort` перед созданием службы. 91 | 92 | # Документация: 93 | [https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands) 94 | 95 | [https://kubernetes.io/docs/reference/kubectl/conventions/](https://kubernetes.io/docs/reference/kubectl/conventions/) 96 | 97 | --------------------------------------------------------------------------------