Search code examples
bashazureshellterraform

Unable to run shell script in Terraform


I am trying to run a shell script with the local-exec command in Terraform. When I run this, it keeps coming up with the error "Can't open appsettings.sh". This script runs fine when run manually. Any ideas what I am missing?

resource "null_resource" "sp" {

  triggers = {
    shell_hash = "${sha256(file("${path.module}/appsettings.sh"))}"
  }
  provisioner "local-exec" {
      command = "appsettings.sh ${azuread_application.rbac-server-principal.application_id} ${azuread_application.rbac-client-principal.application_id}"
      interpreter = ["sh"]
      working_dir = "${path.module}"
  }
}

error message:

Error: Error running command 'appsettings.sh 59942507-xxxx-xxxx-xxxxx 4c64-xxxx-xxxx-xxxxx': exit status 127. Output: sh: 0: Can't open appsettings.sh 59942507-xxxx-xxxx-xxxxx 4c64-xxxx-xxxx-xxxxx'

Solution

  • The issue here is, terraform run the command as

    ["/bin/sh" "-c" "appsettings.sh arg1 arg2"]
    

    So the command interpreter take appsettings.sh as the command name which is very similar to running as below

    $appsettings.sh arg1 arg2
    

    which cannot be done as there is no command like this. So to run that shell script you either has to provide the absolute path of the shell script or relative as shown below

    $ ./appsettings.h
    $ /home/user/appsettings.sh # Example
    

    To achieve this rearrange your command attr as below

    command = "./appsettings.sh ${azuread_application.rbac-server-principal.application_id} ${azuread_application.rbac-client-principal.application_id}"
    
     OR
    
    command = "${path.module}/appsettings.sh ${azuread_application.rbac-server-principal.application_id} ${azuread_application.rbac-client-principal.application_id}"
    

    i.e. add ./appsettings