kubectl get node
NAME STATUS ROLES AGE VERSION10.0.4.144 Ready <none> 24h v1.22.5-tke.1
kubectl get pod -n kube-systemNAMESPACE NAME READY STATUS RESTARTS AGEkube-system pod-identity-webhook-78c76****-9qrpj 1/1 Running 0 43h
$db_address
。$db_port
。0.0.0.0/0
,协议端口为 TCP:3306
。
mysql -h $db_address -P $db_port -uroot -pEnter password:Welcome to the MariaDB monitor. Commands end with ; or \\g.Your MySQL connection id is 4238098Server version: 5.7.36-txsql-log 20211230Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.Type 'help;' or '\\h' for help. Type '\\c' to clear the current input statement.MySQL [(none)]>
MySQL [(none)]> CREATE DATABASE mydb;Query OK, 1 row affected (0.00 sec)MySQL [(none)]> CREATE TABLE mydb.user (Id VARCHAR(120), Name VARCHAR(120));Query OK, 0 rows affected (0.00 sec)MySQL [(none)]> INSERT INTO mydb.user (Id,Name) VALUES ('123','tke-oidc');Query OK, 1 row affected (0.01 sec)MySQL [(none)]> SELECT * FROM mydb.user;+------+----------+| Id | Name |+------+----------+| 123 | tke-oidc |+------+----------+1 row in set (0.01 sec)
$db_name
。%
。$ssm_name
$ssm_region_name
$my_pod_audience
,当oidc:aud的 value 值有多个时,任选其中之一即可。$my_pod_role_arn
。kubectl create namespace my-namespace
$my_pod_role_arn
替换为 RoleArn 的 value 值,将$my_pod_audience
替换为 oidc:aud 的 value 值。apiVersion: v1kind: ServiceAccountmetadata:name: my-serviceaccountnamespace: my-namespaceannotations:tke.cloud.tencent.com/role-arn: $my_pod_role_arntke.cloud.tencent.com/audience: $my_pod_audiencetke.cloud.tencent.com/token-expiration: "86400"
apiVersion: apps/v1kind: Deploymentmetadata:name: nginx-deploymentnamespace: my-namespacespec:selector:matchLabels:app: my-appreplicas: 1template:metadata:labels:app: my-appspec:serviceAccountName: my-serviceaccountcontainers:- name: nginximage: $imageports:- containerPort: 80
$image
选择ccr.ccs.tencentyun.com/tkeimages/sample-application:latest
,该镜像集成了编译的 demo文件,方便进行示例演示。您可以根据自身业务进行填写。kubectl apply -f my-serviceaccount.yamlkubectl apply -f sample-application.yaml
kubectl get pods -n my-namespace
NAME READY STATUS RESTARTS AGEnginx-deployment-6bfd845f47-9zxld 1/1 Running 0 67s
kubectl describe pod nginx-deployment-6bfd845f47-9zxld -n my-namespace
git clone https://github.com/TencentCloud/ssm-rotation-sdk-golang.git
package mainimport ("flag""fmt"_ "github.com/go-sql-driver/mysql""github.com/tencentcloud/ssm-rotation-sdk-golang/lib/db""github.com/tencentcloud/ssm-rotation-sdk-golang/lib/ssm""github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common""log""time")var (roleArn, tokenPath, providerId, regionName, saToken stringsecretName, dbAddress, dbName, ssmRegionName stringdbPort uint64dbConn *db.DynamicSecretRotationDbHeader = map[string]string{"Authorization": "SKIP","X-TC-Action": "AssumeRoleWithWebIdentity","Host": "sts.internal.tencentcloudapi.com","X-TC-RequestClient": "PHP_SDK","X-TC-Version": "2018-08-13","X-TC-Region": regionName,"X-TC-Timestamp": "1659944952","Content-type": "application/json",})type Credentials struct {TmpSecretId stringTmpSecretKey stringToken stringExpiredTime uint64}func main() {flag.StringVar(&secretName, "ssmName", "", "ssm名称")flag.StringVar(&ssmRegionName, "ssmRegionName", "", "ssm地域")flag.StringVar(&dbAddress, "dbAddress", "", "数据库地址")flag.StringVar(&dbName, "dbName", "", "数据库名称")flag.Uint64Var(&dbPort, "dbPort", 0, "数据库端口")flag.Parse()provider, err := common.DefaultTkeOIDCRoleArnProvider()if err != nil {log.Fatal("failed to assume role with web identity, err:", err)}assumeResp, err := provider.GetCredential()if err != nil {log.Fatal("failed to assume role with web identity, err:", err)}var credential Credentialsif assumeResp != nil {credential = Credentials{TmpSecretId: assumeResp.GetSecretId(),TmpSecretKey: assumeResp.GetSecretKey(),Token: assumeResp.GetToken(),}}log.Printf("secretId:%v,secretey%v,token%v\\n", credential.TmpSecretId, credential.TmpSecretKey, credential.Token)DB(credential)}func DB(credential Credentials) {// 初始化数据库连接dbConn = &db.DynamicSecretRotationDb{}err := dbConn.Init(&db.Config{DbConfig: &db.DbConfig{MaxOpenConns: 100,MaxIdleConns: 50,IdleTimeoutSeconds: 100,ReadTimeoutSeconds: 5,WriteTimeoutSeconds: 5,SecretName: secretName, // 凭据名IpAddress: dbAddress, // 数据库地址Port: dbPort, // 数据库端口DbName: dbName, // 可以为空,或指定具体的数据库名ParamStr: "charset=utf8&loc=Local",},SsmServiceConfig: &ssm.SsmAccount{SecretId: credential.TmpSecretId, // 需填写实际可用的SecretIdSecretKey: credential.TmpSecretKey, // 需填写实际可用的SecretKeyToken: credential.Token,Region: ssmRegionName, // 选择凭据所存储的地域},WatchChangeInterval: time.Second * 10, // 多长时间检查一下 凭据是否发生了轮转})if err != nil {fmt.Errorf("failed to init dbConn, err:%v\\n", err)return}// 模拟业务处理中,每过一段时间(一般是几毫秒),需要拿到db连接,来操作数据库的场景t := time.Tick(time.Second)for {select {case <-t:accessDb()queryDb()}}}func accessDb() {fmt.Println("--- accessDb start")c := dbConn.GetConn()if err := c.Ping(); err != nil {log.Fatal("failed to access db with err:", err)}log.Println("--- succeed to access db")}func queryDb() {var (id intname string)log.Println("--- queryDb start")c := dbConn.GetConn()rows, err := c.Query("select id, name from user where id = ?", 1)if err != nil {log.Printf("failed to query db with err: ", err)log.Fatal(err)}defer rows.Close()for rows.Next() {err := rows.Scan(&id, &name)if err != nil {log.Fatal(err)}log.Println(id, name)}err = rows.Err()if err != nil {log.Fatal(err)}log.Println("--- succeed to query db")}
kubectl exec -ti nginx-deployment-6bfd845f47-9zxld -n my-namespace -- /bin/bashcd /root/
./demo --ssmName=$ssm_name --ssmRegionName=$ssm_region_name --dbAddress=$db_address --dbName=$db_name --dbPort=$db_port
功能 | 涉及对象 | 涉及操作权限 |
需要查询创建的 pod 上指定的 serviceaccounts 的资源情况。 | serviceaccount | list/watch/get |
创建组件时需要在 mutatingwebhookconfigurations 的资源注入客户端的证书。 | mutatingwebhookconfigurations | get/update |
rules:- apiGroups:- ""resources:- serviceaccountsverbs:- get- watch- list- apiGroups:- ""resources:- eventsverbs:- patch- update- apiGroups:- "admissionregistration.k8s.io"resources:- "mutatingwebhookconfigurations"verbs:- get
本页内容是否解决了您的问题?