Home > OS >  How do I pass a variable from a pipeline task into a terraform task and apply it in my terraform cod
How do I pass a variable from a pipeline task into a terraform task and apply it in my terraform cod

Time:11-19

So I have a pipeline with a task, where I check for the date through Powershell.

 - task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: |
          $iso8601_time = Get-Date -Format "o"
          echo "##vso[task.setvariable variable=pitr_time;]$iso8601_time"
        displayName: "Get point-in-time record before launching migration"

I am trying to use this date later in my terraform task to create a database based on the DateTime from my PowerShell task.

If I got it correctly with the use of

echo "##vso[task.setvariable variable=pitr_time;]$iso8601_time"

I create an environment variable with the name pitr_time that could be passed on to other tasks within the same pipeline.

Thus, I now have a second task where I use this environment variable.

- stage: DeployInfraPOC
  dependsOn: BuildInfraPOC
  variables:
    env: poc
    # TODO: check if variable get transfered to tf.
    TF_VAR_PITR: $(pitr_time)
  jobs: 
  - template: templates/deploy-infra.yml
    parameters:
      env: poc
      armServiceConnection: "Service connection devops"
      projectRoot: $(System.DefaultWorkingDirectory)
      planArtifactName: "pitr-database-migration-poc-$(Build.BuildId).tfplan

Now, when I checked the terraform documentation, I saw that I had to define it using the prefix "TF_VAR_" to use the variable I want to pass.

But now my question is: how can I use this variable in Terraform?

I thought I could just add it inside my variables.tf file as

variable "TF_VAR_PITR" {
  description = "Env var - Point-in-time restore."
  type = string
}

But it doesn't seem to work when I want to call my variable inside my main.tf like this

resource "azurerm_mssql_database" "mssqldb" {
  name                          = "db-bkup-temp-pitr"
  server_id                     = data.azurerm_mssql_server.mssqlsrv.id
  create_mode                   = "PointInTimeRestore"
  creation_source_database_id   = "/subscriptions/##############"
  restore_point_in_time         = var.TF_VAR_PITR
  }

What am I doing wrong? Are there better alternatives?

CodePudding user response:

If your env variable is TF_VAR_PITR, then the TF varriable is called PITR:

variable "PITR" {
  description = "Env var - Point-in-time restore."
  type = string
}
  • Related