gpt4 book ai didi

使用环境名称对 cloudformation 堆栈进行 Python 过滤

转载 作者:行者123 更新时间:2023-12-03 07:23:55 30 4
gpt4 key购买 nike

更新的问题:我需要根据环境获取cloudformation堆栈。下面是我为此使用的代码:

#!/usr/bin/env python

import boto3
import datetime
from datetime import date
import subprocess
import re, itertools

from collections import defaultdict

regions = ['us-west-2']

env_names = ["dev", "test", "stage"]

stack_names_found = defaultdict(list)

for region in regions:
session = boto3.session.Session(region_name=region)
cf_client = session.resource('cloudformation')
for i in cf_client.stacks.all():
StackStatus = i.stack_status
Createdtime = i.creation_time
StackName1 = i.stack_name

for env_name in env_names:
if ('-' + env_name + '-') in StackName1:
stack_names_found[env_name].append(StackName1)
output = {'StackName': stack_names_found,
'Createdtime': Createdtime,
'Status': StackStatus
}
print(output)

输出中的 StackName 如下所示:

{'StackName':defaultdict(<class 'list'>, {'test': ['customer1-test-server1', 'customer2-test-server1', 'customer3-test-server1','customer3-test-server1', 'customer1-test-server2]})

而不是:

['customer1-test-server1']
['customer2-test-server1']
['customer3-test-server1']
['customer3-test-server1']

最佳答案

您可以看一下下面的版本,它使用defaultdict并为每个 env_name 创建堆栈名称字典:

#!/usr/bin/env python

import boto3
import csv
import datetime
from datetime import date
import subprocess
import re, itertools

from collections import defaultdict

regions = ['us-west-2']

env_names = ["dev", "test", "stage"]

stack_names_found = defaultdict(list)

for region in regions:
session = boto3.session.Session(region_name=region)
cf_client = session.resource('cloudformation')
for i in cf_client.stacks.all():
StackStatus = i.stack_status
Createdtime = i.creation_time
StackName1 = i.stack_name

for env_name in env_names:
if ('-' + env_name + '-') in StackName1:
stack_names_found[env_name].append(StackName1)

print(stack_names_found)

请注意,我尚未运行该代码,因此可能需要进行一些调整才能使其完全运行。

关于使用环境名称对 cloudformation 堆栈进行 Python 过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65203475/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com