benomite
benomite

Reputation: 868

How to use npm in terraform entreprise?

I an trying to build a React.js application before zipping it with this code:

resource "null_resource" "build" {
  triggers = {
    always_run = "${timestamp()}"
  }
  provisioner "local-exec" {
    command = "cd ${path.module}/.. && npm run build"
    environment = var.environment_variables
  }
}
data "archive_file" "source_zip" {
  depends_on = [null_resource.build]
  type        = "zip"
  source_dir  = "../build"
  output_path = "dist/source.zip"
}

This code runs well on my local machine but fails on Terraform cloud (https://www.terraform.io/). NPM seems to be not installed on the machine where terraform runs. Here is the erro I get:

Error: Error running command 'cd ./.. && npm run build': exit status 127. Output: /bin/sh: 1: npm: not found

So, how to have npm installed on the Terraform cloud?

Upvotes: 4

Views: 3045

Answers (1)

benomite
benomite

Reputation: 868

The only possibility I found is to install node/npm on the terraform VM prior to use it. Here is my code:


resource "null_resource" "build" {
  triggers = {
    always_run = "${timestamp()}"
  }
  provisioner "local-exec" {
    command = <<-EOF
      cd ${path.module}/.. &&\
      mkdir ./node_install &&\
      cd ./node_install &&\
      curl https://nodejs.org/dist/latest-v10.x/node-v10.19.0-linux-x64.tar.gz | tar xz --strip-components=1 &&\
      export PATH="$PWD/bin:$PATH" &&\
      cd .. &&\
      npm install &&\
      npm run build
    EOF

    environment = var.environment_variables
  }
}
data "archive_file" "source_zip" {
  depends_on = [null_resource.build]
  type        = "zip"
  source_dir  = "../build"
  output_path = "dist/source.zip"
}

In the commandsection I use curl to download nodejs, then add it (temporarily) to the path so I can npm install and npm run buildafterward

Upvotes: 5

Related Questions