无法从AWS秘密管理器中列出所有秘密。

huangapple go评论56阅读模式
英文:

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'])

huangapple
  • 本文由 发表于 2023年2月7日 02:32:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定