How to use awscli inside python script?

2019-03-24 01:01发布

I'm using aws ec2 service with awscli. Now I want to put all the commands I type in the console into a python script. I see that if I write import awscli inside a python script it works fine but I don't understand how to use it inside the script. For instance how do I execute the commands aws ec2 run-instances <arguments> inside the python script after import awscli? Just to make it clear, I'm not looking for a solution like os.system('aws ec2 run-instances <arguments>'), I'm looking for something like

import awscli
awscli.ec2_run-instances(<arguments>)

3条回答
劫难
2楼-- · 2019-03-24 01:25

The CLI would be more suited for the shell prompt, for a better python API, check the boto library. This example shows how to launch an instance: http://boto.readthedocs.org/en/latest/ec2_tut.html

查看更多
狗以群分
3楼-- · 2019-03-24 01:26

Boto3 doesn't have everything the cli has so you may have to use something from the cli in a script once in a blue moon. I can't find an analog for aws deploy push in boto3 for example so here is how I push to s3 with the cli from a python script. Although to Julio's point, I use boto for everything else.

import subprocess

cmd='aws deploy push --application-name SomeApp --s3-location  s3://bucket/Deploy/db_schema.zip --ignore-hidden-files' 
push=subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)
print push.returncode
查看更多
爷的心禁止访问
4楼-- · 2019-03-24 01:38

You can do it with brilliant sh package. You could mimic python package with sh doing wrapping for you.

import sh
s3 = sh.bash.bake("aws s3")
s3.put("file","s3n://bucket/file")
查看更多
登录 后发表回答