代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。建议不要在代码中使用持久 SecretId 和 SecretKey,为了提高密钥的安全性,推荐以下几种方案:
方案1:通过环境变量读取 SecretId 和 SecretKey
将 SecretId 和 SecretKey 预先配置到环境变量中,在代码运行时从环境变量中读取 SecretId 和 SecretKey 的值,代码示例如下:
import osfrom tencentcloud.common import credentialfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKExceptionfrom tencentcloud.cvm.v20170312 import cvm_client, modelstry:# 硬编码密钥到代码中有可能随代码泄露而暴露,有安全隐患,不推荐# 为保护密钥安全,建议将密钥设置在环境变量中# cred = credential.Credential("secretId", "secretKey")cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),os.environ.get("TENCENTCLOUD_SECRET_KEY"))client = cvm_client.CvmClient(cred, "ap-shanghai")req = models.DescribeInstancesRequest()resp = client.DescribeInstances(req)print(resp.to_json_string())except TencentCloudSDKException as err:print(err)
方案2:使用临时密钥
# 换取临时秘钥的 SDK 示例import jsonimport osfrom tencentcloud.common import credentialfrom tencentcloud.common.profile.client_profile import ClientProfilefrom tencentcloud.common.profile.http_profile import HttpProfilefrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKExceptionfrom tencentcloud.sts.v20180813 import sts_client, modelstry:# 实例化一个认证对象,入参需要传入腾讯云账户的secretId和secretKey,为了保护密钥安全,建议结合方案一,将密钥设置在环境变量中cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),os.environ.get("TENCENTCLOUD_SECRET_KEY"))httpProfile = HttpProfile()httpProfile.endpoint = "sts.tencentcloudapi.com"clientProfile = ClientProfile()clientProfile.httpProfile = httpProfileclient = sts_client.StsClient(cred, "", clientProfile)req = models.GetFederationTokenRequest()params = {}req.from_json_string(json.dumps(params))resp = client.GetFederationToken(req)print(resp.to_json_string())except TencentCloudSDKException as err:print(err)