create cloud function with trigger cloud storage - google-cloud-functions

I'm trying to deploy a cloud function from the serverless framework, and setting as a trigger that is activated when files are created in a bucket, but it doesn't work and I can't find more information about this in the documentation
serverless.yml
read-file:
handler: ReadFile
events:
- event:
eventType: providers/cloud.storage/eventTypes/google.storage.object.archive
resource: "projects/${self:provider.project}/buckets/${env:BUCKET_NAME_GS}"
memorySize: 128
environment:
AUDIENCE_AUTH0: ${env:AUDIENCE_AUTH0}
DOMAIN_AUTH0: ${env:DOMAIN_AUTH0}
serverless response:
{
"code":400,
"message":"The request has errors",
"status":"INVALID_ARGUMENT",
"details":[{"#type":"type.googleapis.com/google.rpc.BadRequest","fieldViolations":[{"field":"event_trigger","description":"Unknown event_type providers/cloud.storage/eventTypes/google.storage.object.archive"
}

Related

Firebase Cloud Function Braintree unexpectedError with Blaze Plan

I have a firebase cloud function and want to enable payments via braintree under that function.
I have a upgraded Blaze Plan for firebase but the braintree is still throwing that unexpectedError
const functions = require('firebase-functions');
var braintree = require("braintree");
var gateway = braintree.connect({
environment: "Sandbox",
merchantId: "xxxxxxxxxxxxxxxx",
publicKey: "xxxxxxxxxxxxxxxxxxxx",
privateKey: "xxxxxxxxxxxxxxxxxxx"
});
Studying various on SO almost all posts are pointing that you must upgrade your plan but I am already in blaze plan.

403 error when attempting to fetch google analytics 4 data from app script

I am attempting to connect a custom community connector to google analytics 4 in order to get data from analytics and be able to modify it in app script and then send it to data studio. However I am having difficulty connecting and retrieving data from google analytics.
The error:
{ error:
{ code: 403,
message: 'Google Analytics Data API has not been used in project 640397821842 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/analyticsdata.googleapis.com/overview?project=640397821842 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.',
status: 'PERMISSION_DENIED',
details: [ [Object], [Object] ] } }
I have the scopes set up
"oauthScopes": [
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/analytics.readonly"
],
The code i am trying to test:
function testFetch(){
const options = {
entry: { propertyId: 263290444},
"dateRanges": [{ "startDate": "2020-12-01", "endDate": "2021-03-01" }],
"dimensions": [{ "name": "country" }],
"metrics": [{ "name": "activeUsers" }],
// etc.
}
var response = UrlFetchApp.fetch(
'https://analyticsdata.googleapis.com/v1alpha:runReport', {
method: 'POST',
muteHttpExceptions: true,
headers: {
Authorization : `Bearer ${ScriptApp.getOAuthToken()}`
},
contentType: 'application/json; charset=utf-8',
payload: JSON.stringify(options)
});
var result = JSON.parse(response.getContentText());
console.log(result);
'Google Analytics Data API has not been used in project 640397821842 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/analyticsdata.googleapis.com/overview?project=640397821842 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.',
status:
The problem you are having is that you have not enabled the API in Google developer console You need to follow the link in the error message then go to library and look for Google analytics data api and enable it.
Once you have enabled it try and run your application again.
For those with the same issue who may have overlooked some steps:
Create an API project at https://console.cloud.google.com/
Make sure to connect your appscript project to your cloud API project by changing the Google Cloud Platform (GCP) Project in appscript settings (It is set to a default project when you start).
Enable the required APIs from the API Library in the cloud project.
Now you will be able to fetchurls related to the APIs you have enabled.

How to pass attributes from Cloud Scheduler to Pub/Sub?

I am trying to trigger a Cloud Function which runs on a schedule as such:
Cloud Scheduler -> Cloud Pub/Sub -> Cloud Functions
My Cloud Function uses attributes from the Pub/Sub message:
let messageTitle = null;
try {
messageTitle = message.attributes.messageTitle;
} catch (e) {
console.error('no title in pub/sub message', e);
}
How can I create a scheduler which has attributes?
I have tried entering this in the Scheduler 'Payload' field:
{
"data": "string",
"attributes": {
messageTitle: "TEST 3 title",
messageBody: "TEST 3 body"
},
"messageId": "string",
"publishTime": "string"
}
But it does not create the attributes in Pub/Sub.
Today (july 2020), an important thing to know on Cloud Scheduler: Few parameters are accessible through the console.
If you want to access to advance parameter, use the gcloud command or the rest API
Now you can access to the retry policies and to the attributes on PubSub message.
gcloud scheduler jobs create pubsub --message-body=my_body \
--attributes=att1=val1,att2=val2 --topic=topicName \
--schedule="0 0 * * *" --time-zone=UTC mySchedulerName
Note, in the console, you can only define the payload, I mean the data field in the PubSub message, equal to the --message-body= in the command line

Accessing user token in IBM Cloud Functions serverless app secured with OAuth user authentication

I am creating a serverless app using IBM Cloud Functions. My Cloud Functions API is secured with OAuth user authentication using an IBM Cloud App ID service. When a user logs into my app, an access token is generated by this service. I want to extract user data from that access token so that I can customize the user experience.
How do I access that token from within a Cloud Functions action that is coded for Node.js 10?
Example
The openwhisk webaction doc
https://github.com/apache/openwhisk/blob/master/docs/webactions.md
states that the following code
function main(params) {
return { response: params };
}
generates the following response
{
"response": {
"__ow_method": "get",
"__ow_headers": {
"accept": "*/*",
"connection": "close",
"host": "172.17.0.1",
"user-agent": "curl/7.43.0"
},
"__ow_path": ""
}
}
From that data I should be able to get HTTP request details. Specifically, I should be able to get the Authorization header value off the "__ow_headers" property of the action argument (params).
However, the same code inside an IBM Cloud Functions web action generates nothing. Nothing exists on the params object.

Trigger a cloud build pipeline using Cloud Function

I'm trying to create a cloud function listening to cloudbuilds topic and making an API call to trigger the build. I think I'm missing something in my index.js file (I'm new to Node.js). Can you provide a sample example of a Cloud Function making an API call to the Cloud Build API?
Here is my function:
const request = require('request')
const accessToken = '$(gcloud config config-helper --format='value(credential.access_token)')';
request({
url: 'https://cloudbuild.googleapis.com/v1/projects/[PROJECT_ID]/builds',
auth: {
'bearer': accessToken
},
method: 'POST',
json: {"steps": [{"name":"gcr.io/cloud-builders/gsutil", "args": ['cp','gs://adolfo-test-cloudbuilds/cloudbuild.yaml', 'gs://adolfo-test_cloudbuild/cloudbuild.yaml']}]},
},
module.exports.build = (err, res) => {
console.log(res.body);
});
I was executing the command gcloud config config-helper --format='value(credential.access_token)', copying the token, and putting it as a value to the variable accessToken. But this didn't work for me.
Here is the error: { error: { code: 403, message: 'The caller does not have permission', status: 'PERMISSION_DENIED' } }
I had the same exact problem and I have solved it by writing a small package, you can use it or read the source code.
https://github.com/MatteoGioioso/google-cloud-build-trigger
With this package you can run a pre-configured trigger from cloud build.
You can also extend to call other cloud build API endpoints.
As my understanding cloud build API requires either OAuth2 or a service account. Make sure you gave the right permission to cloud build in the gcp console under IAM. After that you should be able to download the service-account.json file.