How to run custom scripts post terraform vmware vm deployment? - terraform

I have been researching on this topic for over a week now and couldn't find any good solution neither on terraform documentation site nor on the web.
Main issue trying to solve right now is: how to run a custom powershell script at the end of terraform vmware basic windows server 2016 vm build.
Tried following methods:
remote-exec - fail
provisioners inside vm resource definition - fail
null resource - Error: timeout - last error: http response error: 401 - invalid content type
Here's my null resource definition right below vm resource build within the same main.tf file
resource "null_resource" "vm" {
triggers = {
public_ip = <host ip address>
}
connection {
type = "winrm"
host = <host ip address>
user = <username>
password = <password>
agent = false
}
provisioner "file" {
source = "userdata.ps1"
destination = "C:/Windows"
}
provisioner "remote-exec" {
inline = [
"powershell.exe -ExecutionPolicy Bypass -File C:/Windows/userdata.ps1"
]
}
}
Please suggest what are the recommended practices and your working solution

Related

'terraform init' returns 404 'Resource Group not found' when it does exist

Since adding backend "azurerm" to my Terraform main.tf file it's now returning a 404 on the resource group created to maintain the state file.
I'm at a bit of a loss to explain why, the session is logged in to the correct tenant and subscription using Connect-AzAccount and Set-AzContext methods in the Az PowerShell module.
Here's my setup:
main.tf
## Terraform Configuration
terraform {
# Azure Remote State
backend "azurerm" {
resource_group_name = "abc-uat-tfstate"
storage_account_name = "abcuattfstate"
container_name = "tfstate"
key = "myapp.uat.tfstate"
}
# Provider Dependencies
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "~> 3.0.0"
}
}
}
## Provider Configurations
# Azure
provider "azurerm" {
subscription_id = var.subscriptionId
features {}
}
...
When I run terraform init on this main.tf file I receive the following error:
However note, I can immediately run Get-AzResourceGroup and it returns the group as I see it in Azure Portal.
Until I added the backend it was creating resources correctly so I'm thinking this is a simple configuration issue but after reviewing all the docs don't see what I've got wrong.
Ok, operator error as I suspected.
Running az login --tenant '...' and then az account set --subscrption '...' resolved the problem. terraform init now works correctly.
I should have thought about this earlier.

I want to create 2 azure vm and install jenkins and Sonarqube using terraform does anyone know how to do that?

I have to deploy dot net core and React application on those one of those virtual machines
You can create the infrastructure using Terraform.
Use Ansible to configure Jenkins and Sonarqube to have a cleaner approach
refer below Code Snippet
provisioner "remote-exec" {
inline = ["sudo apt -y install python"]
connection {
type = "ssh"
user = "ubuntu"
private_key = "${file(var.ssh_key_private)}"
}
}
provisioner "local-exec" {
command = "ansible-playbook -u ubuntu -i '${self.public_ip},' --private-key ${var.ssh_key_private} provision.yml"
}
Second Way would be to create a shell script and execute it using Terraform
provisioner "local-exec" {
command = "/bin/bash provision.sh"
}

Unable to create azura resources using terraform despite being a subscription owner

I cannot create any resource in azure cloud using terraform.
WSL2 - Ubuntu:
Ubuntu 20.04.3 LTS
Terraform version:
Terraform v1.1.5
AZ CLI version:
"azure-cli": "2.33.0"
"azure-cli-core": "2.33.0"
"azure-cli-telemetry": "1.0.6"
At the beggining I login to azure subscription through az login. I have only one available subscription on this account and I am owner.
Then I create "main.tf" file same as here : https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs#example-usage
After "terraform init" i do "terraform plan" but i recive that error:
Error: Unable to list provider registration status, it is possible that this is due to invalid credentials or the service principal does not have permission to use the Resource Manager API, Azure error: resources.ProvidersClient#List: Failure sending request: StatusCode=0 -- Original Error: Get "https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/providers?api-version=2016-02-01": dial tcp: lookup management.azure.com on 000.00.000.0:00: cannot unmarshal DNS message
with provider["registry.terraform.io/hashicorp/azurerm"],
on main.tf line 10, in provider "azurerm":
10: provider "azurerm" {
Also i go through this way: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/guides/service_principal_client_secret
My app has contributor/owner priviliges at the subscription level.
Then adding this configuration :
provider "azurerm" {
features {}
subscription_id = "00000000-0000-0000-0000-000000000000"
client_id = "00000000-0000-0000-0000-000000000000"
client_secret = var.client_secret
tenant_id = "00000000-0000-0000-0000-000000000000"
}
Finally I get the same error. Do you have any ideas?
sudo vim /etc/resolv.conf
and change nameserver value to 8.8.8.8
It should work, but every time you reboot you should do this action or write a script to automate it!

Azure Recovery Services Vault with Terraform local provisioner

Terraform doesn't provide options to change the Azure recovery Services Vault to use LocallyRedundant storage replication type. So I decided to use the PowerShell module to set this after the resource is provisioned. The command seems to be correct and works when it's manually invoked but doesn't when it's put in the provisioner. Any thoughts?
Terraform Version : 0.15
Azurerm Version : 2.40.0
resource "azurerm_recovery_services_vault" "RSV"{
name = "RSV"
location = "eastus"
resource_group_name = "RGTEST"
sku = "Standard"
provisioner "local-exec" {
command = "Get-AzRecoveryServicesVault -Name ${azurerm_recovery_services_vault.RSV.name} | Set-AzRecoveryServicesBackupProperty -BackupStorageRedundancy LocallyRedundant"
interpreter = ["powershell", "-Command"]
}
}
The PowerShell scripts rely on the resource "azurerm_recovery_services_vault" that is fully created. In this case, if you include the local-exec Provisioner in a null_resource, run terraform init and terraform apply again, it works.
Note that even though the resource will be fully created when the
provisioner is run, there is no guarantee that it will be in an
operable state
resource "null_resource" "script" {
provisioner "local-exec" {
command = "Get-AzRecoveryServicesVault -Name ${azurerm_recovery_services_vault.RSV.name} | Set-AzRecoveryServicesBackupProperty -BackupStorageRedundancy LocallyRedundant"
interpreter = ["powershell", "-Command"]
}
}

Terraform and Azure: Unable to provision Storage Account

I am trying to provision a storage account but running it results in error:
Error: Error reading static website for AzureRM Storage Account "sa12345461234512name":
accounts.Client#GetServiceProperties:
Failure responding to request: StatusCode=403 -- Original Error: autorest/azure:
Service returned an error. Status=403 Code="AuthorizationPermissionMismatch"
Message="This request is not authorized to perform this operation using this permission.\n
RequestId:05930d46-301e-00ac-6d72-f021f0000000\n
Time:2020-03-02T09:09:44.9417598Z"
Running OS Windows 10 Pro.
Steps to replicate (in Powershell with Azure CLI installed)
az login
mkdir dummyFolder
cd dummyFolder
create config.tf
terraform init
terraform plan
terraform apply -auto-approve
Config.tf contents
# Configure the Azure Provider
provider "azurerm" {
version = "=2.0.0"
features {}
}
resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "Australia East"
}
resource "azurerm_storage_account" "example" {
name = "sa12345461234512name"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
account_tier = "Standard"
account_replication_type = "LRS"
tags = {
environment = "staging"
}
}
Not sure what i am missing, all other resources work fine, just the storage account.
This is a bug in the azure provider, see: https://github.com/terraform-providers/terraform-provider-azurerm/issues/5869
Update your provider; it doesn't seem to be related to the terraform version.
From:
# Configure the Azure Provider
provider "azurerm" {
# whilst the `version` attribute is optional, we recommend pinning to a given version of the Provider
version = "=2.0.0"
features {}
}
To:
provider "azurerm" {
version = "~> 2.1.0"
features {}
}
Just to add to this since none of above worked. In my case it first didn't work, then next day worked just to not work again in the evening... Not changing versions or anything, was same computer.
It turned out that my time settings on my Ubuntu running in Windows was skewed. Just simply running a sudo ntpdate time.nist.gov to update time solved the problem.
Found the issue. Its got to do with Terraform.
Just checked for updates and notices 0.12.21 is out (I was runnning 0.12.20).
Seems like if running AzureARM 2.0.0 then really need to be min 0.12.21 to make it work.
Same problem as #tesharp experienced.
On my Ubuntu WSL2 the following command fixed the problem:
sudo hwclock -s

Resources