python-3.x - 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 个条件:
- 当 SSM 参数存储为空时,如果 remote_key_vals 集的长度为 0(如不存在 ssm 参数),则将创建/加载本地 application.properties 文件。
- 当 local_key_vals 中的值多于 remote_key_vals 时。我计算了两组的差异并更新了参数存储(application.properties 文件)中的差异
- 如果本地 application.properties 文件不再具有该键/值,则从 SSM 参数存储中删除一个值。
我需要处理两个集合的大小相同的情况,本地 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键(存在于本地文件中)?
解决方案
这个解决方案对我有用。
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);
推荐阅读
- android - 禁用 Firebase 分析和应用性能
- sql - 更新 SQL Server 中的多条记录
- sql-server - MSSQL - 根据 SSMS 版本更新语句不同的结果
- php - SQL,在计算两次之间的差异时插入表
- angular - 影响所有 App HttpRequests 的组件内的 HttpInterceptor
- mysql - 如何根据选定的 id 列出所有重复项
- javascript - Django在使用ajax时不呈现数据
- math - 获取要在 Sphinx 中显示的多行文档字符串方程。狮身人面像中的潜在错误?
- elasticsearch - Kubernetes - 将 pod 关联性规则应用于实时部署