首页 > 解决方案 > Boto3 Cloudformation 漂移状态

问题描述

我正在尝试遍历每个区域并检查堆栈是否漂移,然后打印漂移堆栈的列表。

# !/usr/bin/env python
import boto3
import time

## Create a AWS Session
session = boto3.Session(profile_name='default', region_name='us-east-1')

if __name__ == '__main__':
    ## Connect to the EC2 Service
    client = session.client('ec2')

    ## Make a list of all the regions
    response = client.describe_regions()

    for region in response['Regions']:
        name = region['RegionName']

        print("Drifted CFn in region: " + name)
        ## Connect to the CFn service in the region
        cloudformationClient = boto3.client("cloudformation")
        stacks = cloudformationClient.describe_stacks()
        detection_id = cloudformationClient.detect_stack_drift(StackName=stacks)
        for stack in stacks['Stacks']:
            while True:
                time.sleep(3)
                # sleep between api calls to prevent lockout
                response = cloudformationClient.describe_stack_drift_detection_status(
                    StackDriftDetectionId=detection_id
                )
                if response['DetectionStatus'] == 'DETECTION_IN_PROGRESS':
                    continue
                else:
                    print("Stack" + stack + " has a drift status:" + response)

我仍然是 Python 的新手,我不确定为什么它在第 22 行的 StackName 上失败,因为我知道那是我试图解析的“detect_stack_drift”中变量的名称。一些帮助将不胜感激!

标签: amazon-web-servicesamazon-cloudformationboto3

解决方案


请参阅以下几行:

stacks = cloudformationClient.describe_stacks()
detection_id = cloudformationClient.detect_stack_drift(StackName=stacks)

describe_stacks()调用返回:

{
    'Stacks': [
        {
            'StackId': 'string',
            'StackName': 'string',
            ...
        },
    ],
    'NextToken': 'string'
}

但是,该detect_stack_drift()函数需要一个字符串StackName


推荐阅读