简体   繁体   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 documentation SSM — Boto 3 Docs 1.9.64 文档

get_parameters doesn't list all parameters? get_parameters没有列出所有参数?

For those who wants to just copy-paste the code:对于那些只想复制粘贴代码的人:

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

Beware of the limit of max 50 parameters!注意最多 50 个参数的限制!

This code will get all parameters, by recursively fetching until there are no more (50 max is returned per call):此代码将通过递归获取所有参数,直到没有更多参数(每次调用最多返回 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')

You can use get_paginator api.您可以使用 get_paginator api。 find below example, In my use case i had to get all the values of SSM parameter store and wanted to compare it with a string.找到下面的示例,在我的用例中,我必须获取 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)

One of the responses from above/below(?) (by Val Lapidas ) inspired me to expand it to this (as his solution doesn't get the SSM parameter value, and some other, additional details).来自上方/下方(?)(由Val Lapidas 提供)的回应之一启发我将其扩展到此(因为他的解决方案没有获得 SSM 参数值以及其他一些附加细节)。

The downside here is that the AWS function client.get_parameters() only allows 10 names per call.这里的缺点是 AWS 函数client.get_parameters()每次调用只允许 10 个名称。

There's one referenced function call in this code ( to_pdatetime(...) ) that I have omitted - it just takes the datetime value and makes sure it is a "naive" datetime.这段代码中有一个引用的函数调用( to_pdatetime(...) ),我省略了它——它只接受datetime时间值并确保它是一个“天真的”日期时间。 This is because I am ultimately dumping this data to an Excel file using pandas , which doesn't deal well with timezones.这是因为我最终使用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

There's no ListParameters only DescribeParameter, which lists all the paremeters, or you can set filters.没有ListParameters只有DescribeParameter,它列出了所有的参数,也可以设置过滤器。

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

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

Use paginators .使用paginators

paginator = client.get_paginator('describe_parameters') 

More information here .更多信息在这里

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

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