title: Getting phase in a Terraform external data source script
body: <p>I'm going to use an external data source to create an AWS resource that is not currently supported (an AWS Organizations OU). I'm doing some testing with creating an S3 bucket, because the workflow is similar. I'm using the external data source to call a bash script, and pass the parameters (e,g, bucket name, region).</p>
  
  <p>The script is checking if the S3 bucket exists, and if not, creating it. The script is written to return success etc. if it does already exist.</p>
  
  <p>What I'm seeing is that the script is executed even in the "terraform plan" phase, and there does not appear to be either a stdin argument or environment variable passed to the script in order to indicate the plan/apply/destroy phase. Is this possible to do/deduce ? Ideally the script would be invoked with "plan" and then return if the resource exists already. Then the "apply" phase could then create if necessary.</p>
  
  <p>Is it possible to get the Terraform phase (plan/apply/destroy) in the script ? Or other ways to avoid the script getting invoked fully during the plan stage ?</p>
  
  <p>As a reminder, ultimately I'm not trying to create an S3 bucket (because I know I can do that in Terraform already), I want to create an Organizations OU, but this is an easier workflow to test with...</p>
  
  <p>Example calling code :</p>
  
  <pre><code>data "external" "create_bucket" { 
      program = ["bash", "create_bucket.sh"]
      query = { 
          region = "ca-central-1" 
          bucket_name = "mytestbucket" 
      }
  }
  </code></pre>
  
  <p>Also tried using local-exec :</p>
  
  <p>When I have the following calling code:</p>
  
  <pre><code>variable "bucket_name_list" {
      type = "list"
      default = ["neilp-dummylist-1","neilp-dummylist-2",
                 "neilp-dummylist-3"]
  }
  
  module "local" {
      source           = "../local"
      bucket_name_list = ["${var.bucket_name_list}"]
      bucket_region    = "ca-central-1"
  }
  </code></pre>
  
  <p>With the module :</p>
  
  <pre><code>resource "null_resource" "test" {
      count = "${length(var.bucket_name_list)}"
  
      provisioner "local-exec" {
          command = "aws s3api create-bucket 
                         --bucket 
                           ${element(var.bucket_name_list, count.index)} 
                         --create-bucket-configuration
                           LocationConstraint=${var.bucket_region}"
      }
  }
  </code></pre>
  
  <p>The issue here, is that it just tracks the number of entries in the <code>bucket_name_list</code>, and if I change a value but keep the number of entries the same, it does not notice. </p>