9

is there a possibility to add a sql user to the azure sql via terraform? https://www.mssqltips.com/sqlservertip/5242/adding-users-to-azure-sql-databases/

Or is there a better suggestions how to create a SQL user?

Thanks

1 Answer 1

11

Yes you can do it from Terraform if that is what you want to happen. I would use a null resource provider in Terraform to execute the commands from the box that is running Terraform. You could use PowerShell, CMD, etc. to connect to the database after it is created and create your user account. Here is an example of how to use the null resource provider.

I would image it would look something like this, in this example I am using the SqlServer PowerShell module.

resource "null_resource" "create-sql-user" {

  provisioner "local-exec" {
    command = "Add-SqlLogin -LoginName ${var.loginName} -LoginType ${var.loginType}"
    interpreter = ["PowerShell", "-Command"]
  }

  depends_on = ["azurerm_sql_database.demo"]
}

You could of course do it with our CLI tools, but this would guarantee it is part of your Terraform deployment.

8
  • 1
    Then I prefer to do it in power shell directly
    – MelleD
    Feb 11, 2019 at 6:34
  • 1
    @Jamie : how do you connect to the SQL Server, before firing the powershell command?
    – candidson
    Sep 24, 2019 at 15:59
  • How would you you add a password as well using only the command?
    – Caio Gomes
    Jan 24, 2020 at 17:59
  • 1
    @CaioGomes checkout the LoginPSCredential option in the docs. learn.microsoft.com/en-us/powershell/module/sqlserver/…
    – Jamie
    Jan 24, 2020 at 19:16
  • 1
    @CaioGomes you can alter the command to execute a script. so instead of -Command you could do -File and pass a file name. You will need to set the working_dir property or use releative paths.
    – Jamie
    Jan 24, 2020 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.