繁体   English   中英

我们如何使用 Boto3 列出 aws 参数存储中的所有参数? boto3 文档中没有 ssm.list_parameters 吗?

[英]How can we list all the parameters in the aws parameter store using Boto3? There is no ssm.list_parameters in boto3 documentation?

SSM — Boto 3 Docs 1.9.64 文档

get_parameters没有列出所有参数?

对于那些只想复制粘贴代码的人:

import boto3
ssm = boto3.client('ssm')
parameters = ssm.describe_parameters()['Parameters']

注意最多 50 个参数的限制!

此代码将通过递归获取所有参数,直到没有更多参数(每次调用最多返回 50 个):

import boto3
def get_resources_from(ssm_details):
  results = ssm_details['Parameters']
  resources = [result for result in results]
  next_token = ssm_details.get('NextToken', None)
  return resources, next_token
    
def main()
  config = boto3.client('ssm', region_name='us-east-1')
  next_token = ' '
  resources = []
  while next_token is not None:
    ssm_details = config.describe_parameters(MaxResults=50, NextToken=next_token)
    current_batch, next_token = get_resources_from(ssm_details)
    resources += current_batch
  print(resources)
  print('done')

您可以使用 get_paginator api。 找到下面的示例,在我的用例中,我必须获取 SSM 参数存储的所有值,并希望将其与字符串进行比较。

import boto3
import sys

LBURL = sys.argv[1].strip()
client = boto3.client('ssm')
p = client.get_paginator('describe_parameters')
paginator = p.paginate().build_full_result()
for page in paginator['Parameters']:
    response = client.get_parameter(Name=page['Name'])
    value = response['Parameter']['Value']
    if LBURL in value:
        print("Name is: " + page['Name'] + " and Value is: " + value)

来自上方/下方(?)(由Val Lapidas 提供)的回应之一启发我将其扩展到此(因为他的解决方案没有获得 SSM 参数值以及其他一些附加细节)。

这里的缺点是 AWS 函数client.get_parameters()每次调用只允许 10 个名称。

这段代码中有一个引用的函数调用( to_pdatetime(...) ),我省略了它——它只接受datetime时间值并确保它是一个“天真的”日期时间。 这是因为我最终使用pandas将这些数据转储到 Excel 文件中,这不能很好地处理时区。

from typing import List, Tuple
from boto3 import session
from mypy_boto3_ssm import SSMClient

def ssm_params(aws_session: session.Session = None) -> List[dict]:
    """
    Return a detailed list of all the SSM parameters.
    """
    
    # -------------------------------------------------------------
    #
    #
    # -------------------------------------------------------------
    def get_parameter_values(ssm_client: SSMClient,  ssm_details: dict) -> Tuple[list, str]:
        """
        Retrieve additional attributes for the SSM parameters contained in the 'ssm_details'
        dictionary passed in.
        """
        # Get the details
        ssm_param_details = ssm_details['Parameters']

        # Just the names, ma'am
        param_names = [result['Name'] for result in ssm_param_details]

        # Get the parames, including the values
        ssm_params_with_values = ssm_client.get_parameters(Names=param_names,
                                                           WithDecryption=True)
        resources = []

        result: dict
        for result in ssm_params_with_values['Parameters']:

            # Get the matching parameter from the `ssm_details` dict since this has some of the fields
            # that aren't in the `ssm_params_with_values` returned from "get_arameters".
            param_details = next((zz for zz in ssm_param_details if zz.get('Name', None) == result['Name']), {})

            param_policy = param_details.get('Policies', None)
            if len(param_policy) == 0:
                param_policy = None

            resources.append({
                    'Name': result['Name'],
                    'LastModifiedDate': to_pdatetime(result['LastModifiedDate']),
                    'LastModifiedUser': param_details.get('LastModifiedUser', None),
                    'Version': result['Version'],
                    'Tier': param_details.get('Tier', None),
                    'Policies': param_policy,
                    'ARN': result['ARN'],
                    'DataType': result.get('DataType', None),
                    'Type': result.get('Type', None),
                    'Value': result.get('Value', None)
                    })

        next_token = ssm_details.get('NextToken', None)
        return resources, next_token

    # -------------------------------------------------------------
    #
    #
    # -------------------------------------------------------------
    if aws_session is None:
        raise ValueError('No session.')

    # Create SSM client
    aws_ssm_client = aws_session.client('ssm')

    next_token = ' '
    ssm_resources = []

    while next_token is not None:
        # The "describe_parameters" call gets a whole lot of info on the defined SSM params,
        # except their actual values. Due to this limitation let's call the nested function
        # to get the values, and a few other details. 
        ssm_descriptions = aws_ssm_client.describe_parameters(MaxResults=10,
                                                              NextToken=next_token)

        # This will get additional details for the params, including values.
        current_batch, next_token = get_parameter_values(ssm_client=aws_ssm_client,
                                                         ssm_details=ssm_descriptions)
        ssm_resources += current_batch

    print(f'SSM Parameters: {len(ssm_resources)}')
    return ssm_resources

没有ListParameters只有DescribeParameter,它列出了所有的参数,也可以设置过滤器。

Boto3 文档链接: https ://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ssm.html#SSM.Client.describe_parameters

AWS API 文档链接: https ://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeParameters.html

使用paginators

paginator = client.get_paginator('describe_parameters') 

更多信息在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM