首页 > 解决方案 > 我如何在python中编写aws cli命令

问题描述

我是 AWS 和 Python 的新手。

AWS CLI,以下命令运行良好:

aws cloudformation package --template-file sam.yaml --output-template-file output-sam.yaml --s3-bucket <<bucket_Name>>

目标是创建将运行上述命令的自动化 python 脚本。我试图用谷歌搜索它,但没有一个解决方案对我有用。

以下是我尝试过但无法将工件上传到 S3 存储桶的解决方案。

test.py 文件:

import subprocess
command= ["aws","cloudformation","package","--template-file","sam.yaml","--output-template-file","output-sam.yaml","--s3-bucket","<<bucket_name>>"]
print(subprocess.check_output(command, stderr=subprocess.STDOUT))

标签: pythonamazon-web-services

解决方案


它可以使用 os 库轻松完成。代码中给出了最简单的方法。

import os
os.system("aws cloudformation package --template-file sam.yaml --output-template-file output-sam.yaml --s3-bucket <<bucket_name>>")

但是,子流程可以用于稍微复杂的任务。您还可以查看 boto3 库以执行此类任务。Boto 是适用于 Python 的 AWS 开发工具包。


推荐阅读