英文:
Unable to list all secrets from AWS secret manager
问题
I am trying to list all secrets available in AWS secret manager using lambda function, following is the python code snippet;
region = 'us-west-2'
session = boto3.session.Session(region_name=region)
client = session.client('secretsmanager')
secrets = client.list_secrets()
secrets_manager = secrets['SecretList']
for secret in secrets_manager:
print(secret['Name'])
Above code only lists a few secrets, not all the secrets, but running the following CLI command returns all secrets.
aws secretsmanager list-secrets | grep "Name"
What am I missing in the Python code? Please advise.
英文:
I am trying to list all secrets available in AWS secret manager using lambda function, following is the python code snippet;
region='us-west-2'
session= boto3.sesssion.Session(region_name=region)
client = session.client('secretsmanager')
secrets = client.list_secrets()
secrets_manager = secrets['SecretList']
for secret in secrets_manager:
print(secret['Name'])
Above code only lists few secret not all the secrets but running following CLI command returns all secrets.
aws secretsmanager list-secrets | grep "Name"
What am I missing in python code? Please advise
答案1
得分: 5
API是分页的。您需要发送多个请求以获取所有响应页面。CLI默认为您执行此操作。
最简单的方法是使用boto3中的分页器API,它会为您正确实现分页(在不同的AWS服务/API之间可能略有不同)。
client = session.client('secretsmanager')
paginator = client.get_paginator('list_secrets')
page_iterator = paginator.paginate()
for page in page_iterator:
print(page)
或者您可以以“手动”方式实现相同的效果:
secrets = []
response = client.list_secrets()
secrets.extend(response['SecretList'])
while 'NextToken' in response:
response = client.list_secrets(NextToken=response['NextToken'])
secrets.extend(response['SecretList'])
for secret in secrets:
print(secret['Name'])
英文:
The API is paginated. You need to send multiple requests to get all pages of responses. The CLI does this for you by default.
The easiest way is to use the paginator API in boto3 -- it will correctly implement pagination for you (which may be slightly different between different AWS services/APIs)
client = session.client('secretsmanager')
paginator = client.get_paginator('list_secrets')
page_iterator = paginator.paginate()
for page in page_iterator:
print(page)
Or you can do this 'manually' for the same effect:
secrets = []
response = client.list_secrets()
secrets.extend(response['SecretList'])
while 'NextToken' in response:
response = client.list_secrets(NextToken=response['NextToken'])
secrets.extend(response['SecretList'])
for secret in secrets:
print(secret['Name'])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论