Shared flows can be used to encapsulate common tasks so they can be easily shared between proxies.
In this lab, you create a shared flow that adds the required Authorization header to a target request, and then call it from your retail proxy.
Objectives
In this lab, you learn how to perform the following tasks:
Create a shared flow.
Call a shared flow from a proxy.
Setup and requirements
For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.
Sign in to Qwiklabs using an incognito window.
Note the lab's access time (for example, 1:15:00), and make sure you can finish within that time.
There is no pause feature. You can restart if needed, but you have to start at the beginning.
When ready, click Start lab.
Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.
Click Open Google Console.
Click Use another account and copy/paste credentials for this lab into the prompts.
If you use other credentials, you'll receive errors or incur charges.
Accept the terms and skip the recovery resource page.
Activate Google Cloud Shell
Google Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud.
Google Cloud Shell provides command-line access to your Google Cloud resources.
In Cloud console, on the top right toolbar, click the Open Cloud Shell button.
Click Continue.
It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example:
gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.
You can list the active account name with this command:
[core]
project = qwiklabs-gcp-44776a13dea667a6
Note:
Full documentation of gcloud is available in the
gcloud CLI overview guide
.
Preloaded assets
These assets have already been added to the Apigee organization:
The retail-v1 API proxy
The oauth-v1 API proxy (for generating OAuth tokens)
The TS-Retail target server in the eval environment (used by retail-v1)
These assets will be added to the Apigee organization as soon as the runtime is available:
The API products, developer, and developer app (used by retail-v1)
The ProductsKVM key value map in the eval environment (currently used by retail-v1, and will be used by the shared flow that is created during this lab)
The ProductsKVM key value map will be populated with backendId and backendSecret
The highlighted items are used during this lab.
Note:
Revision 1 of the retail-v1 proxy is marked as deployed, and is immutable. If you ever make a mistake in your proxy code that you can't recover from, you can select revision 1 and restart editing from there.
Task 1. Create a new shared flow to build a basic auth header
In this task, you create a new shared flow that is used to build a basic auth header for calling your backend service.
Pin the Apigee console page
In the Google Cloud console, on the Navigation menu (), look for Apigee in the Pinned Products section.
The Apigee console page will open.
If Apigee is not pinned, search for Apigee in the top search bar and navigate to the Apigee service.
Hover over the name, then click the pin icon ().
The Apigee console page will now be pinned to the Navigation menu.
Create the shared flow
On the left navigation menu, select Proxy development > Shared flows.
Click +Create.
For Name, enter backend-credentials.
Click Create.
Add the policies
The shared flow will be used to create the basic auth header created in the updateProductById flow of the retail-v1 proxy:
The policies will be identical to those used in the retail-v1 proxy.
In the shared flow, click the Develop tab.
Click Shared flows > default.
You will add the key value map policy.
On the default flow, click Add Policy Step (+).
In the Add policy step pane, select Create new policy, and then select Mediation > Key Value Map Operations.
A shared flow cannot be tested without including it in an API proxy, and it must be deployed to an environment before a proxy calling it can be deployed to that environment.
To specify that you want the new revision deployed to the eval environment, select eval as the Environment, and then click Deploy.
Click Confirm.
Task 2. Replace the policies in retail-v1 with a flow callout policy
In this task, you change your retail-v1 proxy to call the shared flow, replacing the KVM and BasicAuthentication policies with a FlowCallout policy.
On the left navigation menu, click Proxy development > API proxies.
Select the retail-v1 proxy.
Click the Develop tab.
You are modifying the version of the retail-v1 proxy that was created during Labs 1 through 8.
To detach the KVM-GetCredentials and BA-AddAuthHeader policies, for each policy, click Policy step actions (), and then click Delete policy step.
Add the flow callout policy
In the updateProductById request flow, click Add Policy Step (+).
In the Add policy step pane, select Create new policy, and then select Extension > Flow Callout.
Specify the following values:
Property
Value
Name
FC-BackendCredentials
Display name
FC-BackendCredentials
Sharedflow
selectbackend-credentials
Click Add.
The policy configuration simply specifies the shared flow to call in the SharedFlowBundle element. The policy configuration does not need to be changed.
Click Save, and then click Save as New Revision.
Click Deploy.
To specify that you want the new revision deployed to the eval environment, click Deploy.
Click Confirm.
Check deployment status
A proxy that is deployed and ready to take traffic will show a green status on the Overview tab.
When a proxy is marked as deployed but the runtime is not yet available and the environment is not yet attached, you may see a red warning sign. Hold the pointer over the Status icon to see the current status.
If the proxy is deployed and shows as green, your proxy is ready for API traffic. If your proxy is not deployed because there are no runtime pods, you can check the provisioning status.
Check provisioning status
In Cloud Shell, to confirm that the runtime instance has been installed and the eval environment has been attached, run the following commands:
export PROJECT_ID=$(gcloud config list --format 'value(core.project)'); echo "PROJECT_ID=${PROJECT_ID}"; export INSTANCE_NAME=eval-instance; export ENV_NAME=eval; export PREV_INSTANCE_STATE=; echo "waiting for runtime instance ${INSTANCE_NAME} to be active"; while : ; do export INSTANCE_STATE=$(curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" -X GET "https://apigee.googleapis.com/v1/organizations/${PROJECT_ID}/instances/${INSTANCE_NAME}" | jq "select(.state != null) | .state" --raw-output); [[ "${INSTANCE_STATE}" == "${PREV_INSTANCE_STATE}" ]] || (echo; echo "INSTANCE_STATE=${INSTANCE_STATE}"); export PREV_INSTANCE_STATE=${INSTANCE_STATE}; [[ "${INSTANCE_STATE}" != "ACTIVE" ]] || break; echo -n "."; sleep 5; done; echo; echo "instance created, waiting for environment ${ENV_NAME} to be attached to instance"; while : ; do export ATTACHMENT_DONE=$(curl -s -H "Authorization: Bearer $(gcloud auth print-access-token)" -X GET "https://apigee.googleapis.com/v1/organizations/${PROJECT_ID}/instances/${INSTANCE_NAME}/attachments" | jq "select(.attachments != null) | .attachments[] | select(.environment == \"${ENV_NAME}\") | .environment" --join-output); [[ "${ATTACHMENT_DONE}" != "${ENV_NAME}" ]] || break; echo -n "."; sleep 5; done; echo "***ORG IS READY TO USE***";
When the script returns ORG IS READY TO USE, you can proceed to the next steps.
In this task, you validate that the retail API and shared flow present the credentials to the backend service and the product overall rating is updated.
Test the API proxy using private DNS
The eval environment in the Apigee organization can be called using the hostname eval.example.com. The DNS entry for this hostname has been created within your project, and it resolves to the IP address of the Apigee runtime instance. This DNS entry has been created in a private zone, which means it is only visible on the internal network.
Cloud Shell does not reside on the internal network, so Cloud Shell commands cannot resolve this DNS entry. A virtual machine (VM) within your project can access the private zone DNS. A virtual machine named apigeex-test-vm was automatically created for this purpose. You can make API proxy calls from this machine.
The curl command will be used to send API requests to an API proxy. The -k option for curl tells it to skip verification of the TLS certificate. For this lab, the Apigee runtime uses a self-signed certificate. For a production environment, you should use certificates that have been created by a trusted certificate authority (CA).
In Cloud Shell, open a new tab, and then open an SSH connection to your test VM:
This command retrieves a Google Cloud access token for the logged-in user, sending it as a Bearer token to the Apigee API call. It retrieves the retail-app app details as a JSON response, which is parsed by jq to retrieve the app's key. That key is then put into the API_KEY environment variable, and the export command is concatenated onto the .bashrc file which runs automatically when starting a the SSH session.
Note:
If you run the command and it shows API_KEY=null, the runtime instance is probably not yet available.
curl -k -H "apikey: ${API_KEY}" -X GET "https://eval.example.com/retail/v1/products" | jq
The response should be a JSON list of products that resembles this:
{
"00621094000P" : {
"category" : "Fitness",
"image" : "https://cdn.pixabay.com/photo/2016/04/01/09/30/boy-1299405_1280.png",
"name" : "00621094000P",
"overall_rating" : 0.2,
"product_name" : "AFG 7.1AT Treadmill",
"short_description" : "The right treadmill makes a difference, especially for highly active fitness enthusiasts. That's why the AFG 7.1AT treadmill has a highly durable, non-folding frame that's designed to last a lifetime. Built with heavy gauge steel, it delivers a club-like workout experience that won’t shift or creak during the most intense exercise sessions. The commercial-grade 3.25 horsepower continuous-duty motor offers a smooth and silent ride, no matter your pace. This ultra-quiet drive system also features a 15% power incline that delivers more workout options to help you reach every fitness goal faster, distraction- and worry-free."
},
"00624932000P" : {
"category" : "Fitness",
"image" : "https://cdn.pixabay.com/photo/2016/04/01/09/30/boy-1299405_1280.png",
"name" : "00624932000P",
"overall_rating" : 4.3,
"product_name" : "NordicTrack Elite 3700 Treadmill",
"short_description" : "Amp it Up with the NordicTrack Elite 3700 Interactive Treadmill. Equipped with the best fitness technology available and banning the boredom of working out, the NordicTrack elite 3700 interactive treadmill puts your goals well within reach. The Intermix Acoustics™ Sound System on the treadmill features two high quality three-inch speakers for amazing sound, delivering the inspiration to press “start” and the motivation to keep moving. Plug in your iPod, ditch your ear buds and turn up the volume for a fun way to workout."
},
The top-level keys are the IDs (00621094000P and 00624932000P are shown here). Choose any one of the IDs in the entire list.
Create an environment variable, replacing REPLACE with the chosen ID:
export PRODUCT_ID=REPLACE
Look at the current overall_rating for the product, and choose a different positive decimal number. For example, 2.1 is the overall_rating for product 31001 shown above. You could change the rating to 4.5. Create an environment variable, replacing REPLACE with the chosen rating:
export NEW_RATING=REPLACE
Use this command to update the overall_rating, and then retrieve the product to make sure that the overall_rating has changed:
The first curl command will return the same overall_rating that you used to update it. The second curl command will return the entire product, including the updated overall_rating.
The shared flow has the same functionality in the API proxy.
Congratulations!
In this lab, you moved some common functionality from your proxy into a shared flow and called it using a FlowCallout policy.
End your lab
When you have completed your lab, click End Lab. Google Cloud Skills Boost removes the resources you’ve used and cleans the account for you.
You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.
The number of stars indicates the following:
1 star = Very dissatisfied
2 stars = Dissatisfied
3 stars = Neutral
4 stars = Satisfied
5 stars = Very satisfied
You can close the dialog box if you don't want to provide feedback.
For feedback, suggestions, or corrections, please use the Support tab.
Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.
Moduły tworzą projekt Google Cloud i zasoby na określony czas.
Moduły mają ograniczenie czasowe i nie mają funkcji wstrzymywania. Jeśli zakończysz moduł, musisz go zacząć od początku.
Aby rozpocząć, w lewym górnym rogu ekranu kliknij Rozpocznij moduł.
Użyj przeglądania prywatnego
Skopiuj podaną nazwę użytkownika i hasło do modułu.
Kliknij Otwórz konsolę w trybie prywatnym.
Zaloguj się w konsoli
Zaloguj się z użyciem danych logowania do modułu. Użycie innych danych logowania może spowodować błędy lub naliczanie opłat.
Zaakceptuj warunki i pomiń stronę zasobów przywracania.
Nie klikaj Zakończ moduł, chyba że właśnie został przez Ciebie zakończony lub chcesz go uruchomić ponownie, ponieważ spowoduje to usunięcie wyników i projektu.
Ta treść jest obecnie niedostępna
Kiedy dostępność się zmieni, wyślemy Ci e-maila z powiadomieniem
Świetnie
Kiedy dostępność się zmieni, skontaktujemy się z Tobą e-mailem
Jeden moduł, a potem drugi
Potwierdź, aby zakończyć wszystkie istniejące moduły i rozpocząć ten
Aby uruchomić moduł, użyj przeglądania prywatnego
Uruchom ten moduł w oknie incognito lub przeglądania prywatnego. Dzięki temu unikniesz konfliktu między swoim kontem osobistym a kontem do nauki, co mogłoby spowodować naliczanie dodatkowych opłat na koncie osobistym.
In this lab, you'll put a series of conditional policies in a shared flow, allowing the functionality to be shared between proxies.
Czas trwania:
Konfiguracja: 14 min
·
Dostęp na 90 min
·
Ukończono w 90 min