首页 > 解决方案 > 描述 EFS 文件系统的 Python 脚本

问题描述

我正在编写一个 python 脚本,该脚本的目的是描述 EFS 中的文件系统并查找一些元数据条目。

这是代码片段:

import boto3
from collections import defaultdict
from utils.utils import get_accounts, get_efs_client
import csv
import os
import sys

THIS_DIR = os.path.dirname(os.path.realpath(__file__))
ROOT = os.path.dirname(THIS_DIR)
sys.path.append(ROOT)

aws_regions = ['ap-northeast-1', 'ap-southeast-1', 'ca-central-1', 'us-east-1', 'us-east-2', 'eu-west-1', 'eu-west-2']

# To create header of the file
header_csv = ['S_No', 'account_id', 'account_name', 'fs_arn', 'fs_id', 'fs_kms']

S_No = 0

filename = "output.csv"

file = open(filename, 'w', newline='\n', encoding='utf-8')
writer = csv.writer(file, lineterminator='\n')
writer.writerow(header_csv)

MY_ROLE_NAME = input("Enter the assigned role:")
os.environ['AWS_SHARED_CREDENTIALS_FILE'] = "C:/Downloads/credentials"
ACCOUNT_NUMBER = input("Enter the account id from where we can list all the AWS accounts that exists in the organizations:")


def list_efs_encryption_types():

    accounts = get_accounts(f"arn:aws:iam::{ACCOUNT_NUMBER}:role/{MY_ROLE_NAME}")
    for account, account_name in accounts.items():
        print(f"{account}:{account_name}")
        for region_val in aws_regions:
            client = boto3.client(service_name='efs', region_name=region_val)
            response = client.describe_file_systems()
            for file_system in response['FileSystems']:

                def default_value():
                    return "No value yet"   

                # use of defaultdict feature to replace keyError with user defined value
                file_system = defaultdict(lambda: default_value, file_system)
                
                fs_arn = file_system['FileSystemArn']
                fs_id = file_system['FileSystemId']
                fs_kms = file_system['KmsKeyId']
                print(f"The file system arn is: {fs_arn} with file id {fs_id} and encrypted with {fs_kms} kms key")

                # output it to the CSV file
                global S_No
                writer.writerow([S_No, account, account_name, fs_arn, fs_id, fs_kms])
                S_No += 1
                    
                # conditional check on encryption status of fs_kms
                if fs_kms == 'No value yet':
                    return f"{fs_arn} is unencrypted"
                else:
                    return f"{fs_arn} is encrypted"

def main():
    return list_efs_encryption_types()


if __name__ == "__main__":
    main()

file.close()

我的代码正在运行文件,但它既不打印输出也不将数据存储到 csv 文件中。

有人可以帮助我代码中的错误是什么,它不允许我打印输出并将数据获取到 csv 文件中。

谢谢

标签: python-3.xamazon-web-servicesboto3amazon-efs

解决方案


推荐阅读