Search code examples
bashazureterraform

How to correctly fail bash script in terraform external datasource


I have a terraform datasource:

data "external" src {
  program = ["bash", "my_script.sh"]
}

In the my_script.sh I assert that environment variable SOME_ENV is set and if so, the script does some logic:

#!/bin/bash

if [ -z $SOME_ENV ]; then
  echo "Env SOME_ENV is missed"
  exit 1
fi

# do some work...

Otherwise, I want to highlight during the terraform apply that env is missed.

Current behaviour: The following message is printed to the console:

...

│ The data source received an unexpected error while attempting to execute the program.
│ 
│ The program was executed, however it returned no additional error messaging.
│ 
│ Program: /bin/bash
│ State: exit status 1

Is there any options to pass error message while applying?

Thanks


Solution

  • You can pass an error message from script to Terraform by writing the error message to the standard error (stderr) stream. In your script, you can write the error message to stderr using the ">&2" redirection operator. Ex: >&2 echo "Error: Environment variable SOME_ENV is missing"

        #!/bin/bash
        
        if [ -z $SOME_ENV ]; then
          >&2 echo "Error: Environment variable SOME_ENV is missing"
          exit 1
        fi
    
        provider "azurerm" {
          features {}
        }
        data "external" src {
          program = ["bash", "my_script.sh"]
        }
    

    Terraform apply

    enter image description here