Can netlify-cli be used in a CD build script?

Hello! Is it possible to use netlify-cli in a build.sh script? Locally I can easily use netlify env:set... to set a few environment variables. Currently I’m copying the COMMIT_REF and CONTEXT variables to the UI so that I can access them at runtime.

However, netlify-cli requires linking it to a site, which I’m not sure is possible in a continuous deployment environment on Netlify.

Is the API the only option in this case to take advantage of the automatic CD system?

Thank you!

Yes, you can use it in a script. You can use the --site-id flag to specify a site ID without linking to a site.

So I ended up with:

build.sh

netlify link --id $SITE_ID
netlify env:set GIT_COMMIT $COMMIT_REF
netlify env:set GIT_BRANCH $BRANCH
npx astro build

But this requires me to click the link in the build output to authenticate. Can I authenticate automatically?

You can set the auth token as well: NETLIFY_AUTH_TOKEN. This is all documented: Netlify CLI deploy command

Perfect! I was looking in the login command info. Thank you much.

If I currently auto deploy using git push, can this run as part of that routine? With Netlify deploy I’d be circumventing that?

I’m sorry, I don’t understand your question completely. If you deploy using git push, Netlify will automatically build and deploy your site. Why would the CLI be needed there?

I ended up using netlify link --id $SITE_ID to authenticate during build to then use env:set commands.

Thank you!

Oh that’s awesome! Thanks for sharing this with the community.