Package: cf-api
Python Cloud Foundry API ClientThis module provides a pure Python interface to the Cloud Foundry APIs.InstallationYou can install from PIPpip install cf-apior view it onPyPI.DocumentationSee the docs athttps://cf-api.readthedocs.io/en/latest/or in the./docsdirectory and the./examplesdirectory.VersioningVersion 1.xSupport both Python 2.7/3.6-3.8Removecf_api.dropsondemodule in favor of thedropsondemodule.Add CF API version 3 supportAddDockerfileexampleVersion 0.xSupports Python 2.7Getting StartedThe following examples should be enough to get you started using this library.# Initializing the Cloud Controller clientfromgetpassimportgetpassimportcf_apiimportjsoncloud_controller='https://api.yourcloudfoundry.com'deploy_client_id='cf'deploy_client_secret=''verify_ssl=Trueusername='youser'password=getpass('Password: ').strip()cc=cf_api.new_cloud_controller(cloud_controller,client_id=deploy_client_id,client_secret=deploy_client_secret,username=username,password=password,).set_verify_ssl(verify_ssl)# List all organizationsreq=cc.organizations()res=req.get()orgs=res.resourcesforrinorgs:print('org',r.guid,r.name)# List all spacesres=cc.spaces().get()spaces=res.resourcesforrinspaces:print('space',r.guid,r.name)# List all applicationsres=cc.apps().get()apps=res.resourcesforrinapps:print('app',r.guid,r.name)# Find an app by it's org/space/nameorg_name='your_org'space_name='your_space'app_name='your_app'# find your org by nameres=cc.organizations().get_by_name(org_name)# you can access the first array resource using the `resource` attributeyour_org=res.resource# find your space by name within your orgres=cc.request(your_org.spaces_url).get_by_name(space_name)your_space=res.resource# find your app by name within your spaceres=cc.request(your_space.apps_url).get_by_name(app_name)your_app=res.resourceprint('your_app',your_app)# Find an app by it's GUID## Note that this same pattern applies to all Cloud Controller resources#res=cc.apps(your_app.guid).get()# you can also use the `resource` attribute to access a response with a# non-array resultyour_same_app=res.resourceprint('your_same_app',your_same_app)# Find a stack by nameyour_stack='some_stack'res=cc.stacks().get_by_name(your_stack)stack=res.resource# Create an appyour_buildpack='some_buildpack'command='python server.py'res=cc.apps().set_params(name=app_name,space_guid=your_space.guid,stack_guid=stack.guid,buildpack=your_buildpack,command=command,health_check_type='port',health_check_timeout=60,instances=2,memory=512,disk_quota=512).post()print('new app',res.data)# Upload the bits for an appmy_zipfile='/tmp/app.zip'withopen(my_zipfile,'r')asf:res=cc.apps(your_app.guid,'bits')\.set_query(async='true')\.add_field('resources',json.dumps([]))\.add_file('application','application.zip',f,'application/zip')\.put()print(res.data)Running in DockerTo get start runningcf_apiin Docker, just build the providedDockerfileyou@yourhost:~/python-cf-api$ docker build -t python-cf-api:latest .and run it using the following syntax.you@yourhost:~/python-cf-api$ docker run --rm -it -v $PWD:/src -w /src python-cf-api:latest python3
Python 3.8.1
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cf_api
>>> # play with it hereUsing CF API version 3The following example shows how to use the Cloud Foundry version 3 API.importcf_apicc=cf_api.new_cloud_controller()req=cc.v3.apps()res=req.get()print(res.resource.guid)Thecc.v3attribute returns aCloudControllerinstance that is configured
to wrap requests and responses in V3 compatible classes, namelyV3CloudControllerRequestandV3CloudControllerResponse. These objects work similarly to their v2 counterparts,CloudControllerRequestandCloudControllerResponse.TheV3CloudControllerResponseprovidesresourceandresourceswhich return
an instance or list of instances ofV3Resourceobjects which support the
common API object keys such asname,guid,space_guid, andorg_guid, etc.Thecc.v3.get_all_resources()function supports both v2 and v3 pagination.Thecc.v3.request()function supportsbothrelative URLs and absolute URLs,
for example/v3/appsandhttp://localhost/v3/apps, respectively. Seerequest()function documentation for more information.Environment VariablesThe library is also configurable via environment variables.VariableDescriptionPYTHON_CF_URLThis is the cloud controller base URL.Do not include a trailing slash on the URL.PYTHON_CF_CLIENT_IDThis is the UAA client ID the library should use.PYTHON_CF_CLIENT_SECRETThis is the UAA client secret the library should use.PYTHON_CF_IGNORE_SSLThis indicates whether to verify SSL certs. Default is false. Set totrueto ignore SSL verification.CF_DOCKER_PASSWORDThis variable optionally provides the Docker user's password if a docker image is being used. This variable is not necessarily required to use a docker image.An example library usage with these variables set would look like this:# env vars might be set as follows# PYTHON_CF_URL=https://api.cloudfoundry.com# PYTHON_CF_CLIENT_ID=my_client_id# PYTHON_CF_CLIENT_SECRET=my_client_secretimportcf_api# no args are required when the above env vars are detectedcc=cf_api.new_cloud_controller()res=cc.apps().get()# ...# the same principle applies to new_uaa()uaa=cf_api.new_uaa()# ...Log in with Cloud Foundry Authorization CodeThe following functions may be used to implement login with Cloud Foundry via Authorization Codes.The functionget_openid_connect_url()shows how to build UAA URL to which the user can be
redirected in order to log in.The functionverify_code()can be used when the user successfully logs in and UAA redirects back
to redirect_uri with thecodeattached. Pass the code and original redirect_uri into this function
in order to get the OAuth2 Token and to also verify the signature of the JWT.This particular example applies to OpenID Connect.importcf_apicc='https://api.yourcloudfoundry.com'client_id='yourclient'client_secret='yoursecret'response_type='code'defget_openid_connect_url(redirect_uri):returncf_api\.new_uaa(cc=cc,client_id=client_id,client_secret=client_secret,no_auth=True)\.authorization_code_url(response_type,scope='openid',redirect_uri=redirect_uri)defverify_code(code,redirect_uri):uaa=cf_api.new_uaa(cc=cc,client_id=client_id,client_secret=client_secret,no_auth=True)res=uaa.authorization_code(code,response_type,redirect_uri)data=res.datauaa.verify_token(data['id_token'],audience=uaa.client_id)returndataDeploy an ApplicationThecf_api.deploy_manifestmodule may be used to deploy a Cloud Foundry app. The
following snippet demonstrates the usage for deploying an app.cdpath/to/your/project
python-mcf_api.deploy_manifest\--cloud-controllerhttps://api.yourcloudfoundry.com\-uyouser-oyourg-syourspace\-mmanifest.yml-v-w# For the CLI usage of deploy_manifest, you may also set#   the CF_REFRESH_TOKEN environment variable as a substitute#   for collecting username and passwordThis module may also be used programmatically.from__future__importprint_functionimportcf_apifromgetpassimportgetpassfromcf_api.deploy_manifestimportDeploycc=cf_api.new_cloud_controller('https://api.yourcloudfoundry.com',username='youruser',password=getpass().strip(),client_id='cf',client_secret='',verify_ssl=True)manifest_filename='path/to/manifest.yml'apps=Deploy.parse_manifest(manifest_filename,cc)forappinapps:app.set_debug(True)app.set_org_and_space('yourorg','yourspace')print(app.push())# print (app.destroy(destroy_routes=True))Deploy a ServiceThecf_api.deploy_servicemodule may be used to deploy a Cloud Foundry service to a space. The
following snippet demonstrates the usage for deploying a service.cdpath/to/your/project
python-mcf_api.deploy_service\--cloud-controllerhttps://api.yourcloudfoundry.com\-uyouser-oyourg-syourspace\--nameyour-custom-service-name--service-namecf-service-type\--service-plancf-service-type-plan-v-wThis module may also be used programmatically.from__future__importprint_functionimportcf_apifromgetpassimportgetpassfromcf_api.deploy_serviceimportDeployServicecc=cf_api.new_cloud_controller('https://api.yourcloudfoundry.com',username='youruser',password=getpass().strip(),client_id='cf',client_secret='',verify_ssl=True)service=DeployService(cc)\.set_debug(True)\.set_org_and_space('yourorg','yourspace')result=service.create('my-custom-db','database-service','small-database-plan')print(result)Query a SpaceThecf_api.deploy_spacemodule provides a convenience interface for working with Cloud Foundry
spaces. The module provides read-only (i.e. GET requests only) support for the Cloud Controller API
endpoints scoped to a specific space i.e. /v2/spaces/<space_guid>/(routes|service_instances|apps).
The following snippet demonstrates the usage for listing apps for in a space.cdpath/to/your/project
python-mcf_api.deploy_space\--cloud-controllerhttps://api.yourcloudfoundry.com\-uyouser-oyourg-syourspaceappsThis module may also be used programmatically.from__future__importprint_functionimportcf_apifromgetpassimportgetpassfromcf_api.deploy_spaceimportSpacecc=cf_api.new_cloud_controller('https://api.yourcloudfoundry.com',username='youruser',password=getpass().strip(),client_id='cf',client_secret='',verify_ssl=True)space=Space(cc,org_name='yourorg',space_name='yourspace')# create the spacespace.create()# destroy the spacespace.destroy()# make a Cloud Controller request within the spaceapps_in_the_space=space.request('apps').get()# deploys an application to this spacespace.deploy_manifest('/path/to/manifest.yml')# push the appspace.wait_manifest('/path/to/manifest.yml')# wait for the app to startspace.destroy_manifest('/path/to/manifest.yml')# destroy the appapp=space.get_app_by_name('yourappname')# find an application by its name within the space# deploy a service in this spacespace.get_deploy_service().create('my-custom-db','database-service','small-database-plan')service=space.get_service_instance_by_name('my-custom-db')# find a service by its name within the spaceTail Application LogsThecf_api.logs_utilmodule may be used to tail Cloud Foundry application logs. Bothrecentlogsandstreammodes are supported. The following snippet demonstrates the usage for
listing recent logs and tailing app logs simultaneously.cdpath/to/your/project
python-mcf_api.logs_util\--cloud-controllerhttps://api.yourcloudfoundry.com\-uyouser-oyourg-syourspace-ayourapp\-r-tThis module may also be used programmatically.from__future__importprint_functionimportcf_apifromgetpassimportgetpassfromcf_apiimportdropsonde_utilcc=cf_api.new_cloud_controller('https://api.yourcloudfoundry.com',username='youruser',password=getpass().strip(),client_id='cf',client_secret='',verify_ssl=True,init_doppler=True)app_guid='your-app-guid'app=cc.apps(app_guid).get().resource# get recent logslogs=cc.doppler.apps(app.guid,'recentlogs').get().multipart# convert log envelopes from protobuf to dictlogs=[dropsonde_util.parse_envelope_protobuf(log)forloginlogs]print(logs)# stream logsws=cc.doppler.ws_request('apps',app.guid,'stream')try:ws.connect()ws.watch(lambdam:print(dropsonde_util.parse_envelope_protobuf(m)))exceptExceptionase:print(e)finally:ws.close()