Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Vault] Using Service Acount of Kubernetes to login Vault system.

Posted on June 28, 2022 By nim No Comments on [Vault] Using Service Acount of Kubernetes to login Vault system.

Contents

Toggle
  • Install vault client or vault CLI.
  • How do our application read the token of Service Account and login the vault?

Install vault client or vault CLI.

Ngoài việc sử dụng UI để tưởng tác với vault thì chúng ta có thể sử dụng command hay còn gọi là cli.

https://www.vaultproject.io/downloads

curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
sudo apt-get update && sudo apt-get install vault
#login vault
vault login -address=<address_vault>
ex: vault login -address=http://vault.nimtechnology.com/

lúc này bạn chỉ cần change ENV sang host vault của bạn là ok.

#config server vault

export VAULT_ADDR='http://vault.nimtechnology.com'

file: vault-auth-service-account.yml

apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: role-tokenreview-binding
  namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
- kind: ServiceAccount
  name: vault-auth
  namespace: default

Để hiểu được về ClusterRole system:auth-delegator và tại sao vault lại cần cluster role này!
Bạn có thể thao khao link bên dưới.
https://www.vaultproject.io/docs/auth/kubernetes#use-local-service-account-token-as-the-reviewer-jwt

Giờ ta tạo service account và ClusterRoleBinding

# Create a service account, 'vault-auth'
$ kubectl -n default create serviceaccount vault-auth

# Update the 'vault-auth' service account
$ kubectl -n default apply --filename vault-auth-service-account.yml

Tạo read-only policy trên vault
Policy này có quyền read và list các secret thuộc path secret/nimtechnology/*
nimtechnology-kv-ro.hcl

# For K/V v1 secrets engine
path "secret/nimtechnology/*" {
    capabilities = ["read", "list"]
}
# For K/V v2 secrets engine
path "secret/data/nimtechnology/*" {
    capabilities = ["read", "list"]
}

$ vault policy write nimtechnology-kv-ro nimtechnology-kv-ro.hcl
Bạn sẽ thấy nó trên UI như sau.

Cấu hình environment variables yêu cầu cho Vault configuration.

# Set VAULT_SA_NAME to the service account you created earlier
$ export VAULT_SA_NAME=$(kubectl -n default get sa vault-auth -o jsonpath="{.secrets[*]['name']}")

# Set SA_JWT_TOKEN value to the service account JWT used to access the TokenReview API
$ export SA_JWT_TOKEN=$(kubectl -n default get secret $VAULT_SA_NAME -o jsonpath="{.data.token}" | base64 --decode; echo)

# Set SA_CA_CRT to the PEM encoded CA cert used to talk to Kubernetes API
$ export SA_CA_CRT=$(kubectl -n default get secret $VAULT_SA_NAME -o jsonpath="{.data['ca\.crt']}" | base64 --decode; echo)

# Look in your cloud provider console for this value
$ export K8S_HOST=<https://your_API_server_endpoint>
==>export K8S_HOST=https://192.168.101.40:6443

Ở mục này là bạn khai báo 1 số thông tin để vault access vào kubernetes.

vault auth enable kubernetes

vault write auth/kubernetes/config \
        token_reviewer_jwt="$SA_JWT_TOKEN" \
        kubernetes_host="$K8S_HOST" \
        kubernetes_ca_cert="$SA_CA_CRT"
TRên UI thì bạn sẽ thấy như trên

Phần tiếp theo là bạn map Policy trên vault với service account ở trên kubernetes

vault write auth/kubernetes/role/nimtechnology \
        bound_service_account_names=default \
        bound_service_account_namespaces='*' \
        policies=nimtechnology-kv-ro \
        ttl=1440h

Giờ chúng ta kiểm tra lại các config:

kubectl apply -f  https://raw.githubusercontent.com/armory/troubleshooting-toolbox/master/docker-debugging-tools/deployment.yml

#we execute this pod
POD_NAME=$(kubectl get pod -l app=debugging-tools -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' --sort-by=".status.startTime" | tail -n 1)

kubectl exec -it $POD_NAME bash

Sau khi execute pod đó thì chúng run tiếp các command sau:

export VAULT_ADDR='http://vault.nimtechnology.com/'
SA_TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)

vault write auth/kubernetes/login role=nimtechnology jwt=$SA_TOKEN
Khi bạn lây tocken của service account để login
=> Nếu thành công thì vault sẽ trả về cho bạn 1 Token của vault
vault login hvs.xxxxxxxxxxxxxxxxxxxxxxxxxxx

>>>>>>>..out put

Nim thử get secret sem sao:

bash-5.0# vault kv get secret/nimtechnology/test
======= Metadata =======
Key                Value
---                -----
created_time       2022-06-28T09:45:14.649162267Z
custom_metadata    <nil>
deletion_time      n/a
destroyed          false
version            1

========== Data ==========
Key                  Value
---                  -----
key_nimtechnology    value_nimtechnology

ngon lành rồi ha

https://docs.armory.io/armory-enterprise/armory-admin/secrets/vault-k8s-configuration/

How do our application read the token of Service Account and login the vault?

Đầu tiên bạn cần phải tạo Service Accountvà add

kubectl apply -f - <<EOF
apiVersion: v1
kind: ServiceAccount
metadata:
  name: build-robot
EOF

Config Service Account vào workload trên K8s.

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - image: nginx
    name: nginx
  serviceAccountName: build-robot #this line

Bước tiếp theo là mình get content token.

Cách 1: cat /var/run/secrets/kubernetes.io/serviceaccount/token
Cách này có 1 hạn chế là không lúc nào code của bạn cũng có đọc được các đường link system

Cách 2: serviceAccountToken projected volumes

Về mount volume trong k8s chúng ta sẽ có 4 kiểu:

  • secret
  • downwardAPI
  • configMap
  • serviceAccountToken

Bạn có thể tham khảo docs này:
https://www.alibabacloud.com/help/en/container-service-for-kubernetes/latest/enable-service-account-token-volume-projection

>>>>>create service account

kubectl apply -f - <<EOF
apiVersion: v1
kind: ServiceAccount
metadata:
  name: build-robot
EOF

>>>>>>>>> edit your workload and config mount token inside your area code!
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - image: nginx
    name: nginx
    volumeMounts:
    - mountPath: /var/run/secrets/tokens #You need to look at
      name: vault-token
  serviceAccountName: build-robot
  volumes:
  - name: vault-token
    projected:
      sources:
      - serviceAccountToken:
          path: vault-token
          expirationSeconds: 7200
          audience: vault

mountPath: chỗ này thì bạn sẽ dẫn đến folder code của bạn.
Mà code của bạn có thể đọc được!

Kubernetes, Vault

Post navigation

Previous Post: My Assignment 
Next Post: [Argocd/Vault] Integrate Vault inside Argocd by the plugin

More Related Articles

[Sidecar/Kubernestes] Inject sidecar into a Pod automatically Kubernetes
[Kubernetes] Don’t believe kubectl top Kubernetes
Hướng dẫn đưa secret của Kubernetes thành biến env của pod Kubernetes
[Kubernetes] How to delete namespace is Terminating and very stubborn Kubernetes
[Kubernetes] Changing DNS or Hosts of the POD on Kubernetes Kubernetes
[Kasm] Stream your workspace directly to your web browser…on any device and from any location. BareMetal

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Laravel] Laravel Helpful June 26, 2025
  • [VScode] Hướng dẫn điều chỉnh font cho terminal June 20, 2025
  • [WordPress] Hướng dấn gửi mail trên WordPress thông qua gmail. June 15, 2025
  • [Bitbucket] Git Clone/Pull/Push with Bitbucket through API Token. June 12, 2025
  • [Teamcity] How to transfer the value from pipeline A to pipeline B June 9, 2025

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.