Cloud Volumes APIs

The cloud volumes capabilities that are available through the web UI are also available through RESTful APIs. The APIs enable you to programmatically create and manage cloud volumes. They also provide the capability to develop scripts and tools for provisioning and support other service workflows.

Creating your service account and private key

  1. In Cloud Shell, create a service account in your project:

    gcloud iam service-accounts create serviceaccountname \
        --description "Admin SA for CVS API access" \
        --display-name "cloudvolumes-admin-sa"
    
  2. Assign the NetApp cloud volumes admin role to the service account. Replace projectname and serviceaccount@projectname with your project name and with the service account you just created.

    gcloud projects add-iam-policy-binding projectname \
        --member='serviceAccount:serviceaccount@projectname.iam.gserviceaccount.com' \
        --role='roles/netappcloudvolumes.admin'
    
  3. Confirm the role bindings for the service account and project:

    gcloud projects get-iam-policy projectname
    

    The output looks something like this:

    output from get-iam-policy

  4. Create and download your private key file.

    gcloud iam service-accounts keys create key_file_name --iam-account serviceaccount@projectname>
    

You have created the private key file that can be used to generate an authorization token to securely make the API calls. See Creating and managing service accounts

View the NetApp Cloud Volumes API Swagger specification

To view the NetApp Cloud Volumes API Swagger specification with Swagger Editor, do the following:

  1. Go to Swagger Editor.
  2. Select File > Import URL.
  3. Enter the following URL:

    https://cloudvolumesgcp-api.netapp.com/swagger.json

  4. Click OK.

    The Cloud Volumes APIs (CVS-GCP) are displayed.

Examples of using the Cloud Volumes APIs

The following examples use Python to interact with the Cloud Volumes APIs.

In this example, the script makes a call to get all volumes in a given project and print out their details. The private key file belongs to a service account that has the netappcloudvolumes.admin role assigned to it. Note how the authentication token is obtained and used in the request headers.

import google.auth
import google.auth.transport.requests
import requests
import json
from google.auth import jwt
from google.oauth2 import service_account
from google.oauth2 import id_token

# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
    return bytes/1024/1024/1024

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/home/username/keys/prj-10-31e8f6d0c17e.json'
project_number = 1234567890

# Get all volumes from all regions
get_url = server + "/v2/projects/" + str(project_number) + "/locations/-/Volumes"

# Create credential object from private key file
svc_creds = service_account.Credentials.from_service_account_file(
    service_account_file)

# Create jwt
jwt_creds = jwt.Credentials.from_signing_credentials(
    svc_creds, audience=audience)

# Issue request to get auth token
request = google.auth.transport.requests.Request()
jwt_creds.refresh(request)

# Extract token
id_token = jwt_creds.token

# Construct GET request
headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + id_token.decode('utf-8')
        }

# Issue the request to the server
r = requests.get(get_url, headers=headers)

# Load the json response into a dict
r_dict = r.json()

# Print out all vols
print ("Response to GET request: " + get_url)
for vol in r_dict:
    # Get volume attributes
    volname = vol["name"]
    volsizeGiB = convertToGiB(vol["quotaInBytes"])
    region = vol["region"]
    print ("\tvolname: " + volname + ", size: " + str(volsizeGiB) + "GiB, region: " + region)

Output

The result of running this script varies based on what volumes exist in your project. The output should be similar to the following:

Response to GET request: https://cloudvolumesgcp-api.netapp.com/v2/projects/1234567890/locations/-/Volumes
     volname: launch, size: 1024.0GiB, region: us-east4
     volname: centraltest, size: 1024.0GiB, region: us-central1
     volname: launch, size: 1024.0GiB, region: us-central1

Get a token

import google.auth
import google.auth.transport.requests
from google.auth import jwt
from google.oauth2 import service_account

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/Users/your-username/Downloads/ncv-beta-demo-eccee8711557.json'
project_number = 779740114201

# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
    return bytes/1024/1024/1024

def get_token():
    # Create credential object from private key file
    svc_creds = service_account.Credentials.from_service_account_file(
        service_account_file)

    # Create jwt
    jwt_creds = jwt.Credentials.from_signing_credentials(
        svc_creds, audience=audience)

    # Issue request to get auth token
    request = google.auth.transport.requests.Request()
    jwt_creds.refresh(request)

    # Extract token
    id_token1 = jwt_creds.token
    print("Token :", id_token1)
    return id_token1

get_token()

Output

The output should be similar to the following:

Token: “You will see your token here”

Create an NFSv3 volume

import google.auth
import google.auth.transport.requests
import requests
import json
import time
from google.auth import jwt
from google.oauth2 import service_account

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/Users/example-user/Downloads/ncv-beta-demo-eccee8711557.json'
project_number = 123456789  # Enter your project number here
location = "us-central1"
volumeIDdetails = "Enter your Volume ID here"

# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
    return bytes/1024/1024/1024

def get_token():
    # Create credential object from private key file
    svc_creds = service_account.Credentials.from_service_account_file(
        service_account_file)

    # Create jwt
    jwt_creds = jwt.Credentials.from_signing_credentials(
        svc_creds, audience=audience)

    # Issue request to get auth token
    request = google.auth.transport.requests.Request()
    jwt_creds.refresh(request)

    # Extract token
    id_token1 = jwt_creds.token
    #print (id_token1)
    return id_token1

def createVol():
    id_token1 = get_token()
    # Get all volumes from all regions
    # Construct GET request

    createvolumeURL = server + "/v2/projects/" + str(project_number) + "/locations/" + location + "/Volumes/"
    payload = {
        "name": "AutomatedVolume2",
        "creationToken": "ACV2",
        "region": "us-central1",
        "serviceLevel": "basic",
        "quotaInBytes": 1100000000000,

        "network": "projects/123456789/global/networks/ncv-vpc", # Replace with your VPC instead of ncv-vpc and the project number instead of 123456789
        "protocolTypes": [
            "NFSv3"
        ]
    }
    headers = {
        'accept': "application/json",
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    # POST request to create the volume
    response = requests.post(createvolumeURL, json.dumps(payload), headers=headers)
    # Sleep for 20 seconds to wait for the creation of the volume
    time.sleep(20)
    r_dict = response.json()
    # print("Response to POST request: " + response.text)
    # Get volume attributes
    # To get the values from the dictionary, you have read the dictionary one by one.
    # fetch the response first
    fetchvalue = (r_dict.get('response'))
    # fetch all the values from the response
    fetchvolumeID = fetchvalue.get('AnyValue')
    # fetch the volume ID from the values
    volumeID = fetchvolumeID.get('volumeId')
    # fetch the service level from the values
    serviceLevel = fetchvolumeID.get('serviceLevel')
    # Print the values
    print("\tvolumeID: " + volumeID + ", serviceLevel: " + serviceLevel)

createVol()

Output

The output should be similar to the following:

volumeID: f5b11c33-dff5-b4ab-d2ae-fbb14e4b063b, serviceLevel: basic

Create an NFSv4 volume

import google.auth
import google.auth.transport.requests
import requests
import json
import time
from google.auth import jwt
from google.oauth2 import service_account

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/Users/your-username/Downloads/ncv-beta-demo-eccee8711557.json'
project_number = 123456789  # Enter your project number here
location = "us-central1"
volumeIDdetails = "Enter your Volume ID here"

# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
  return bytes/1024/1024/1024

def get_token():
  # Create credential object from private key file
  svc_creds = service_account.Credentials.from_service_account_file(
      service_account_file)

  # Create jwt
  jwt_creds = jwt.Credentials.from_signing_credentials(
      svc_creds, audience=audience)

  # Issue request to get auth token
  request = google.auth.transport.requests.Request()
  jwt_creds.refresh(request)

  # Extract token
  id_token1 = jwt_creds.token
  #print (id_token1)
  return id_token1

def createVol():
  id_token1 = get_token()
  # Get all volumes from all regions
  # Construct GET request

  createvolumeURL = server + "/v2/projects/" + str(project_number) + "/locations/" + location + "/Volumes/"
  payload = "{\n   \"name\": \"AutomatedVolume7\",\n   \"creationToken\": \"ACV7\",\n   \"region\": \"us-central1\",\n   \"serviceLevel\": \"basic\",\n   \"quotaInBytes\": 1100000000000,\n   \"kerberosEnabled\": false,\n   \"network\": \"projects/123456789/global/networks/ncv-vpc\",\n   \"protocolTypes\": [\"NFSv4\"],\n   \"exportPolicy\": {\n      \"rules\": [\n         {\n            \"access\": \"ReadWrite\",\n            \"allowedClients\": \"0.0.0.0/0\",\n            \"nfsv3\": {\n               \"checked\": false\n            },\n            \"nfsv4\": {\n               \"checked\": true\n            }\n         }\n      ]\n   }\n}"
  headers = {
      'accept': "application/json",
      'Content-Type': "application/json",
      'Authorization': "Bearer " + id_token1.decode('utf-8'),
      'cache-control': "no-cache",
  }
  # POST request to create the volume
  response = requests.post(createvolumeURL, payload, headers=headers)
  # Sleep for 20 seconds to wait for the creation of the volume
  time.sleep(20)
  r_dict = response.json()
  # print("Response to POST request: " + response.text)
  # Get volume attributes
  # To get the values from the dictionary, you have read the dictionary one by one.
  # fetch the response first
  fetchvalue = (r_dict.get('response'))
  # fetch all the values from the response
  fetchvolumeID = fetchvalue.get('AnyValue')
  # fetch the volume ID from the values
  volumeID = fetchvolumeID.get('volumeId')
  # fetch the service level from the values
  serviceLevel = fetchvolumeID.get('serviceLevel')
  # fetch the class of the protocol types
  ProtocolList = fetchvolumeID.get('protocolTypes')
  # fetch the protocol type
  protocolType = ProtocolList[0]
  # Print the values
  print("\tvolumeID: " + volumeID + ", serviceLevel: " + serviceLevel + ", ProtocolType: " + protocolType)

createVol()

Output

The output should be similar to the following:

volumeID: 2c564228-29bd-822c-a315-a739b73c3a2d, serviceLevel: basic, ProtocolType: NFSv4

Create a volume with NFSv4 Kerberos encryption

import google.auth
import google.auth.transport.requests
import requests
import time
from google.auth import jwt
from google.oauth2 import service_account

# Set common variables
stagingaudience = 'https://dev-cloudvolumesgcp-api.netapp.com'
stagingserver = 'https://stage.ncv.us-east4.gcp.netapp.com'
service_account_file = '/Users/your-username/Downloads/ncv-beta-demo-eccee8711557.json'
project_number = 123456789  # Enter your project number here
location = "us-east4"
volumeIDdetails = "Enter your Volume ID here"

# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
   return bytes/1024/1024/1024

def get_token():
   # Create credential object from private key file
   svc_creds = service_account.Credentials.from_service_account_file(
       service_account_file)

   # Create jwt
   jwt_creds = jwt.Credentials.from_signing_credentials(
       svc_creds, audience=stagingaudience)

   # Issue request to get auth token
   request = google.auth.transport.requests.Request()
   jwt_creds.refresh(request)

   # Extract token
   id_token1 = jwt_creds.token
   #print (id_token1)
   return id_token1

def createVol():
   id_token1 = get_token()
   # Get all volumes from all regions
   # Construct GET request
   createvolumeURL = stagingserver + "/v2/projects/" + str(project_number) + "/locations/" + location + "/Volumes/"
   payload = "{\n   \"name\": \"AutomatedVolume5\",\n   \"creationToken\": \"ACV5\",\n   \"region\": \"us-east4\",\n   \"serviceLevel\": \"basic\",\n   \"quotaInBytes\": 1100000000000,\n   \"kerberosEnabled\": true,\n   \"network\": \"projects/779740114201/global/networks/cvs-scle-optimized\",\n   \"protocolTypes\": [\"NFSv4\"],\n   \"exportPolicy\": {\n      \"rules\": [\n         {\n            \"allowedClients\": \"0.0.0.0/0\",\n            \"hasRootAccess\": true,\n            \"access\": \"None\",\n            \"nfsv3\": {\n               \"checked\": false\n            },\n            \"nfsv4\": {\n               \"checked\": true\n            },\n            \"kerberos5ReadOnly\": true,\n\t        \"kerberos5ReadWrite\": true,\n\t        \"kerberos5iReadOnly\": true,\n\t        \"kerberos5iReadWrite\": true,\n\t        \"kerberos5pReadOnly\": true,\n\t        \"kerberos5pReadWrite\": true\n         }\n      ]\n   }\n}"
   headers = {
       'accept': "application/json",
       'Content-Type': "application/json",
       'Authorization': "Bearer " + id_token1.decode('utf-8'),
       'cache-control': "no-cache",
   }
   # POST request to create the volume
   response = requests.post(createvolumeURL, payload, headers=headers)
   # Sleep for 20 seconds to wait for the creation of the volume
   time.sleep(20)
   r_dict = response.json()
   # print("Response to POST request: " + response.text)
   # Get volume attributes
   # To get the values from the dictionary, you have read the dictionary one by one.
   # fetch the response first
   fetchvalue = (r_dict.get('response'))
   # fetch all the values from the response
   fetchvolumeID = fetchvalue.get('AnyValue')
   # fetch the volume ID from the values
   volumeID = fetchvolumeID.get('volumeId')
   # fetch the service level from the values
   serviceLevel = fetchvolumeID.get('serviceLevel')
   # Print the values
   print("\tvolumeID: " + volumeID + ", serviceLevel: " + serviceLevel)

createVol()

Output

The output should be similar to the following:

volumeID: 143c844e-f0b2-5839-8308-220bfa4a8869, serviceLevel: basic

Update Active Directory with Kerberos

import google.auth
import google.auth.transport.requests
import requests
import time
from google.auth import jwt
from google.oauth2 import service_account


# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/Users/your-username/Downloads/ncv-beta-demo-eccee8711557.json'
project_number = 779740114201  # Enter your project number here
location = "us-central1"
volumeIDdetails = "Enter your Volume ID here"
ActiveDirectory = "4b4507f4-a71c-6b13-6866-bf46899621e3"
# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
   return bytes/1024/1024/1024

def get_token():
   # Create credential object from private key file
   svc_creds = service_account.Credentials.from_service_account_file(
       service_account_file)

   # Create jwt
   jwt_creds = jwt.Credentials.from_signing_credentials(
       svc_creds, audience=audience)

   # Issue request to get auth token
   request = google.auth.transport.requests.Request()
   jwt_creds.refresh(request)

   # Extract token
   id_token1 = jwt_creds.token
   #print (id_token1)
   return id_token1

def updateAD():
   id_token1 = get_token()
   # Get all volumes from all regions
   # Construct GET request
   updateADURL = server + "/v2/projects/" + str(project_number) + "/locations/" + location + "/Storage/" + "/ActiveDirectory/" + ActiveDirectory
   payload = "{\n  \"username\": \"admin@cloudheroes.com\",\n  \"password\": \"Password123\",\n  \"domain\": \"cloudheroes.com\",\n  \"DNS\": \"10.0.0.0\",\n  \"netBIOS\": \"cloudier\",\n  \"organizationalUnit\": \"CN=Computers\",\n  \"site\": \"Default-First-Site-Name\",\n  \"kdcIP\": \"10.0.0.0\",\n  \"adName\": \"2BOVAEKB44B\",\n  \"ldapSigning\": false,\n  \"securityOperators\": [\n    \"test\"\n  ]\n}"
   headers = {
       'accept': "application/json",
       'Content-Type': "application/json",
       'Authorization': "Bearer " + id_token1.decode('utf-8'),
       'cache-control': "no-cache",
   }
   # POST request to create the volume
   response = requests.put(updateADURL, payload, headers=headers)
   # Sleep for 20 seconds to wait for the creation of the volume
   time.sleep(20)
   r_dict = response.json()
   # Get AD attributes
   # fetch the DNS details
   DNSServer = (r_dict.get('DNS'))
   # fetch the KPC IP address
   kdcIP = (r_dict.get('kdcIP'))
   # fetch the Domain Name
   domain = (r_dict.get('domain'))
   # fetch the KPC IP address
   UUID = (r_dict.get('UUID'))
   # Print the values
   print("\tDNSServer: " + DNSServer + ", domain: " + domain + ", kdcIP: " + kdcIP + ", UUID: " + UUID)

updateAD()

Output

The output should be similar to the following:

/usr/local/bin/python3.7 /Users/your-username/PycharmProjects/ntap-CVS-GCP-API/updateAD.py
    DNSServer: 10.0.0.0, domain: cloudheroes.com, kdcIP: 10.0.0.0, UUID: 4b4507f4-a71c-6b13-6866-bf46899621e3

Create an SMB volume (continuously available, non-browsable, with encryption enabled)

import google.auth
import google.auth.transport.requests
import requests
import time
from google.auth import jwt
from google.oauth2 import service_account

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/Users/your-username/Downloads/ncv-beta-demo-eccee8711557.json'
project_number = 779740114201  # Enter your project number here
location = "us-central1"
volumeIDdetails = "Enter your Volume ID here"

# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
   return bytes/1024/1024/1024

def get_token():
   # Create credential object from private key file
   svc_creds = service_account.Credentials.from_service_account_file(
       service_account_file)

   # Create jwt
   jwt_creds = jwt.Credentials.from_signing_credentials(
       svc_creds, audience=audience)

   # Issue request to get auth token
   request = google.auth.transport.requests.Request()
   jwt_creds.refresh(request)

   # Extract token
   id_token1 = jwt_creds.token
   #print (id_token1)
   return id_token1

def createVolSMB():
   id_token1 = get_token()
   # Get all volumes from all regions
   # Construct GET request

   createvolumeURL = server + "/v2/projects/" + str(project_number) + "/locations/" + location + "/Volumes/"
   #payload = "{\n  \"name\": \"prabu-smb_encryption4\",\n  \"region\": \"us-central1\",\n  \"creationToken\": \"prabu-smb_encryption4\",\n  \"serviceLevel\": \"medium\",\n  \"network\": \"projects/779740114201/global/networks/ncv-vpc\",\n  \"quotaInBytes\": 1099511627776,\n  \"snapReserve\": 20,\n  \"protocolTypes\": [\n    \"CIFS\"\n  ],\n  \"smbShareSettings\": [\n    \"continuously_available\",\n    \"encrypt_data\"\n  ],\n  \"jobs\": [\n    {}\n  ],\n  \"labels\": [\n    \"api\"\n  ]\n}\n\n\n"
   payload = "{\n  \"name\": \"prabu-smb_encryption\",\n  \"region\": \"us-central1\",\n  \"creationToken\": \"prabu-smb\",\n  \"serviceLevel\": \"medium\",\n  \"network\": \"projects/779740114201/global/networks/ncv-vpc\",\n  \"quotaInBytes\": 1099511627776,\n  \"snapReserve\": 20,\n  \"protocolTypes\": [\n    \"CIFS\"\n  ],\n  \"smbShareSettings\": [\n    \"continuously_available\",\n    \"encrypt_data\",\n    \"non_browsable\"\n  ],\n  \"jobs\": [\n    {}\n  ],\n  \"labels\": [\n    \"api\"\n  ]\n}\n\n\n"
   headers = {
       'accept': "application/json",
       'Content-Type': "application/json",
       'Authorization': "Bearer " + id_token1.decode('utf-8'),
       'cache-control': "no-cache",
   }
   # POST request to create the volume
   response = requests.post(createvolumeURL, payload, headers=headers)
   # Sleep for 20 seconds to wait for the creation of the volume
   time.sleep(20)
   r_dict = response.json()
   # print("Response to POST request: " + response.text)
   # Get volume attributes
   # To get the values from the dictionary, you have read the dictionary one by one.
   # fetch the response first
   fetchvalue = (r_dict.get('response'))
   # fetch all the values from the response
   fetchvolumeID = fetchvalue.get('AnyValue')
   # fetch the volume ID from the values
   volumeID = fetchvolumeID.get('volumeId')
   # fetch the service level from the values
   serviceLevel = fetchvolumeID.get('serviceLevel')
   # fetch the class of the protocol types
   ProtocolList = fetchvolumeID.get('protocolTypes')
   # fetch the protocol type
   protocolType = ProtocolList[0]
   smbShareSettingsFromResponse = fetchvolumeID.get('smbShareSettings')
   for smbShareSettings in smbShareSettingsFromResponse:
       print("\tsmbShareSettings: " + smbShareSettings + ", ")
   # Print the values
   print("\tvolumeID: " + volumeID + ", serviceLevel: " + serviceLevel + ", ProtocolType: " + protocolType )
createVolSMB()

Output

The output should be similar to the following:

/Users/your-username/PycharmProjects/ntap-CVS-GCP-API/createVolume_SMB_CA_Encrypt.py
  smbShareSettings: continuously_available,
  smbShareSettings: encrypt_data,
  smbShareSettings: non_browsable,
  volumeID: 0a867fe7-bbd9-18d6-4de5-1191ba0fe123, serviceLevel: standard, ProtocolType: CIFS

Get service level details

import google.auth
import google.auth.transport.requests
import requests
from google.auth import jwt
from google.oauth2 import service_account

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/Users/your-username/Downloads/ncv-beta-demo-eccee8711557.json'
project_number = 123456789
location = "us-central1"

# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
    return bytes/1024/1024/1024

def get_token():
    # Create credential object from private key file
    svc_creds = service_account.Credentials.from_service_account_file(
        service_account_file)

    # Create jwt
    jwt_creds = jwt.Credentials.from_signing_credentials(
        svc_creds, audience=audience)

    # Issue request to get auth token
    request = google.auth.transport.requests.Request()
    jwt_creds.refresh(request)

    # Extract token
    id_token1 = jwt_creds.token
    #print (id_token1)
    return id_token1

def getServiceLevel():
    id_token1 = get_token()
    # Get all volumes from all regions
    url = server + "/v2/projects/" + str(project_number) + "/locations/" + location + "/Storage/ServiceLevels"
    # Construct GET request
    #url = "https://cloudvolumesgcp-api.netapp.com/v2/projects/779740114201/locations/us-central1/Storage/ServiceLevels"
    payload = ""
    headers = {
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    response = requests.request("GET", url, data=payload, headers=headers)
    # Load the json response into a dict
    r_dict = response.json()
    # Print out all service levels
    print("Response to GET request: " + url)
    for serviceLevel in r_dict:
        # Get volume attributes
        serviceLevelName = serviceLevel["name"]
        serviceLevelPerformance = serviceLevel["performance"]
        print("\tserviceLevelName: " + serviceLevelName + ", \tserviceLevelPerformance: " + serviceLevelPerformance)

getServiceLevel()

Output

The output should be similar to the following:

Response to GET request: https://cloudvolumesgcp-api.netapp.com/v2/projects/779740114201/locations/us-central1/Storage/ServiceLevels
       serviceLevelName: basic,   serviceLevelPerformance: low
       serviceLevelName: standard,       serviceLevelPerformance: medium
       serviceLevelName: extreme,        serviceLevelPerformance: high

Get volume details

import google.auth
import google.auth.transport.requests
import requests
from google.auth import jwt
from google.oauth2 import service_account

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/Users/your-username/Downloads/ncv-beta-demo-eccee8711557.json'
project_number = 123456789
location = "us-central1"
volumeIDdetails = "EnterYourVolumeID"

# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
    return bytes/1024/1024/1024

def get_token():
    # Create credential object from private key file
    svc_creds = service_account.Credentials.from_service_account_file(
        service_account_file)

    # Create jwt
    jwt_creds = jwt.Credentials.from_signing_credentials(
        svc_creds, audience=audience)

    # Issue request to get auth token
    request = google.auth.transport.requests.Request()
    jwt_creds.refresh(request)

    # Extract token
    id_token1 = jwt_creds.token
    #print (id_token1)
    return id_token1

def getVolumeDetails():
    id_token1 = get_token()
    # Get all volumes from all regions
    # Construct GET request
    volumeURL = server + "/v2/projects/" + str(project_number) + "/locations/" + location + "/Volumes/" + volumeIDdetails
    payload = ""
    headers = {
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    response = requests.request("GET", volumeURL, data=payload, headers=headers)
    # Load the json response into a dict
    r_dict = response.json()
    #Print out all service levels
    print("Response to GET request: " + volumeURL)
    # Get volume attributes
    volumeName = (r_dict.get('name'))
    volumeID = (r_dict.get('volumeId'))
    serviceLevcel = (r_dict.get('serviceLevel'))
    print("\tvolumeName: " + volumeName + ", serviceLevel: " + serviceLevcel , "volumeID: " + volumeID)

getVolumeDetails()

Output

The output should be similar to the following:

Response to GET request: https://cloudvolumesgcp-api.netapp.com/v2/projects/779740114201/locations/us-central1/Volumes/4f30e00b-87ef-28b3-6e74-72e1c1c378d3
volumeName: volumeshapingtest, serviceLevel: basic volumeID: 4f30e00b-87ef-28b3-6e74-72e1c1c378d3

Update volume details

import google.auth
import google.auth.transport.requests
import requests
import time
from google.auth import jwt
from google.oauth2 import service_account

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/Users/your-username/Downloads/ncv-beta-demo-eccee8711557.json'
project_number = 123456789  # Enter your project number here
location = "us-central1"
volumeIDdetails = "Enter your VolumeID here"

# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
   return bytes/1024/1024/1024

def get_token():
   # Create credential object from private key file
   svc_creds = service_account.Credentials.from_service_account_file(
       service_account_file)

   # Create jwt
   jwt_creds = jwt.Credentials.from_signing_credentials(
       svc_creds, audience=audience)

   # Issue request to get auth token
   request = google.auth.transport.requests.Request()
   jwt_creds.refresh(request)

   # Extract token
   id_token1 = jwt_creds.token
   #print (id_token1)
   return id_token1

def updateVolume():
   id_token1 = get_token()
   # Get all volumes from all regions
   # Construct GET request

   updatevolumeURL = server + "/v2/projects/" + str(project_number) + "/locations/" + location + "/Volumes/" + volumeIDdetails
   payload = "{\n   \"name\": \"AutomatedVolume1\",\n   \"creationToken\": \"ACV1\",\n   \"region\": \"us-central1\",\n   \"serviceLevel\": \"basic\",\n   \"quotaInBytes\": 1100000000000,\n   \"kerberosEnabled\": \"false\",\n   \"network\": \"projects/123456789/global/networks/ncv-vpc\",\n   \"kerberosEnabled\": \"false\",\n   \"protocolTypes\": [\"NFSv4\"],\n   \"exportPolicy\": {\n      \"rules\": [\n         {\n            \"access\": \"ReadWrite\",\n            \"allowedClients\": \"0.0.0.0/0\",\n            \"nfsv3\": {\n               \"checked\": false\n            },\n            \"nfsv4\": {\n               \"checked\": true\n            }\n         }\n      ]\n   }\n}"
   headers = {
       'accept': "application/json",
       'Content-Type': "application/json",
       'Authorization': "Bearer " + id_token1.decode('utf-8'),
       'cache-control': "no-cache",
   }
   # POST request to create the volume
   response = requests.put(updatevolumeURL, payload, headers=headers)
   # Sleep for 20 seconds to wait for the creation of the volume
   time.sleep(20)
   r_dict = response.json()
   # print("Response to POST request: " + response.text)
   # Get volume attributes
   # To get the values from the dictionary, you have read the dictionary one by one.
   # fetch the response first
   fetchvalue = (r_dict.get('response'))
   # fetch all the values from the response
   fetchvolumeID = fetchvalue.get('AnyValue')
   # fetch the volume ID from the values
   volumeID = fetchvolumeID.get('volumeId')
   # fetch the service level from the values
   serviceLevel = fetchvolumeID.get('serviceLevel')
   # Print the values
   print("\tvolumeID: " + volumeID + ", serviceLevel: " + serviceLevel)

updateVolume()

Output

The output should be similar to the following:

volumeID: 7fd1095f-617b-819a-f9ce-e3c84e31b8c9, serviceLevel: basic

Update volume details with rootAccess disabled

import google.auth
import google.auth.transport.requests
import requests
import time
from google.auth import jwt
from google.oauth2 import service_account

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/Users/your-username/Downloads/ncv-beta-demo-eccee8711557.json'
project_number = 779740114201  # Enter your project number here
location = "us-central1"
volumeIDdetails = "7fd1095f-617b-819a-f9ce-e3c84e31b8c9"

# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
   return bytes/1024/1024/1024

def get_token():
   # Create credential object from private key file
   svc_creds = service_account.Credentials.from_service_account_file(
       service_account_file)

   # Create jwt
   jwt_creds = jwt.Credentials.from_signing_credentials(
       svc_creds, audience=audience)

   # Issue request to get auth token
   request = google.auth.transport.requests.Request()
   jwt_creds.refresh(request)

   # Extract token
   id_token1 = jwt_creds.token
   #print (id_token1)
   return id_token1

def updateVolume():
   id_token1 = get_token()
   # Get all volumes from all regions
   # Construct GET request

   updatevolumeURL = server + "/v2/projects/" + str(project_number) + "/locations/" + location + "/Volumes/" + volumeIDdetails
   payload = "{\n   \"name\": \"AutomatedVolume1\",\n   \"creationToken\": \"ACV1\",\n   \"region\": \"us-central1\",\n   \"serviceLevel\": \"standard\",\n   \"quotaInBytes\": 1100000000000,\n   \"kerberosEnabled\": \"false\",\n   \"network\": \"projects/123456789/global/networks/ncv-vpc\",\n   \"kerberosEnabled\": \"false\",\n   \"protocolTypes\": [\"NFSv4\"],\n   \"exportPolicy\": {\n      \"rules\": [\n         {\n            \"access\": \"ReadWrite\",\n            \"allowedClients\": \"0.0.0.0/0\",\n             \"hasRootAccess\": false,\n        \"nfsv3\": {\n               \"checked\": false\n            },\n            \"nfsv4\": {\n               \"checked\": true\n            }\n         }\n      ]\n   }\n}"
   headers = {
       'accept': "application/json",
       'Content-Type': "application/json",
       'Authorization': "Bearer " + id_token1.decode('utf-8'),
       'cache-control': "no-cache",
   }
   # POST request to create the volume
   response = requests.put(updatevolumeURL, payload, headers=headers)
   # Sleep for 20 seconds to wait for the creation of the volume
   time.sleep(20)
   r_dict = response.json()
   # print("Response to POST request: " + response.text)
   # Get volume attributes
   # To get the values from the dictionary, you have read the dictionary one by one.
   # fetch the response first
   fetchvalue = (r_dict.get('response'))
   # fetch all the values from the response
   fetchvolumeID = fetchvalue.get('AnyValue')
   # fetch the volume ID from the values
   volumeID = fetchvolumeID.get('volumeId')
   # fetch the service level from the values
   serviceLevel = fetchvolumeID.get('serviceLevel')
   # Print the values
   print("\tvolumeID: " + volumeID + ", serviceLevel: " + serviceLevel)

updateVolume()

Output

The output should be similar to the following:

volumeID: 7fd1095f-617b-819a-f9ce-e3c84e31b8c9, serviceLevel: standard

Update the service level

import google.auth
import google.auth.transport.requests
import requests
from google.auth import jwt
from google.oauth2 import service_account
import time

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/Users/your-username/Downloads/ncv-beta-demo-eccee8711557.json'
project_number = 779740114201
location = "us-central1"
volumeIDdetails = "4f30e00b-87ef-28b3-6e74-72e1c1c378d3"

# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
    return bytes/1024/1024/1024

def get_token():
    # Create credential object from private key file
    svc_creds = service_account.Credentials.from_service_account_file(
        service_account_file)

    # Create jwt
    jwt_creds = jwt.Credentials.from_signing_credentials(
        svc_creds, audience=audience)

    # Issue request to get auth token
    request = google.auth.transport.requests.Request()
    jwt_creds.refresh(request)

    # Extract token
    id_token1 = jwt_creds.token
    #print (id_token1)
    return id_token1

def updateServiceLevel():
    id_token1 = get_token()
    # Get all volumes from all regions
    # Construct GET request
    volumeURL = server + "/v2/projects/" + str(project_number) + "/locations/" + location + "/Volumes/" + volumeIDdetails
    payload = "{\n    \"serviceLevel\": \"basic\"\n}"
    headers = {
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    response = requests.request("PUT", volumeURL, data=payload, headers=headers)
    # Load the json response into a dict
    #Print out all service levels
    time.sleep(10)
    print("Response to GET request: " + volumeURL)
    print(response.text)

updateServiceLevel()

Output

The output should be similar to the following:

Response to GET request: https://cloudvolumesgcp-api.netapp.com/v2/projects/projectNumber/locations/us-central1/Volumes/volumeID 

{"name":"/v2/projects/ProjectId/locations/us-central1/operations/4operationsID","response":{"@type":"type.googleapis.com/google.protobuf.Struct",
"AnyValue":{"created":"2020-08-19T23:30:54.000Z","lifeCycleState":"updating",
"lifeCycleStateDetails":"Update in progress","name":"volumeshapingtest","ownerId":"OwnerID","region":"us-central1","volumeId":"4VolumeID","zone":"us-central1-zone1","creationToken":"blissful-infallible-euler","exportPolicy":{"rules":[]},"isDataProtection":false,
"jobs":[{"action":"update","created":"2020-08-26T21:23:22.984Z","jobId":"jobId","objectId":"objectId","objectType":"Volume","state":"ongoing","stateDetails":"Job is in progress","workerId":"320e8c10-c056-5599-3a8f-001108ac89aa"}],"labels":null,"mountPoints":[{"export":"/blissful-infallible-euler",
"exportFull":"10.210.0.4:/blissful-infallible-euler","instructions":"Setting up your instance
\nOpen an SSH client and connect to your instance.\nInstall the nfs client on your instance.
\nOn Red Hat Enterprise Linux or SuSE Linux instance:\nsudo yum install -y nfs-utils\nOn an 
Ubuntu or Debian instance:\nsudo apt-get install nfs-common\n\nMounting your volume\nCreate a 
new directory on your instance, such as \"/blissful-infallible-euler\":\nsudo mkdir 
/blissful-infallible-euler\nMount your volume using the example command below:\nsudo mount -t nfs -o rw,hard,rsize=65536,wsize=65536,vers=3,tcp 10.210.0.4:/blissful-infallible-euler 
/blissful-infallible-euler\nNote. Please use mount options appropriate for your specific 
workloads when known.","protocolType":"NFSv3","server":"10.210.0.4","vlanId":1042}],

"network":"projects/779740114201/global/networks/ncv-vpc","protocolTypes":["NFSv3"],
"quotaInBytes":1099511627776,
"securityStyle":"unix","serviceLevel":"basic","snapReserve":0,"snapshotDirectory":true,
"snapshotPolicy":{"dailySchedule":{"hour":0,"minute":0,"snapshotsToKeep":0},
"enabled":false,"hourlySchedule":{"minute":0,"snapshotsToKeep":0},"monthlySchedule":
{"daysOfMonth":"1","hour":0,"minute":0,"snapshotsToKeep":0},"weeklySchedule":{"day":"Sunday",
"hour":0,"minute":0,"snapshotsToKeep":0}},"storageClass":"hardware","timezone":"CST","usedBytes
":413696}}}

Process finished with exit code 0

Create a backup

import google.auth
import google.auth.transport.requests
import requests
import json
import sys
import argparse
from google.auth import jwt
from google.oauth2 import service_account
from google.oauth2 import id_token

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/home/username/keys/prj-10-31e8f6d0c17e.json'
project_number = 81821054389
region = 'us-east1'
volumeID = 'c8edf010-454e-5c47-477b-a7acff2f7235'
name_of_backup = 'backup_test2'

# Create backup post url
post_url = server + "/v2/projects/" + str(project_number) + "/locations/" + region + "/Volumes/" + volumeID + "/Backups"

# Name
data = {"name": name_of_backup}

# create credential object from private key file
svc_creds = service_account.Credentials.from_service_account_file(
    service_account_file)

# create jwt
jwt_creds = jwt.Credentials.from_signing_credentials(
    svc_creds, audience=audience)

# issue request to get auth token
request = google.auth.transport.requests.Request()
jwt_creds.refresh(request)

# extract token
id_token = jwt_creds.token

# Construct GET request
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer " + id_token.decode('utf-8')
}

# Issue the request to the server
r = requests.post(post_url, headers=headers, data=json.dumps(data))

# Load the json response into a dict
r_dict = r.json()

if r.status_code == 202:
    # print out the response of backup create
    print("Response to post request: " + post_url)

    vol_uuid = r_dict['response']['AnyValue']['volumeId']
    backup_uuid = r_dict['response']['AnyValue']['backupId']
    lifeCycleState = r_dict['response']['AnyValue']['lifeCycleState']
    region = r_dict['response']['AnyValue']['region']
    print("\tvolUUID: " + vol_uuid + ", backupUUID: " + str(
        backup_uuid) + ", region: " + region + ", lifeCycleState: " + lifeCycleState)
else:
    print(r_dict)

Output

Response to post request:
https://cloudvolumesgcp-api.netapp.com/v2/projects/81821054389/locations/us-east1/Volumes/c8edf010-454e-5c47-477b-a7acff2f7235/Backups
volUUID: c8edf010-454e-5c47-477b-a7acff2f7235, backupUUID: 02819d6c-1cad-2f73-493c-a29bd57f076d, region: , lifeCycleState: creating

List backups

import google.auth
import google.auth.transport.requests
import requests
import json
import sys
import argparse
from google.auth import jwt
from google.oauth2 import service_account
from google.oauth2 import id_token

# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com' 
service_account_file = '/home/username/keys/prj-10-31e8f6d0c17e.json'
project_number = 81821054389
region = 'us-east1'

# Get all volumes from all regions
get_url = server + "/v2/projects/" + str(project_number) + "/locations/" + region + "/Backups"

# create credential object from private key file
svc_creds = service_account.Credentials.from_service_account_file(
    service_account_file)

# create jwt
jwt_creds = jwt.Credentials.from_signing_credentials(
    svc_creds, audience=audience)

# issue request to get auth token
request = google.auth.transport.requests.Request()
jwt_creds.refresh(request)

# extract token
id_token = jwt_creds.token

# Construct GET request
headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + id_token.decode('utf-8')
        }

# Issue the request to the server
r = requests.get(get_url, headers=headers)

# Load the json response into a dict
r_dict = r.json()

for backup in r_dict:
   backup_id = backup['backupId']
   backup_name = backup['name']
   region = backup['region']
   lifeCycleState = backup['lifeCycleState']
   progressPercentage = backup['progressPercentage']
   bytesTransferred = backup['bytesTransferred']
   print ("\n\tbackupName: " + backup_name + ", backupUUID: " + str(backup_id) + ", region: " + region + ", lifeCycleState: " + lifeCycleState + ", progressPercentage: " + str(progressPercentage) + ", bytesTransferred: " + str(bytesTransferred))

Output

backupName: backup1, backupUUID: b88190ae-7463-03c5-5daf-1ef822c2360a, region: us-east1, lifeCycleState: available, progressPercentage: 100, bytesTransferred: 0

backupName: backup2, backupUUID: 3c7ecde8-479b-14fa-ab14-f32baa027d21, region: us-east1, lifeCycleState: available, progressPercentage: 100, bytesTransferred: 271198

backupName: backup3, backupUUID: fd2d1ebe-ab97-7833-6571-fb36d87853dd, region: us-east1, lifeCycleState: available, progressPercentage: 100, bytesTransferred: 0

backupName: backup_test1, backupUUID: 6631e751-fd5d-3aff-b9d6-c0bc78b2ebda, region: us-east1, lifeCycleState: available, progressPercentage: 100, bytesTransferred: 0

backupName: backup_test2, backupUUID: 68822cf6-ae94-bba6-84e0-9d742eff708f, region: us-east1, lifeCycleState: available, progressPercentage: 100, bytesTransferred: 0

Restore from a backup

import google.auth
import google.auth.transport.requests
import requests
import json
import sys
import argparse
from google.auth import jwt
from google.oauth2 import service_account
from google.oauth2 import id_token


# Small utility function to convert bytes to gibibytes
def convertToGiB(bytes):
    return bytes / 1024 / 1024 / 1024


# Set common variables
audience = 'https://cloudvolumesgcp-api.netapp.com'
server = 'https://cloudvolumesgcp-api.netapp.com'
service_account_file = '/home/username/keys/prj-10-31e8f6d0c17e.json'

#Volume create payload json picked from a file whose path is specified below
volume_payload = '/home/username/payload.json' 
project_number = 81821054389
region = 'us-east1'
zone = 'us-east1-b'
vol_size = 1099511627776
creation_token = 'token123'

# backup uuid needed to be restored
backupId = 'b88190ae-7463-03c5-5daf-1ef822c2360a'

# consumer vpc information
network = 'projects/81821054389/global/networks/test-vpc'

# export policy information
export_policy = {"rules": [{ "allowedClients": "0.0.0.0/0", "access": "ReadWrite", "nfsv3": {"checked": True}, "nfsv4": {"checked": False}}]}

# snapshot policy information
snapshot_policy = {"enabled": True, "hourlySchedule": {"snapshotsToKeep": 2, "minute": 10}, "dailySchedule": {
        "snapshotsToKeep": 7, "hour": 12, "minute": 10}, "weeklySchedule": {"snapshotsToKeep": 2, "day": "sunday",
        "hour": 23, "minute": 10 },"monthlySchedule": { "snapshotsToKeep": 12, "daysOfMonth": "1,15,31", "hour": 23, "minute": 10}
        }

# Volume create payload
data = {"name": "vol_test", "region": region, "zone": zone, "creationToken": creation_token,
        "serviceLevel": "low", "network": network, "quotaInBytes": vol_size, "storageClass": "software",
        "snapshotPolicy": snapshot_policy, "snapReserve": 20, "timezone": "GMT", "exportPolicy": export_policy,
        "protocolTypes": ["NFSv3"], "labels": ["test"], "backupId": backupId}

# Get all volumes from all regions
post_url = server + "/v2/projects/" + str(project_number) + "/locations/" + str(region) + "/Volumes"

# Get creation token api
get_creationToken_url = server + "/v2/projects/" + str(project_number) + "/locations/" + str(
    region) + "/VolumeCreationToken"

# create credential object from private key file
svc_creds = service_account.Credentials.from_service_account_file(
    service_account_file)

# create jwt
jwt_creds = jwt.Credentials.from_signing_credentials(
    svc_creds, audience=audience)

# issue request to get auth token
request = google.auth.transport.requests.Request()
jwt_creds.refresh(request)

# extract token
id_token = jwt_creds.token

# Construct GET request
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer " + id_token.decode('utf-8')
}

# Issue the request to the server
r = requests.post(post_url, headers=headers, data=json.dumps(data))

# Load the json response into a dict
r_dict = r.json()

if r.status_code == 202:
    # print out the response of vol create
    print("Response to post request: " + post_url)

    uuid = r_dict['response']['AnyValue']['volumeId']
    volname = r_dict['response']['AnyValue']['name']
    volsizeGiB = convertToGiB(r_dict['response']['AnyValue']['quotaInBytes'])
    region = r_dict['response']['AnyValue']['region']
    print("\tvolname: " + volname + ", uuid: " + str(uuid) + ", size: " + str(volsizeGiB) + "GiB, region: " + region)
else:
    print(r_dict)

Output

Response to post request:
https://cloudvolumesgcp-api.netapp.com/v2/projects/81821054389/locations/us-east1/Volumes
volname: vol_test, uuid: 25fef067-cf58-e46a-f63e-54a081764a66, size: 1024.0GiB, region: us-east1