Introduction
If an Azure feature or action is available within the Terraform Azure providers,
there may be a need to run a shell and use the Azure CLI as part of a Terraform run.
One way to accomplish this is to have a script that runs in a null-resource provider
with local-exec provisioner.
The caveat to using a null-resource with local-exec resource is that this will result
in a change everytime a plan is run.
Use Case
This use case requires a call the Azure CLI during a Terraform run.
Procedure
The null_resource provider has one resource, null_resource. The null_resource
resource implements the standard resource lifecycle but takes no further action.
Using the null_resource resource with a local-exec provider is a pattern for running a shell
script.
The following configuration is an example of running a bash shell script in a
local-exec provider. In this example, the shell script will install the Azure CLI. This
script is for Debian and Debian based Linux distributions like Ubuntu.
For installation steps for other platforms, please refer to:
https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-yum?view=azure-cli-latest
resource "null_resource" "install_azure_cli" {
provisioner "local-exec" {
command = <<EOH
echo "Installing AzureCLI"
apt-get update
# install requirements
apt-get install -y curl apt-transport-https lsb-release gnupg jq
# add Microsoft as a trusted source
curl -sL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/microsoft.asc.gpg > /dev/null
AZ_REPO=$(lsb_release -cs)
echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main" | sudo tee /etc/apt/sources.list.d/azure-cli.list
apt-get update
apt-get install azure-cli
EOH
interpreter = ["/bin/bash", "-c"]
}
Additional Information
Recommendations
Installing the Azure CLI is the first step. The next step would be running
the az
command to accomplish a goal. The example here is logging in,
creating a resource group.
echo "Logging in to Azure Subscription"
az login --service-principal -u app-url -p password-or-cert --tenant tenant
az account set --subscription = subscription-id
# Create a resource group.
az group create --name my-resource-group --location my-location