Grace.B
Grace.B

Reputation: 61

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' } }

Upvotes: 2

Views: 2140

Answers (1)

Matteo
Matteo

Reputation: 2624

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.

Upvotes: 1

Related Questions