Friday, 21 September 2018

Deploying to PyPi from from travis-ci

When building a python project, it's very common to want to deploy to PyPi. To save effort you can have travis-ci automatically deploy for you.

Insecure Method

The most basic (and insecure) way to do this is to add a deploy step to your .travis.yml file, that specifies your PyPi username and password.

1
2
3
4
deploy:
  provider: pypi
  user: "Your username"
  password: "Your password"

This will always deploy the master branch of your project, but unfortunately it exposes your PyPi username and password.

Secure Method

To secure your password you can use the travis command line client, to generate an encrypted password and add this to your deploy configuration. To do this, navigate to your repository and run the following:

1
2
3
4
5
6
7
$ travis encrypt mypassword
Detected repository as me/myproject, is this correct? |yes| y
Please add the following to your .travis.yml file:
 
  secure: "encrypted password"
 
Pro Tip: You can add it automatically by running with --add.

Add the secure section under the password in .travis.yml or as mentioned in the output use the --add option to do this automatically.

1
2
3
4
5
deploy:
  provider: pypi
  user: "Your username"
  password:
    secure: "encrypted password"

Limit to only Tagged Releases

The above method, will deploy your master branch to pypi. However, it's likely you only want tagged releases to be uploaded to pypi. To limit this you can use the on section to say if you only want to release tags.

1
2
3
4
5
6
7
deploy:
  provider: pypi
  user: "Your username"
  password:
    secure: "encrypted password"
  on:
    tags: true

Using Test PyPi instance

The test PyPi instance is a playground for testing if your deployment to PyPi would work. If you are testing the above deploys, you may want to first deploy to this test instance to confirm that everything works. To do this you can use the server variable to specify that you want to use the test pypi instance.

1
2
3
4
5
6
7
8
deploy:
  provider: pypi
  server: https://test.pypi.org/legacy/ # Remove for deployment to official PyPi repo
  user: "Your username"
  password:
    secure: "encrypted password"
  on:
    tags: true

This will send your python package to the test pypi server.

Note: Remember to change your encrypted password to the one you use for the test PyPi instance.

Note: This method can also be used for a self hosted PyPi instance.