简体   繁体   English

如何使用Fabric访问AWS的动态EC2库存?

[英]How to access AWS's dynamic EC2 inventory using Fabric?

Fabric has a hosts setting to specify which computers to SSH into. Fabric具有主机设置,用于指定要通过SSH连接到的计算机。

Amazon Web Services has more of a dynamic inventory that can be queried in python using tools like boto . Amazon Web Services具有更多动态清单,可以使用诸如boto之类的工具在python中查询。

Is there a way to combine these two services? 有没有办法将这两种服务结合起来? Ideally, I wanted something as simple as ansible 's approach with an inventory file and using an external file like ec2.py . 理想情况下,我想是这样简单的事情ansible的与清单文件的方法,并使用像一个外部文件ec2.py

More specifically, is there a prebaked solution for this use case? 更具体地说,是否有针对该用例的预烘焙解决方案? Ideally, I would like to run something straightforward like this: 理想情况下,我想直接执行以下操作:

from fabric.api import env, task
import ec2
env.roledefs = ec2.Inventory()

@task
def command():
    run("lsb_release -a")

And run it like so, assuming env.roledefs['nginx'] exists: 并假设env.roledefs['nginx']存在,以env.roledefs['nginx']运行:

$ fab -R nginx command

You can use fabric and boto concurrently. 您可以同时使用Fabric和Boto。 First you need to export the aws_secret_key, aws_secret_access_key and default regions from your console. 首先,您需要从控制台导出aws_secret_key,aws_secret_access_key和默认区域。 Fabric file name should be fabfile.py and should not ec2.py/other. 架构文件名应为fabfile.py,而不应为ec2.py/other。

import boto, urllib2
from   boto.ec2 import connect_to_region
from   fabric.api import env, run, cd, settings, sudo
from   fabric.api import parallel
import os
import sys
REGION       = os.environ.get("AWS_EC2_REGION")
env.user      = "ec2-user"
env.key_filename = ["/home/user/uswest.pem"]
@task
def command():
    run("lsb_release -a")
def _create_connection(region):
    print "Connecting to ", region
    conn = connect_to_region(
        region_name = region, 
        aws_access_key_id=os.environ.get("AWS_ACCESS_KEY_ID"), 
        aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY")
    )
    print "Connection with AWS established"
    return connection

Finally this program can be executed by using below command. 最后,可以使用以下命令执行该程序。

$ fab command

From http://docs.python-guide.org/en/latest/scenarios/admin/ http://docs.python-guide.org/en/latest/scenarios/admin/

You can see that if you set env.hosts = ['my_server1', 'my_server2'] 您可以看到,如果设置env.hosts = ['my_server1','my_server2']

You'll then be able to target those hosts. 然后,您可以定位那些主机。

With boto, if you just have a function that does ec2_connection.get_only_instances(filter={'tag':< whatever>}) and returns a list of their dns names, you'll be able to then set env.hosts = [< list of dns names from ec2>] 使用boto,如果您只有一个执行ec2_connection.get_only_instances(filter = {'tag':<what>}}并返回其dns名称列表的函数,则可以设置env.hosts = [< ec2中的DNS名称列表>]

Piece of cake! 小菜一碟!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM