平时我们一般情况下是直接使用webconsole 或者直接使用aws cli来执行我们想要的命令,但是有些时候我们却要对结果进行分析,也就是,我们有时候需要在python里调用aws命令
简单第一种方法就是直接使用Python 的subprocess方法,调用系统命令,直接执行awscli命令,例如查询ecr的命令:
1 |
aws ecr describe-images --repository-name |
另外一种方法就是使用boto3
boto3是专为python设计的用来调用aws 接口的,官方文档:
https://boto3.amazonaws.com/v1/documentation/api/latest/index.html
我们可以在Python代码中很容易的调用aws 的接口来获取 ec2 , ELB, ami等等各种资源
例如上边的例子:
我们可以使用如下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#!/usr/bin/python # vim: expandtab:tabstop=4:shiftwidth=4 ''' script to get ecr info ''' # Reason: disable invalid-name because pylint does not like our naming convention # pylint: disable=invalid-name import boto3 import sys import argparse def get_taginfo(repo_name): client = boto3.client('ecr', region_name='us-east-1') response = client.describe_images( repositoryName=repo_name ) print(response) def main(): parser=argparse.ArgumentParser(description='''get the images for your repo''') parser.add_argument('-s', '--service', required=True, help="repo name that you want to check ") args=parser.parse_args() repo_name = args.service get_taginfo(repo_name) if __name__ == "__main__": main() |
上边的脚本的内容是帮你查找你账号下你输入的repo名字下的所有image信息,注意,此脚本需要你已经在本地设定好了aws credential ,脚本会读取环境变量里边的设置
更多关于boto3 对于ECR的操作可以参考
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ecr.html
Latest posts by Zhiming Zhang (see all)
- aws eks node 自动化扩展工具 Karpenter - 8月 10, 2022
- ReplicationController and ReplicaSet in Kubernetes - 12月 20, 2021
- public key fingerprint - 5月 27, 2021