Hashicorp Vault脚本续期Token返回n/a无法保存问题求助
问题:Vault Token续期返回"n/a"无法获取新Token值
我写了一个自动续期Hashicorp Vault Token的脚本,但执行时Vault返回的token字段是"n/a",没法把新Token保存到Kubernetes Secret里。
Vault输出示例:
--- ----- token n/a token_accessor ------------- token_duration 10h token_renewable true token_policies ["default"] identity_policies [] policies ["default"]
我的Python脚本:
import subprocess import json from kubernetes import client, config def renew_vault_token(vault_pod, token_id): try: result = subprocess.run( ['kubectl', 'exec', '-ti', vault_pod, '-n', 'vault', '--', 'vault', 'token', 'renew', '-accessor', token_id], capture_output=True, text=True, check=True ) output = result.stdout print("Vault renew output:", output) # Debugging output token_line = next(line for line in output.splitlines() if line.startswith('token')) new_token = token_line.split(None, 1)[1] print(new_token) return new_token except subprocess.CalledProcessError as e: print(f"Error renewing token: {e}") return None if __name__ == "__main__": VAULT_POD = 'vault-0' TOKEN_ID = '----------------' new_token = renew_vault_token(VAULT_POD, TOKEN_ID)
原因分析
出现"n/a"是Vault的安全设计:当使用-accessor参数通过token accessor续期时,Vault不会返回实际的token值。Token accessor的作用是让你在不持有原始token的情况下管理token(比如续期、撤销),出于安全考量,这类操作不会暴露token本身。
解决方案
根据你的实际需求选择对应方案:
1. 需要获取新Token值:直接用原始Token续期
如果你能持有原始token(而不是仅持有accessor),去掉-accessor参数,改用原始token执行续期,此时Vault会返回实际的token值:
def renew_vault_token(vault_pod, token): try: # 通过-token参数传递原始token result = subprocess.run( ['kubectl', 'exec', vault_pod, '-n', 'vault', '--', 'vault', 'token', 'renew', '-token', token], capture_output=True, text=True, check=True ) # 改用JSON格式输出,解析更可靠 output_data = json.loads(result.stdout) new_token = output_data['auth']['client_token'] print("新Token:", new_token) return new_token except subprocess.CalledProcessError as e: print(f"续期失败: {e}") return None
2. 仅需续期Token,无需获取新值
如果你的目标只是延长token有效期,不需要保存新token,那直接去掉提取token的逻辑,只要确认命令执行成功即可:
def renew_vault_token(vault_pod, token_accessor): try: subprocess.run( ['kubectl', 'exec', vault_pod, '-n', 'vault', '--', 'vault', 'token', 'renew', '-accessor', token_accessor], capture_output=True, text=True, check=True ) print("Token续期成功") return True except subprocess.CalledProcessError as e: print(f"Token续期失败: {e}") return False
3. 用JSON格式输出解析结果(推荐)
不管哪种场景,都建议给vault token renew加上-format=json参数,输出JSON格式结果,避免解析文本行的不确定性:
result = subprocess.run( ['kubectl', 'exec', vault_pod, '-n', 'vault', '--', 'vault', 'token', 'renew', '-format=json', '-accessor', token_accessor], capture_output=True, text=True, check=True ) output_data = json.loads(result.stdout) # 可以通过output_data['data']['duration']确认续期后的有效期 print(f"续期后有效期: {output_data['data']['duration']}")
内容的提问来源于stack exchange,提问作者poisoned_monkey
相关产品推荐
相关产品推荐

