Terraform Inconsistent Azure VM Names - azure

I have the following terraform code that creates multiple instances of a Azure VM based on a variable called nb_instance
module "create-servers" {
  source              = "../../Modules/Create-Vms"
  resource_group_name = azurerm_resource_group.rg.name
  vm_hostname         = "testvm"
  nb_instances = 2
On my create-servers module, I have the following code
resource "azurerm_virtual_machine" "vm-windows" {
  count                         = var.nb_instances 
  name                          = "${var.vm_hostname}${format("%02d",count.index+1)}"
  resource_group_name           = data.azurerm_resource_group.vm.name
Which works great, however I'm getting inconsitent naming convention between the Azure resource and the actual server name of the VM.
Azure displays the server as testvm01 and testvm02 however the server's actual OS name is testvm-1 and testvm-2 . My desired name is testvm02 which is what I expected within the module. Is there a workaround for this to keep both names consistent?

You also need to set the property os_profile.computer_name
https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/virtual_machine#os_profile

Related

Azure - Create Function App hostkey with Terraform azapi/bicep/powershell

I'm working on automating the rotation of my azure function app's host key, which is used to maintain a more secure connection between my API Management and my function apps. The issue is that I can not figure out how to accomplish this based on the lack of clear documentation. I found a document for how to create a key for a specific function within the function app, but not for the host level. I've tried using the web ui resource manager to figure out what the proper values are, but host seems to have no values available by GET request to help me see what the formatting needs to be. In fact, I can't find any reference to my function app's host keys anywhere in the resource manager UI. (Of course I can in the portal).
I don't care if it's powershell, bicep, ARM, terraform azapi, whatever, I'd just like to find a way to accomplish the creation of a new hostkey so that I can control it's rotation with terraform. Does anyone know how to accomplish this?
Right now my attempt looks like
resource "azapi_resource" "function_host_key" {
type = "Microsoft.Web/sites/host/functionkeys#2018-11-01"
name = "${azurerm_windows_function_app.api_function.name}-host-key"
parent_id = "${azurerm_windows_function_app.api_function.id}/host"
body = jsonencode({
properties = {
name = "test-key-terraform"
value = "asdfasdfasdfasdfasdfasdfasdf"
}
})
}
I also tried
resource "azapi_resource" "function_host_key" {
type = "Microsoft.Web/sites#2018-11-01"
name = "${azurerm_windows_function_app.api_function.name}-host-key"
parent_id = "${azurerm_windows_function_app.api_function.id}/functionsAppKeys"
location = var.region
}
since it said the body was invalid, but this also throws an error due to there being no body. I'm wondering if this just isn't possible.
I also just tried
resource "azapi_resource" "function_host_key" {
type = "Microsoft.Web/host/functionkeys#2018-11-01"
name = "${azurerm_windows_function_app.api_function.name}-host-key"
parent_id = "${azurerm_windows_function_app.api_function.id}/host"
location = var.region
}
and the result said that it was expecting
parent_id of `parent_id is invalid`: expect ID of `Microsoft.Web/host`
so I'm not sure what that parent_id should be.
I found an example through a bash/powershell script using the azure rest API, but I get a 403 error when I attempt to do it, I can only assume because my function app is secured, but I'm not sure a good way to determine that.
There must be a way to create a key programmatically...
UPDATE
I believe that this has been purposely made impossible now to do with terraform and I need to, as grose and backwards as it may be, use a CLI command in my pipeline. I understand you can do this, but it is (ofc my opinion) that if I am using terraform, I have terraform manage something, not have random CLI commands outside of terraform doing things that TF should be able to manage.
I created a key using az functionapp keys set and that worked, and the output explicitly stated that the type of resource which was created was Microsoft.Web/sites/host/functionKeys, so I went to the Azure Resource Explorer to see what versions were available for this type, since it clearly exists.. and found that nope, azure does not have it listed.
What confuses me is that I see this being done w/ ARM templates and I believe that my code matches theirs, just I'm using AZAPI.. and I get a not found error. Giving up for now

Get inbound ip adress from azurerm_windows_web_app in Terraform

I want to create azurerm_mssql_firewall_rule resource witch allows IP of "Azure windows web app".
When I write it manually it works fine. f.e.:
resource "azurerm_mssql_firewall_rule" "api_cloud" {
name = var.cloud_firewal_rule_name
server_id = azurerm_mssql_server.api.id
start_ip_address = "00.000.000.00"
end_ip_address = "00.000.000.00"
}
I want to get IP address like this start_ip_address/end_ip_address = azurerm_windows_web_app.api.inbound_ip_address.
But there isn't inbound option in azurerm_windows_web_app, I can only access outbound addresses azurerm_windows_web_app.api.outbound_ip_addresses.
Is there is anyway do something like this?
IN SHORT:
How to get this IP address with terraform?
Yes, there is but it's a bit complicated due to the way Terraform works. I used a Linux App Service in my examples but it should work identically for both Windows and Linux versions. Let's go:
So, things are a bit more complicated due to the fact that App Services have quite a big range of possible outbound IP addresses as they are running on a shared infrastructure. Therefore it returns a list with an unknown length. That makes things annoying for Terraform. As an example, this is how you usually iterate through multiple items in Terraform using for_each:
resource "azurerm_mssql_firewall_rule" "example" {
for_each = toset(azurerm_linux_web_app.api_app.outbound_ip_address_list)
name = "FirewallRule"
server_id = azurerm_mssql_server.example.id
start_ip_address = each.key
end_ip_address = each.key
}
In this snippet, you take the list of outbound IP addresses from the App Service, cast them to a set, and then iterate through it. However, this only works if the App Service already exists - if you are starting from an empty slate, you will face the following error:
azurerm_linux_web_app.api_app.outbound_ip_address_list is a list of
string, known only after apply
The "for_each" map includes keys
derived from resource attributes that cannot be determined until
apply, and so Terraform cannot determine the full set of keys that
will identify the instances of this resource.
When working with
unknown values in for_each, it's better to define the map keys
statically in your configuration and place apply-time results only in
the map values.
Alternatively, you could use the -target
planning option to first apply only the resources that the for_each
value depends on, and then apply a second time to fully converge.
Luckily Terraform has a quite helpful error message, which tells us how we can work around the problem. Using the -target parameter we can first create the App Service like this
terraform apply -target=azurerm_linux_web_app.api_app
This should only create the App Service and dependencies required by it. Afterward, we can then execute Terraform normally and it should work as desired without any errors. It's not very pretty, but currently, there are no better ways of achieving exactly what you want.

terraform interpolation with variables returning error [duplicate]

# Using a single workspace:
terraform {
backend "remote" {
hostname = "app.terraform.io"
organization = "company"
workspaces {
name = "my-app-prod"
}
}
}
For Terraform remote backend, would there be a way to use variable to specify the organization / workspace name instead of the hardcoded values there?
The Terraform documentation
didn't seem to mention anything related either.
The backend configuration documentation goes into this in some detail. The main point to note is this:
Only one backend may be specified and the configuration may not contain interpolations. Terraform will validate this.
If you want to make this easily configurable then you can use partial configuration for the static parts (eg the type of backend such as S3) and then provide config at run time interactively, via environment variables or via command line flags.
I personally wrap Terraform actions in a small shell script that runs terraform init with command line flags that uses an appropriate S3 bucket (eg a different one for each project and AWS account) and makes sure the state file location matches the path to the directory I am working on.
I had the same problems and was very disappointed with the need of additional init/wrapper scripts. Some time ago I started to use Terragrunt.
It's worth taking a look at Terragrunt because it closes the gap between Terraform and the lack of using variables at some points, e.g. for the remote backend configuration:
https://terragrunt.gruntwork.io/docs/getting-started/quick-start/#keep-your-backend-configuration-dry

AzureWebJobsScriptRoot variable is not defined on Azure Functions, but returns correct value locally

AzureWebJobsScriptRoot variable is not defined on Azure Functions. The code below returns no value.
System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Process)["AzureWebJobsScriptRoot"];
However, %HOME%\site\wwwroot will be returned based on below:
AzureWebJobsScriptRoot
AzureWebJobsScriptRoot
The path to the root directory where the host.json file and function folders are located. In a function app, the default is %HOME%\site\wwwroot.
Key Sample value
AzureWebJobsScriptRoot %HOME%\site\wwwroot
It returns correct value locally, not %HOME%\site\wwwroot
Update
Is this a bug with Azure Functions?
If so, what is an alternative solution?
Before the issue is fixed by Microsoft, can this variable, AzureWebJobsScriptRoot, be defined myself to "%HOME%\site\wwwroot" on Azure?
https://github.com/Azure/Azure-Functions/issues/1146
https://github.com/MicrosoftDocs/azure-docs/issues/26761
I test in my site and get the same problem with you. As the article said, when running in Azure, will default to %HOME%\site\wwwroot and it set the function folder under home\site\wwwroot.
However, when I set AzureWebJobsScriptRoot in Azure funtion Application Settings, it will show in the output like below:
If you configure a function app with a different value for AzureWebJobsScriptRoot, then the functions host should honor that new value. For example, if you set AzureWebJobsScriptRoot = D:\home\site\wwwroot\foo then the functions host would look for a host.json file and function directories in the D:\home\site\wwwroot\foo location.
By default, this environment variable is not set. So it is expected that if you did not set it yourself, then System.Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot") will return null.
Be aware that if you modify this setting, other components like the portal, visual studio, visual studio code, etc will not be aware of setting and will deploy your code to the normal default location. If you want to customize this setting, its up to you to make sure the application code is deployed to the right location.
Please refer the full details here

How to use multiple Terraform Providers sequentially

How can I get Terraform 0.10.1 to support two different providers without having to run 'terraform init' every time for each provider?
I am trying to use Terraform to
1) Provision an API server with the 'DigitalOcean' provider
2) Subsequently use the 'Docker' provider to spin up my containers
Any suggestions? Do I need to write an orchestrating script that wraps Terraform?
Terraform's current design struggles with creating "multi-layer" architectures in a single configuration, due to the need to pass dynamic settings from one provider to another:
resource "digitalocean_droplet" "example" {
# (settings for a machine running docker)
}
provider "docker" {
host = "tcp://${digitalocean_droplet.example.ipv4_address_private}:2376/"
}
As you saw in the documentation, passing dynamic values into provider configuration doesn't fully work. It does actually partially work if you use it with care, so one way to get this done is to use a config like the above and then solve the "chicken-and-egg" problem by forcing Terraform to create the droplet first:
$ terraform plan -out=tfplan -target=digitalocean_droplet.example
The above will create a plan that only deals with the droplet and any of its dependencies, ignoring the docker resources. Once the Docker droplet is up and running, you can then re-run Terraform as normal to complete the setup, which should then work as expected because the Droplet's ipv4_address_private attribute will then be known. As long as the droplet is never replaced, Terraform can be used as normal after this.
Using -target is fiddly, and so the current recommendation is to split such systems up into multiple configurations, with one for each conceptual "layer". This does, however, require initializing two separate working directories, which you indicated in your question that you didn't want to do. This -target trick allows you to get it done within a single configuration, at the expense of an unconventional workflow to get it initially bootstrapped.
Maybe you can use a provider instance within your resources/module to set up various resources with various providers.
https://www.terraform.io/docs/configuration/providers.html#multiple-provider-instances
The doc talks about multiple instances of same provider but I believe the same should be doable with distinct providers as well.
A little bit late...
Well, got the same Problem. My workaround is to create modules.
First you need a module for your docker Provider with an ip variable:
# File: ./docker/main.tf
variable "ip" {}
provider "docker" {
host = "tcp://${var.ip}:2375/"
}
resource "docker_container" "www" {
provider = "docker"
name = "www"
}
Next one is to load that modul in your root configuration:
# File: .main.tf
module "docker01" {
source = "./docker"
ip = "192.169.10.12"
}
module "docker02" {
source = "./docker"
ip = "192.169.10.12"
}
True, you will create on every node the same container, but in my case that's what i wanted. I currently haven't found a way to configure the hosts with an individual configuration. Maybe nested modules, but that didn't work in the first tries.

Resources