Does python fabric support dynamic set env.hosts?

前端 未结 3 1337
误落风尘
误落风尘 2021-02-04 01:41

I want to change the env.hosts dynamically because sometimes I want to deploy to one machine first, check if ok then deploy to many machines. Currently I need to set env.hosts f

3条回答
  •  旧巷少年郎
    2021-02-04 02:23

    Yet another new answer to an old question. :) But I just recently found myself attempting to dynamically set hosts, and really have to disagree with the main answer. My idea of dynamic, or at least what I was attempting to do, was take an instance DNS-name that was just created by boto, and access that instance with a fab command. I couldn't do fab staging deploy, because the instance doesn't exist at fabfile-editing time.

    Fortunately, fabric does support a truly dynamic host-assignment with execute. (It's possible this didn't exist when the question was first asked, of course, but now it does). Execute allows you to define both a function to be called, and the env.hosts it should use for that command. For example:

    def create_EC2_box(data=fab_base_data):
        conn = boto.ec2.connect_to_region(region)
        reservations = conn.run_instances(image_id=image_id, ...)
        ...
        return instance.public_dns_name
    
    def _ping_box():
        run('uname -a')
        run('tail /var/log/cloud-init-output.log')
    
    def build_box():
        box_name = create_EC2_box(fab_base_data)
        new_hosts = [box_name]
        # new_hosts = ['ec2-54-152-152-123.compute-1.amazonaws.com'] # testing
        execute(_ping_box, hosts=new_hosts)
    

    Now I can do fab build_box, and it will fire one boto call that creates an instance, and another fabric call that runs on the new instance - without having to define the instance-name at edit-time.

提交回复
热议问题