问题描述
我的目标是拥有一个lambda来解析cloudformation堆栈漂移资源,然后打印出所有已修改的安全组的列表。
import boto3
cfn_client = boto3.client('cloudformation')
drifts = cfn_client.describe_stack_resource_drifts(
StackName='my_stack>',StackResourceDriftStatusFilters=[
'MODIFIED',],MaxResults=100
)
哪个返回dict响应(我只包括了与问题相关的字段):
{
'ResponseMetadata': {
'RetryAttempts': 0,'HTTPStatusCode': 200,'RequestId': '12b1f618-722e-4b08-9534-123','HTTPHeaders': {
'content-type': 'text/xml','content-length': '118369','vary': 'accept-encoding','date': 'Tue,18 Aug 2020 11:11:38 GMT'
}
},u 'StackResourceDrifts': [{
u 'StackId': 'arn:aws:cloudformation:eu-west-1:12345678:stack/my_stack/12345,u 'ResourceType': 'AWS::EC2::SecurityGroup',u 'PhysicalResourceId': 'sg-987654321xyz',u 'StackResourceDriftStatus': 'MODIFIED',u 'LogicalResourceId': 'MySecGrp1'
},{
u 'StackId': 'arn:aws:cloudformation:eu-west-1:12345678:stack/my_stack/12345,u 'ResourceType': 'AWS::ElasticLoadBalancingV2::TargetGroup',u 'PhysicalResourceId': 'arn:aws:elasticloadbalancing:eu-west-1:12345678:targetgroup/my_resource_id',u 'LogicalResourceId': 'NyTargerGroup1'
},u 'ResourceType': 'AWS::EC2::Instance',u 'PhysicalResourceId': 'i-123456789xyz',u 'LogicalResourceId': 'MyServer1'
},u 'PhysicalResourceId': 'sg-123456789xyz',u 'LogicalResourceId': 'MySecGrp2'
}]
}
我正在尝试打印PhysicalResourceId
== LogicalResourceId
的{{1}}和ResourceType
。一个响应中可能有多个。
到目前为止,我只能看到如何返回特定值,但与我仍然需要的还有很长的距离:AWS::EC2::SecurityGroup
我是Python的新手,希望能帮助您实现此目标。
解决方法
尝试一下。最终将是字典列表。
final = []
for item in drifts['StackResourceDrifts']:
if item['ResourceType'] == 'AWS::EC2::SecurityGroup':
final.append({'PhysicalResourceId': item['PhysicalResourceId'],'LogicalResourceId': item['LogicalResourceId']
})
print(final)