Create Azure Automation Start/Stop solution through Terraform - azure

I'm trying to set up machines to be automatically start/stopped using the newish Azure Automation add-in (https://learn.microsoft.com/en-us/azure/automation/automation-solution-vm-management) with this being set up by Terraform.
I can create the automation account but I don't know how to create the start-stop functionality, can someone help fill in the blanks?

the AzureRM provider can manage aspects of runbooks. If you have a look at the documentation here. Using azurerm_automation_runbook and azurerm_automation_schedule you can create and schedule runbooks. The Microsoft solution requires parameters on the runbooks, I don't see any attributes in the provider to add parameters so this may not be possible.

You can pass the required parameter in this resource provider "azurerm_automation_job_schedule". Please note the Parameters attribute in the below code this is how we can pass the required parameter. You can refer this link for more details. https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/automation_job_schedule
resource "azurerm_automation_job_schedule" "startvm_sched" {
resource_group_name = "IndraTestRG"
automation_account_name = "testautomation"
schedule_name = azurerm_automation_schedule.scheduledstartvm.name
runbook_name = azurerm_automation_runbook.startstopvmrunbook.name
parameters = {
action = "Start"
}
depends_on = [azurerm_automation_schedule.scheduledstartvm]
}
Below is the complete code for VM Start/Stop job schedule resource provider "azurerm_automation_schedule" and "azurerm_automation_job_schedule"
resource "azurerm_automation_schedule" "scheduledstartvm" {
name = "StartVM"
resource_group_name = "IndraTestRG"
automation_account_name = "testautomation"
frequency = "Day"
interval = 1
timezone = "America/Chicago"
start_time = "2021-09-20T13:00:00Z"
description = "Run every day"
}
resource "azurerm_automation_job_schedule" "startvm_sched" {
resource_group_name = "IndraTestRG"
automation_account_name = "testautomation"
schedule_name = azurerm_automation_schedule.scheduledstartvm.name
runbook_name = azurerm_automation_runbook.startstopvmrunbook.name
parameters = {
action = "Start"
}
depends_on = [azurerm_automation_schedule.scheduledstartvm]
}
resource "azurerm_automation_schedule" "scheduledstopvm" {
name = "StopVM"
resource_group_name = "IndraTestRG"
automation_account_name = "testautomation"
frequency = "Day"
interval = 1
timezone = "America/Chicago"
start_time = "2021-09-20T10:30:00Z"
description = "Run every day"
}
resource "azurerm_automation_job_schedule" "stopvm_sched" {
resource_group_name = "IndraTestRG"
automation_account_name = "testautomation"
schedule_name = azurerm_automation_schedule.scheduledstopvm.name
runbook_name = azurerm_automation_runbook.startstopvmrunbook.name
parameters = {
action = "Stop"
}
depends_on = [azurerm_automation_schedule.scheduledstopvm]
}

Related

Terraform deployment for 'Work pace based Application Insight' on Azure

I have been trying to figure out a way to prepare a terraform template for my app service/az function where I can connect it to application Insight while creating them through Terraform. Well the it worked, BUT the application Insight shows
Migrate this resource to Workspace-based Application Insights to gain support for all of the capabilities of Log Analytics, including Customer-Managed Keys and Commitment Tiers. Click here to learn more and migrate in a few clicks.
How do I acheive it from terraform? As from the documentation page of terraform there is no mention of such setup. Appreciate you help on this.
Here is the terraform code for az-function
resource "azurerm_linux_function_app" "t_funcapp" {
name = "t-function-app"
location = local.resource_location
resource_group_name = local.resource_group_name
service_plan_id = azurerm_service_plan.t_app_service_plan.id
storage_account_name = azurerm_storage_account.t_funcstorage.name
storage_account_access_key = azurerm_storage_account.t_funcstorage.primary_access_key
site_config {
application_stack {
java_version = "11"
}
remote_debugging_enabled = false
ftps_state = "AllAllowed"
}
app_settings = {
APPINSIGHTS_INSTRUMENTATIONKEY = "${azurerm_application_insights.t_appinsights.instrumentation_key}"
}
depends_on = [
azurerm_resource_group.t_rg,
azurerm_service_plan.t_app_service_plan,
azurerm_storage_account.t_funcstorage,
azurerm_application_insights.t_appinsights
]
}
Here is the terraform code for app insight
resource "azurerm_application_insights" "t_appinsights" {
name = "t-appinsights"
location = local.resource_location
resource_group_name = local.resource_group_name
application_type = "web"
depends_on = [
azurerm_log_analytics_workspace.t_workspace
]
}
output "instrumentation_key" {
value = azurerm_application_insights.t_appinsights.instrumentation_key
}
output "app_id" {
value = azurerm_application_insights.t_appinsights.app_id
}
You must create a Log Analytics Workspace and add it to your Application Insights.
For example
resource "azurerm_log_analytics_workspace" "example" {
name = "workspace-test"
location = local.resource_location
resource_group_name = local.resource_group_name
sku = "PerGB2018"
retention_in_days = 30
}
resource "azurerm_application_insights" "t_appinsights" {
name = "t-appinsights"
location = local.resource_location
resource_group_name = local.resource_group_name
workspace_id = azurerm_log_analytics_workspace.example.id
application_type = "web"
}
output "instrumentation_key" {
value = azurerm_application_insights.t_appinsights.instrumentation_key
}
output "app_id" {
value = azurerm_application_insights.t_appinsights.app_id
}
Hope this helps!

Update exsiting Azure App Service in Terraform

I would like to update my exsiting Azure App Service in Terraform by adding a Backup to this App Service.
For now it looks like this:
data "azurerm_app_service_plan" "example" {
name = "MyUniqueServicePlan"
resource_group_name = "example-resources"
}
resource "azurerm_app_service" "example" {
name = "MyUniqueWebAppName"
location = "West Europe"
resource_group_name = "example-resources"
app_service_plan_id = data.azurerm_app_service_plan.example.id
connection_string {
name = "myConectionString"
type = "SQLServer"
value = "Server=tcp:mysqlservername123.database.windows.net,1433;Initial Catalog=MyDatabaseName;Persist Security Info=False;User ID=xxx;Password=xxxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
}
backup {
name = "MyBackupName"
enabled = true
storage_account_url = "https://storageaccountnameqwetih.blob.core.windows.net/mycontainer?sp=r&st=2022-08-31T09:49:17Z&se=2022-08-31T17:49:17Z&spr=https&sv=2021-06-08&sr=c&sig=2JwQ%xx%2B%2xxB5xxxxFZxxVyAadjxxV8%3D"
schedule {
frequency_interval = 30
frequency_unit = "Day"
keep_at_least_one_backup = true
retention_period_in_days = 10
start_time = "2022-08-31T07:11:56.52Z"
}
}
}
But when I run it i got a error A resource with the ID ........ /MyUniqueWebAppName" already exists - to be managed via Terraform this resource needs to be imported into the State.
How in terraform can I point to an existing Azure APP Service and add a backup with the same schedule as I did in my template?
Before you can modify your existing resources with TF, you must import into the terraform state. For this you use import command.
data "azurerm_resource_group" "example" {
name = "<give rg name existing one>"
}
data "azurerm_app_service_plan" "example" {
name = "MyUniqueServicePlan"
resource_group_name = data.azurerm_resource_group.example.name
}
data "azurerm_app_service" "example" {
name = "MyUniqueWebAppName"
location = data.azurerm_resource_group.example.location
resource_group_name = data.azurerm_resource_group.example.name
app_service_plan_id = data.azurerm_app_service_plan.example.id
connection_string {
name = "myConectionString"
type = "SQLServer"
value = "Server=tcp:mysqlservername123.database.windows.net,1433;Initial Catalog=MyDatabaseName;Persist Security Info=False;User ID=xxx;Password=xxxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
}
backup {
name = "MyBackupName"
enabled = true
storage_account_url = "https://storageaccountnameqwetih.blob.core.windows.net/mycontainer?sp=r&st=2022-08-31T09:49:17Z&se=2022-08-31T17:49:17Z&spr=https&sv=2021-06-08&sr=c&sig=2JwQ%xx%2B%2xxB5xxxxFZxxVyAadjxxV8%3D"
schedule {
frequency_interval = 30
frequency_unit = "Day"
keep_at_least_one_backup = true
retention_period_in_days = 10
start_time = "2022-08-31T07:11:56.52Z"
}
}
}
No need to use import command , use this code for your reference
just give rg name existing one in resources group block

Terraform azurerm_api_management_api bumping revision does not apply all required changes

We are managing our API Management platform in Azure with terraform. Sometimes we need to bump the revision, and when we do that there are several issues:
The API that gets bumped is recreated (expected)
The recreated API is lost from all products it belonged to
The recreated API does not get any policies applied
So when the revision is bumped, the pipeline has to be run twice:
The API is recreated
The API is added to the product again and gets its policy applied
This is how the template looks like:
# Fetch existing API management instance
data "azurerm_api_management" "storemanager_api_management" {
name = local.api_management_name
resource_group_name = local.api_management_resource_group_name
}
# Create the API
resource "azurerm_api_management_api" "api" {
api_management_name = data.azurerm_api_management.storemanager_api_management.name
resource_group_name = local.api_management_resource_group_name
name = "api"
path = "api"
display_name = "api 1"
protocols = ["https"]
revision = var.api_revision
subscription_required = true
subscription_key_parameter_names {
header = local.api_subscription_key_name
query = local.api_subscription_key_name
}
import {
content_format = "swagger-link-json"
content_value = format("https://%s.blob.core.windows.net/%s/%s/%s",
data.azurerm_storage_account.storage_account.name,
data.azurerm_storage_container.open_api_definition_storage_container.name,
var.api_api_version,
local.api_api_definition_name
)
}
}
# Create the product
resource "azurerm_api_management_product" "product" {
api_management_name = data.azurerm_api_management.storemanager_api_management.name
resource_group_name = local.api_management_resource_group_name
product_id = "product"
display_name = "Product"
description = "Collection of APIs"
subscription_required = true
subscriptions_limit = 1
approval_required = true
published = true
}
# Associate the API with the product
resource "azurerm_api_management_product_api" "product_api" {
api_management_name = data.azurerm_api_management.storemanager_api_management.name
resource_group_name = local.api_management_resource_group_name
product_id = azurerm_api_management_product.product.product_id
api_name = azurerm_api_management_api.api.name
}
# Apply policy to the API
resource "azurerm_api_management_api_policy" "policy" {
api_name = azurerm_api_management_api.api.name
api_management_name = data.azurerm_api_management.storemanager_api_management.name
resource_group_name = local.api_management_resource_group_name
xml_content = templatefile("./policy.tmpl", { x_functions_key_value = var.function_key, backend_name = azurerm_api_management_backend.generic_function_app_backend.name })
}
Is this a bug, or am I not using terraform correctly? How do I re-add the recreated API to the product and get its policy applied in one run of the pipeline?

Azure APIM - Terraform - Use same AAD group for multiple products errors out

Getting an error message when using the same Azure AD group for two different groups.
The error I get says the group is already in the TF state and can't be used again.
Hopefully someone has seen this error before.
dev = {
product1 = {
product_name = "Product-1"
approval_required = true
published = true
subscriptions_limit = "2"
aad_group_obj_id = "00000000-0000-0000-0000-000000000000"
aad_group_name = "AG-Azure-Sample-Group"
product_policy = "../policy-samples/base-policy.xml"
}
product2 = {
product_name = "Product-2"
approval_required = true
published = true
subscriptions_limit = "2"
aad_group_obj_id = "00000000-0000-0000-0000-000000000000"
aad_group_name = "AG-Azure-Sample-Group"
product_policy = "../policy-samples/base-policy.xml"
}
}
# ========================================================================
# Product for BU APIs
resource "azurerm_api_management_product" "custom_product" {
product_id = var.product_name
api_management_name = var.api_management_name
resource_group_name = var.resource_group_name
display_name = replace(var.product_name, "-", " ")
# Require subscription keys for API access
subscription_required = true
approval_required = var.approval_required
published = var.published
subscriptions_limit = var.subscriptions_limit
}
# Relate group to a product, for each is if we want to use developer or guest built in groups
resource "azurerm_api_management_product_group" "assignments" {
for_each = toset([azurerm_api_management_group.external_group.name])
product_id = azurerm_api_management_product.custom_product.product_id
group_name = each.key
api_management_name = var.api_management_name
resource_group_name = var.resource_group_name
}
# Create default policy for Product
resource "azurerm_api_management_product_policy" "apim-product-policy" {
product_id = azurerm_api_management_product.custom_product.product_id
api_management_name = var.api_management_name
resource_group_name = var.resource_group_name
xml_content = file(var.product_policy_file_path)
}
Solved the problem by separating the group creation from the assignment. Problem was that the module creating the group was executed every time the group was assigned to the product. Now I have a separate map which contains the groups to be added to the API and on the assignment module I pull in the group via a data block segment. Works like a charm.

Automate the start/stop VMs during off-hours in Azure using terraform

I'm trying to automate the start/stop VMs during off-hours in Azure using Terraform. This is the way of automating it in Azure portal https://learn.microsoft.com/en-us/azure/automation/automation-solution-vm-management I have done it once in azure portal but I want to do the same using terraform.
I've searched days to find out how to do this. I've found the same question asked by someone else before Create Azure Automation Start/Stop solution through Terraform but there was only one answer to that which is it's not possible since the Microsoft solution requires parameters on the runbooks, and there isn't any attributes in the provider to add parameters. But I'm not quite convinced with the answer.
I'm newish in Terraform and I know some resources like azurerm_automation_job_schedule and azurerm_automation_runbook must be used, but I couldn't figure out the whole module to do this. Has anyone done anything like this before?
I think the post is a bit old now but I am responding if this is going to help someone trying to figure out the solution to pass parameter for the runbook. You can pass the required parameter in this resource provider "azurerm_automation_job_schedule". Please note the Parameters attribute this is how we can pass the required parameter. You can refer this link for more details.
https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/automation_job_schedule
resource "azurerm_automation_job_schedule" "startvm_sched" {
resource_group_name = "IndraTestRG"
automation_account_name = "testautomation"
schedule_name = azurerm_automation_schedule.scheduledstartvm.name
runbook_name = azurerm_automation_runbook.startstopvmrunbook.name
parameters = {
action = "Start"
}
depends_on = [azurerm_automation_schedule.scheduledstartvm]
}
Below is the complete code for VM Start/Stop job schedule resource provider "azurerm_automation_schedule" and "azurerm_automation_job_schedule"
resource "azurerm_automation_schedule" "scheduledstartvm" {
name = "StartVM"
resource_group_name = "IndraTestRG"
automation_account_name = "testautomation"
frequency = "Day"
interval = 1
timezone = "America/Chicago"
start_time = "2021-09-20T13:00:00Z"
description = "Run every day"
}
resource "azurerm_automation_job_schedule" "startvm_sched" {
resource_group_name = "IndraTestRG"
automation_account_name = "testautomation"
schedule_name = azurerm_automation_schedule.scheduledstartvm.name
runbook_name = azurerm_automation_runbook.startstopvmrunbook.name
parameters = {
action = "Start"
}
depends_on = [azurerm_automation_schedule.scheduledstartvm]
}
resource "azurerm_automation_schedule" "scheduledstopvm" {
name = "StopVM"
resource_group_name = "IndraTestRG"
automation_account_name = "testautomation"
frequency = "Day"
interval = 1
timezone = "America/Chicago"
start_time = "2021-09-20T10:30:00Z"
description = "Run every day"
}
resource "azurerm_automation_job_schedule" "stopvm_sched" {
resource_group_name = "IndraTestRG"
automation_account_name = "testautomation"
schedule_name = azurerm_automation_schedule.scheduledstopvm.name
runbook_name = azurerm_automation_runbook.startstopvmrunbook.name
parameters = {
action = "Stop"
}
depends_on = [azurerm_automation_schedule.scheduledstopvm]
}

Resources