網頁

2023/6/26

Golang 取得GCP Services清單

Go以Google API Client Libraries來查詢APIs&Services服務列表。



事前要求

參考「GCP 設定本機應用程式存取憑證 Application Default Credentials」設定credential。

參考「Golang 取得GCP Project資訊」取得project number。


下載API modules

在專案根目錄執行以下命令下載需要的google-api-go-client modules。



查詢APIs&Services服務清單

呼叫serviceusage.NewService取得serviceusage.Service來進行操作。

呼叫serviceusage.Service.ServicesService.List取得服務清單,參數如下:

  • parent - 輸入服務所在的parent名稱,格式為projects/{project-number}{project-number}為project number,例如projects/948024786833

實際執行serviceusage.Service.ServicesService.List呼叫的serviceusage.ServicesListCall提供以下方法:

  • Field - 篩選回應物件中僅要取得屬性值的名稱。例如最後返回serviceusage.ListServicesResponse物件只需要取得NextPageToken屬性值與Services屬性物件中的NameState則輸入參數"nextPageToken""services(name,state)"
  • PageSize - 由於GCP API在查詢多筆資料時,是以分頁形式提供(也就是無法一次查詢全部),每頁預設50筆,最多200筆。
  • PageToken - 取得下一分頁結果的token參數。這token來自於前一次呼叫返回的NextPageToken

serviceusage.ServicesListCall.Do返回serviceusage.ListServicesResponse物件,屬性如下:


由於以serviceusage.Service.ServicesService.List查詢服務清單是以分頁形式提供,所以範例以for迴圈重複以返回的NextPageToken往下一頁查詢,直到NextPageToken的值為空字串代表已至最後一頁。

範例只篩選出.googleapis.com結尾的服務。

main.go

package main

import (
    "context"
    "fmt"
    "strings"

    "google.golang.org/api/cloudresourcemanager/v1"
    "google.golang.org/api/serviceusage/v1"
)

func main() {
    ctx := context.Background()
    crmService, err := cloudresourcemanager.NewService(ctx)
    if err != nil {
        panic(err)
    }

    projectId := "project-id-1"
    project, err := crmService.Projects.Get(projectId).Do()
    if err != nil {
        panic(err)
    }

    serviceusageService, err := serviceusage.NewService(ctx)
    if err != nil {
        panic(err)
    }

    parent := fmt.Sprintf("projects/%d", project.ProjectNumber)
    prefix := fmt.Sprintf("%s/services/", parent)
    serviceNames := make([]string, 0)
    pageToken := ""
    for {
        resp, err := serviceusageService.Services.List(parent).
            Fields("nextPageToken", "services(name,state)").
            PageSize(200).
            PageToken(pageToken).
            Do()
        if err != nil {
            panic(err)
        }

        for _, s := range resp.Services {
            if strings.HasSuffix(s.Name, ".googleapis.com") {
                serviceNames = append(serviceNames, strings.TrimPrefix(s.Name, prefix))
            }
        }

        pageToken = resp.NextPageToken
        if pageToken == "" {
            break
        }

    }

    for _, name := range serviceNames {
        fmt.Println(name)
    }

}

github


測試

執行結果如下。

abusiveexperiencereport.googleapis.com
acceleratedmobilepageurl.googleapis.com
accessapproval.googleapis.com
accesscontextmanager.googleapis.com
acmedns.googleapis.com
actions.googleapis.com
addressvalidation.googleapis.com
adexchangebuyer.googleapis.com
adexchangeseller.googleapis.com
adexperiencereport.googleapis.com
admin.googleapis.com
admob.googleapis.com
adsdatahub.googleapis.com
adsense.googleapis.com
adsensehost.googleapis.com
advisorynotifications.googleapis.com
aerialview.googleapis.com
aiplatform.googleapis.com
alertcenter.googleapis.com
alloydb.googleapis.com
analytics.googleapis.com
analyticsadmin.googleapis.com
analyticsdata.googleapis.com
analyticshub.googleapis.com
analyticsreporting.googleapis.com
androiddeviceprovisioning.googleapis.com
androidenterprise.googleapis.com
androidmanagement.googleapis.com
androidovertheair.googleapis.com
androidpublisher.googleapis.com
anthos.googleapis.com
anthosaudit.googleapis.com
anthosconfigmanagement.googleapis.com
anthosgke.googleapis.com
anthosidentityservice.googleapis.com
apigateway.googleapis.com
apigee.googleapis.com
apigeeconnect.googleapis.com
apigeeregistry.googleapis.com
apikeys.googleapis.com
appdevelopmentexperience.googleapis.com
appengine.googleapis.com
appengineflex.googleapis.com
appenginereporting.googleapis.com
appsmarket-component.googleapis.com
appsmarket.googleapis.com
arcore.googleapis.com
arcorecloudanchor.googleapis.com
area120tables.googleapis.com
artifactregistry.googleapis.com
assuredworkloads.googleapis.com
audit.googleapis.com
authorizedbuyersmarketplace.googleapis.com
automl.googleapis.com
automotivemaps.googleapis.com
autoscaling.googleapis.com
backupdr.googleapis.com
baremetalsolution.googleapis.com
batch.googleapis.com
beyondcorp.googleapis.com
biglake.googleapis.com
bigquery.googleapis.com
bigqueryconnection.googleapis.com
bigquerydatapolicy.googleapis.com
bigquerydatatransfer.googleapis.com
bigquerymigration.googleapis.com
bigqueryreservation.googleapis.com
bigquerystorage.googleapis.com
bigtable.googleapis.com
bigtableadmin.googleapis.com
bigtabletableadmin.googleapis.com
billingbudgets.googleapis.com
binaryauthorization.googleapis.com
blockchainnodeengine.googleapis.com
blogger.googleapis.com
books.googleapis.com
businessprofileperformance.googleapis.com
caldav.googleapis.com
calendar-json.googleapis.com
carddav.googleapis.com
certificatemanager.googleapis.com
chat.googleapis.com
checks.googleapis.com
chromedevicetoken.googleapis.com
chromemanagement.googleapis.com
chromepolicy.googleapis.com
chromeuxreport.googleapis.com
chromewebstore.googleapis.com
chronicle.googleapis.com
civicinfo.googleapis.com
classroom.googleapis.com
cloud.googleapis.com
cloudapis.googleapis.com
cloudasset.googleapis.com
cloudbilling.googleapis.com
cloudbuild.googleapis.com
cloudchannel.googleapis.com
cloudcommerceconsumerprocurement.googleapis.com
clouddebugger.googleapis.com
clouddeploy.googleapis.com
clouderrorreporting.googleapis.com
cloudfunctions.googleapis.com
cloudidentity.googleapis.com
cloudkms.googleapis.com
cloudlatencytest.googleapis.com
cloudoptimization.googleapis.com
cloudprivatecatalog.googleapis.com
cloudprofiler.googleapis.com
cloudresourcemanager.googleapis.com
cloudscheduler.googleapis.com
cloudsearch.googleapis.com
cloudshell.googleapis.com
cloudsupport.googleapis.com
cloudtasks.googleapis.com
cloudtrace.googleapis.com
cloudvideosearch.googleapis.com
composer.googleapis.com
compute.googleapis.com
confidentialcomputing.googleapis.com
config.googleapis.com
connectgateway.googleapis.com
connectors.googleapis.com
contactcenteraiplatform.googleapis.com
contactcenterinsights.googleapis.com
contacts.googleapis.com
container.googleapis.com
containeranalysis.googleapis.com
containerfilesystem.googleapis.com
containerregistry.googleapis.com
containerscanning.googleapis.com
containersecurity.googleapis.com
containerthreatdetection.googleapis.com
contentwarehouse.googleapis.com
copresence.googleapis.com
customsearch.googleapis.com
datacatalog.googleapis.com
dataconnectors.googleapis.com
dataflow.googleapis.com
dataform.googleapis.com
datafusion.googleapis.com
datalabeling.googleapis.com
datalineage.googleapis.com
datamigration.googleapis.com
datapipelines.googleapis.com
dataplex.googleapis.com
dataproc.googleapis.com
datastore.googleapis.com
datastream.googleapis.com
datastudio.googleapis.com
deploymentmanager.googleapis.com
dfareporting.googleapis.com
dialogflow.googleapis.com
digitalassetlinks.googleapis.com
directions-backend.googleapis.com
discovery.googleapis.com
discoveryengine.googleapis.com
displayvideo.googleapis.com
distance-matrix-backend.googleapis.com
dlp.googleapis.com
dns.googleapis.com
docs.googleapis.com
documentai.googleapis.com
domains.googleapis.com
domainsrdap.googleapis.com
doubleclickbidmanager.googleapis.com
doubleclicksearch.googleapis.com
drive.googleapis.com
driveactivity.googleapis.com
drivelabels.googleapis.com
earthengine.googleapis.com
edgecache.googleapis.com
edgecontainer.googleapis.com
edgenetwork.googleapis.com
elevation-backend.googleapis.com
embeddedassistant.googleapis.com
endpoints.googleapis.com
endpointsportal.googleapis.com
enterpriseknowledgegraph.googleapis.com
essentialcontacts.googleapis.com
eventarc.googleapis.com
eventarcpublishing.googleapis.com
factchecktools.googleapis.com
fcm.googleapis.com
fcmdata.googleapis.com
fcmregistrations.googleapis.com
file.googleapis.com
firebase.googleapis.com
firebaseappcheck.googleapis.com
firebaseappdistribution.googleapis.com
firebaseapptesters.googleapis.com
firebasedatabase.googleapis.com
firebasedynamiclinks.googleapis.com
firebaseextensions.googleapis.com
firebaseextensionspublisher.googleapis.com
firebasehosting.googleapis.com
firebaseinappmessaging.googleapis.com
firebaseinstallations.googleapis.com
firebaseml.googleapis.com
firebaseremoteconfig.googleapis.com
firebaseremoteconfigrealtime.googleapis.com
firebaserules.googleapis.com
firebasestorage.googleapis.com
firestore.googleapis.com
firestorekeyvisualizer.googleapis.com
firewallinsights.googleapis.com
fitness.googleapis.com
forms.googleapis.com
games.googleapis.com
gamesconfiguration.googleapis.com
gameservices.googleapis.com
gamesmanagement.googleapis.com
geocoding-backend.googleapis.com
geolocation.googleapis.com
gkebackup.googleapis.com
gkeconnect.googleapis.com
gkedataplanev2.googleapis.com
gkehub.googleapis.com
gkemulticloud.googleapis.com
gkeonprem.googleapis.com
gmail.googleapis.com
gmailpostmastertools.googleapis.com
googleads.googleapis.com
googlecloudmessaging.googleapis.com
groupsmigration.googleapis.com
groupssettings.googleapis.com
gsuiteaddons.googleapis.com
healthcare.googleapis.com
homegraph.googleapis.com
iam.googleapis.com
iamcredentials.googleapis.com
iap.googleapis.com
identitytoolkit.googleapis.com
ids.googleapis.com
indexing.googleapis.com
integrations.googleapis.com
issuerswitch.googleapis.com
jobs.googleapis.com
keep.googleapis.com
kgsearch.googleapis.com
kmsinventory.googleapis.com
krmapihosting.googleapis.com
language.googleapis.com
libraryagent.googleapis.com
licensing.googleapis.com
lifesciences.googleapis.com
livestream.googleapis.com
localservices.googleapis.com
logging.googleapis.com
looker.googleapis.com
managedidentities.googleapis.com
manufacturers.googleapis.com
maps-android-backend.googleapis.com
maps-backend.googleapis.com
maps-embed-backend.googleapis.com
maps-ios-backend.googleapis.com
mapsbooking.googleapis.com
mapsfleetrouting.googleapis.com
mapsplatformdatasets.googleapis.com
mediatranslation.googleapis.com
memcache.googleapis.com
merchantapi.googleapis.com
mesh.googleapis.com
meshca.googleapis.com
meshconfig.googleapis.com
meshtelemetry.googleapis.com
metastore.googleapis.com
microservices.googleapis.com
migrate.googleapis.com
migrationcenter.googleapis.com
ml.googleapis.com
mlkit.googleapis.com
mobilecrashreporting.googleapis.com
monitoring.googleapis.com
moviesanywhere.googleapis.com
multiclusteringress.googleapis.com
multiclustermetering.googleapis.com
multiclusterservicediscovery.googleapis.com
mybusinessaccountmanagement.googleapis.com
mybusinessbusinessinformation.googleapis.com
mybusinesslodging.googleapis.com
mybusinessnotifications.googleapis.com
mybusinessplaceactions.googleapis.com
mybusinessqanda.googleapis.com
mybusinessverifications.googleapis.com
netapp.googleapis.com
networkactions.googleapis.com
networkconnectivity.googleapis.com
networkmanagement.googleapis.com
networksecurity.googleapis.com
networkservices.googleapis.com
networksubscriptions.googleapis.com
networktopology.googleapis.com
notebooks.googleapis.com
ondemandscanning.googleapis.com
opsconfigmonitoring.googleapis.com
orgpolicy.googleapis.com
osconfig.googleapis.com
oslogin.googleapis.com
pagespeedonline.googleapis.com
partnerdev-mapsbooking.googleapis.com
partners-json.googleapis.com
paymentsresellersubscription.googleapis.com
people.googleapis.com
performanceparameters.googleapis.com
photoslibrary.googleapis.com
picker.googleapis.com
places-backend.googleapis.com
places.googleapis.com
playablelocations.googleapis.com
playcustomapp.googleapis.com
playdeveloperreporting.googleapis.com
playintegrity.googleapis.com
plus.googleapis.com
plusdomains.googleapis.com
plushangouts.googleapis.com
policyanalyzer.googleapis.com
policysimulator.googleapis.com
policytroubleshooter.googleapis.com
poly.googleapis.com
privateca.googleapis.com
prod-tt-sasportal.googleapis.com
programmablesearchelement.googleapis.com
publicca.googleapis.com
pubsub.googleapis.com
pubsublite.googleapis.com
rapidmigrationassessment.googleapis.com
readerrevenuesubscriptionlinking.googleapis.com
realtime.googleapis.com
realtimebidding.googleapis.com
recaptchaenterprise.googleapis.com
recommendationengine.googleapis.com
recommender.googleapis.com
redis.googleapis.com
regionlookup.googleapis.com
remotebuildexecution.googleapis.com
replicapool.googleapis.com
replicapoolupdater.googleapis.com
reseller.googleapis.com
resourcesettings.googleapis.com
resourceviews.googleapis.com
retail.googleapis.com
risc.googleapis.com
roads.googleapis.com
routes.googleapis.com
run.googleapis.com
runapps.googleapis.com
runtimeconfig.googleapis.com
safebrowsing-json.googleapis.com
safebrowsing.googleapis.com
sasportal.googleapis.com
script.googleapis.com
searchads360.googleapis.com
searchconsole.googleapis.com
secretmanager.googleapis.com
securedlandingzone.googleapis.com
securetoken.googleapis.com
securitycenter.googleapis.com
serviceconsumermanagement.googleapis.com
servicecontrol.googleapis.com
servicedirectory.googleapis.com
servicemanagement.googleapis.com
servicenetworking.googleapis.com
serviceusage.googleapis.com
sheets.googleapis.com
shoppingcontent.googleapis.com
siteverification.googleapis.com
slides.googleapis.com
smartdevicemanagement.googleapis.com
smbstorefront.googleapis.com
sourcerepo.googleapis.com
spanner.googleapis.com
speech.googleapis.com
sql-component.googleapis.com
sqladmin.googleapis.com
stackdriver.googleapis.com
static-maps-backend.googleapis.com
storage-api.googleapis.com
storage-component.googleapis.com
storage.googleapis.com
storageinsights.googleapis.com
storagetransfer.googleapis.com
stream.googleapis.com
street-view-image-backend.googleapis.com
streetviewpublish.googleapis.com
sts.googleapis.com
subscribewithgoogle.googleapis.com
subscribewithgoogledeveloper.googleapis.com
surveys.googleapis.com
tagmanager.googleapis.com
tasks.googleapis.com
tenor.googleapis.com
testing.googleapis.com
texttospeech.googleapis.com
tile.googleapis.com
timeseriesinsights.googleapis.com
timezone-backend.googleapis.com
toolresults.googleapis.com
tpu.googleapis.com
trafficdirector.googleapis.com
transcoder.googleapis.com
transferappliance.googleapis.com
translate.googleapis.com
translationhub.googleapis.com
travelimpactmodel.googleapis.com
travelpartner.googleapis.com
travelpartnerprices.googleapis.com
usercontext.googleapis.com
vault.googleapis.com
verifiedaccess.googleapis.com
versionhistory.googleapis.com
videointelligence.googleapis.com
vision.googleapis.com
visionai.googleapis.com
vmmigration.googleapis.com
vmwareengine.googleapis.com
vpcaccess.googleapis.com
walletobjects.googleapis.com
webfonts.googleapis.com
webrisk.googleapis.com
websecurityscanner.googleapis.com
workflowexecutions.googleapis.com
workflows.googleapis.com
workloadcertificate.googleapis.com
workloadmanager.googleapis.com
workstations.googleapis.com
youtube.googleapis.com
youtubeanalytics.googleapis.com
youtubeembeddedplayer.googleapis.com
youtubeoembed.googleapis.com
youtubereporting.googleapis.com


沒有留言:

張貼留言