首页 > 解决方案 > Python:如何比较包含字符串的两个集合,如果它们不相等,则将一个值替换为另一个?

问题描述

我正在编写一个 python 脚本来创建/更新/删除 AWS SSM 参数存储中的值。

我目前的逻辑是:

def lambda_handler(event, context):
    logger.info(event)#removing tab
    files = get_local_files() #set of all application.properties files
    count = 0
    for file in files: #iterate in each application.properties file
        remote_key_vals = get_ssm_paramstore_values(file) #remote_key_vals is a set of keys from ssm
        local_key_vals = read_ssm_local_file(file) #local_key_vals is a set of keys from local file
        if(len(remote_key_vals)==0):
            create_ssm_paramstore(file)
            count=count+1
        elif(local_key_vals>remote_key_vals):
            diff = local_key_vals-remote_key_vals
            if(len(diff)>0):
                update_ssm_paramstore(file, diff)
                count=count+1
        elif(remote_key_vals>local_key_vals):
            diff=remote_key_vals - local_key_vals
            if(len(diff)>0):
                delete_ssm_paramstore(file, diff)
                count = count+1 
        else:
            logger.info(file+' already exist')
        logger.info(local_key_vals)
    try:
        req = requests.put(event['ResponseURL'],
                          data=getResponse(event, context,
                                            responseStatus))
        if req.status_code != 200:
            logger.info(req.text)
            raise Exception('Received non 200 response while sending response to CFN.'
                            )
    except requests.exceptions.RequestException, e:
        logger.info(e)
        raise
    return

此代码仅适用于 3 个条件:

我需要处理两个集合的大小相同的情况,本地 application.properties 文件中的一个键具有更新的名称,并且远程 ssm 需要使用该名称进行更新。

例如:本地学生/application.properties 的密钥集:set(['APPLICATION_NAME_TEST', 'VERSION', 'S3_BUCKET'])

SSM 参数存储的密钥集(student/application.properties):set(['APPLICATION_NAME', 'VERSION', 'S3_BUCKET'])

如何将 SSM 参数存储中的 APPLICATION_NAME 键更新为APPLICATION_NAME_TEST键(存在于本地文件中)?

标签: python-3.xsetssm

解决方案


这个解决方案对我有用。

local_key_set = set(['APPLICATION_NAME_TEST', 'VERSION']);
remote_key_set= set(['APPLICATION_NAME', 'VERSION']);

local_key_list = list(local_key_set);
remote_key_list= list(local_key_set);

for i in range(0,len(local_key_list)):
    if local_key_list[i] != remote_key_list[i]:
        remote_key_list[i] = local_key_list[i]

remote_key_set = set(remote_key_list);

推荐阅读