Skip to content
Myr

fabric.rst

This file

Path

docs/patterns/fabric.rst

186 lines · 7.1 KiB

Last changed by

Merge pull request #2969 from codeaditya/update-linksDavid Lordbefore adoption7e714bd

History of this file

Take it

1.. _fabric-deployment:23Deploying with Fabric4=====================56`Fabric`_ is a tool for Python similar to Makefiles but with the ability7to execute commands on a remote server.  In combination with a properly8set up Python package (:ref:`larger-applications`) and a good concept for9configurations (:ref:`config`) it is very easy to deploy Flask10applications to external servers.1112Before we get started, here a quick checklist of things we have to ensure13upfront:1415-   Fabric 1.0 has to be installed locally.  This tutorial assumes the16    latest version of Fabric.17-   The application already has to be a package and requires a working18    :file:`setup.py` file (:ref:`distribute-deployment`).19-   In the following example we are using `mod_wsgi` for the remote20    servers.  You can of course use your own favourite server there, but21    for this example we chose Apache + `mod_wsgi` because it's very easy22    to setup and has a simple way to reload applications without root23    access.2425Creating the first Fabfile26--------------------------2728A fabfile is what controls what Fabric executes.  It is named :file:`fabfile.py`29and executed by the `fab` command.  All the functions defined in that file30will show up as `fab` subcommands.  They are executed on one or more31hosts.  These hosts can be defined either in the fabfile or on the command32line.  In this case we will add them to the fabfile.3334This is a basic first example that has the ability to upload the current35source code to the server and install it into a pre-existing36virtual environment::3738    from fabric.api import *3940    # the user to use for the remote commands41    env.user = 'appuser'42    # the servers where the commands are executed43    env.hosts = ['server1.example.com', 'server2.example.com']4445    def pack():46        # build the package47        local('python setup.py sdist --formats=gztar', capture=False)4849    def deploy():50        # figure out the package name and version51        dist = local('python setup.py --fullname', capture=True).strip()52        filename = '%s.tar.gz' % dist5354        # upload the package to the temporary folder on the server55        put('dist/%s' % filename, '/tmp/%s' % filename)5657        # install the package in the application's virtualenv with pip58        run('/var/www/yourapplication/env/bin/pip install /tmp/%s' % filename)5960        # remove the uploaded package61        run('rm -r /tmp/%s' % filename)6263        # touch the .wsgi file to trigger a reload in mod_wsgi64        run('touch /var/www/yourapplication.wsgi')6566Running Fabfiles67----------------6869Now how do you execute that fabfile?  You use the `fab` command.  To70deploy the current version of the code on the remote server you would use71this command::7273    $ fab pack deploy7475However this requires that our server already has the76:file:`/var/www/yourapplication` folder created and77:file:`/var/www/yourapplication/env` to be a virtual environment.  Furthermore78are we not creating the configuration or ``.wsgi`` file on the server.  So79how do we bootstrap a new server into our infrastructure?8081This now depends on the number of servers we want to set up.  If we just82have one application server (which the majority of applications will83have), creating a command in the fabfile for this is overkill.  But84obviously you can do that.  In that case you would probably call it85`setup` or `bootstrap` and then pass the servername explicitly on the86command line::8788    $ fab -H newserver.example.com bootstrap8990To setup a new server you would roughly do these steps:91921.  Create the directory structure in :file:`/var/www`::9394        $ mkdir /var/www/yourapplication95        $ cd /var/www/yourapplication96        $ virtualenv --distribute env97982.  Upload a new :file:`application.wsgi` file to the server and the99    configuration file for the application (eg: :file:`application.cfg`)1001013.  Create a new Apache config for ``yourapplication`` and activate it.102    Make sure to activate watching for changes of the ``.wsgi`` file so103    that we can automatically reload the application by touching it.104    (See :ref:`mod_wsgi-deployment` for more information)105106So now the question is, where do the :file:`application.wsgi` and107:file:`application.cfg` files come from?108109The WSGI File110-------------111112The WSGI file has to import the application and also to set an environment113variable so that the application knows where to look for the config.  This114is a short example that does exactly that::115116    import os117    os.environ['YOURAPPLICATION_CONFIG'] = '/var/www/yourapplication/application.cfg'118    from yourapplication import app119120The application itself then has to initialize itself like this to look for121the config at that environment variable::122123    app = Flask(__name__)124    app.config.from_object('yourapplication.default_config')125    app.config.from_envvar('YOURAPPLICATION_CONFIG')126127This approach is explained in detail in the :ref:`config` section of the128documentation.129130The Configuration File131----------------------132133Now as mentioned above, the application will find the correct134configuration file by looking up the ``YOURAPPLICATION_CONFIG`` environment135variable.  So we have to put the configuration in a place where the136application will able to find it.  Configuration files have the unfriendly137quality of being different on all computers, so you do not version them138usually.139140A popular approach is to store configuration files for different servers141in a separate version control repository and check them out on all142servers.  Then symlink the file that is active for the server into the143location where it's expected (eg: :file:`/var/www/yourapplication`).144145Either way, in our case here we only expect one or two servers and we can146upload them ahead of time by hand.147148149First Deployment150----------------151152Now we can do our first deployment.  We have set up the servers so that153they have their virtual environments and activated apache configs.  Now we154can pack up the application and deploy it::155156    $ fab pack deploy157158Fabric will now connect to all servers and run the commands as written159down in the fabfile.  First it will execute pack so that we have our160tarball ready and then it will execute deploy and upload the source code161to all servers and install it there.  Thanks to the :file:`setup.py` file we162will automatically pull in the required libraries into our virtual163environment.164165Next Steps166----------167168From that point onwards there is so much that can be done to make169deployment actually fun:170171-   Create a `bootstrap` command that initializes new servers.  It could172    initialize a new virtual environment, setup apache appropriately etc.173-   Put configuration files into a separate version control repository174    and symlink the active configs into place.175-   You could also put your application code into a repository and check176    out the latest version on the server and then install.  That way you177    can also easily go back to older versions.178-   hook in testing functionality so that you can deploy to an external179    server and run the test suite.180181Working with Fabric is fun and you will notice that it's quite magical to182type ``fab deploy`` and see your application being deployed automatically183to one or more remote servers.184185186.. _Fabric: https://www.fabfile.org/