- Setup a Basic Terraform Configuration:
- Install Terraform on your local machine.
- Set up your Azure Service Principal for authentication.
- Create a minimal Terraform script to deploy an Azure resource (like a simple virtual machine or storage account).
- Example: You can use Terraform to create a basic Azure resource (e.g., a storage account) by defining the provider and resource in a .tf file.
- Authenticate with Azure (after Azure CLI installation)
- Before we run Terraform, make sure you’re authenticated with Azure using the Azure CLI. Open your terminal or command prompt and run:
az login- This command opens a browser window for you to authenticate your Azure account. Once you’re logged in, Terraform can interact with your Azure subscription.
- Create a Service Principal (Optional but Recommended)
- If you prefer to authenticate via a service principal (which is a more secure and common practice for automation), run:
az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/{subscriptionId}"- This will return credentials (appId, password, and tenant) that you’ll need for Terraform configuration. Keep them handy.
- Create a Terraform Configuration
- Now that you’re authenticated, you can configure your main.tf file to define the Azure infrastructure you want to deploy. Here’s a simple example that creates a resource group in Azure:
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "East US"
}- Initialize Terraform
- Navigate to the directory where your main.tf is located and run:
terraform init- This command initializes Terraform, downloading necessary plugins (like the Azure provider).
- Plan Your Deployment
- Next, you should check if your configuration is valid and see what Terraform plans to do:
terraform plan- This command gives you an overview of what Terraform will create or modify in your Azure environment based on your configuration.
- Apply the Configuration
- Once you’re satisfied with the plan, you can apply the configuration:
terraform apply- Terraform will ask for confirmation. Type yes to proceed. This will create the resource group in your Azure subscription.
- Verify Resources in Azure
- Once the terraform apply is successful, you can check your Azure portal to confirm that the resource group has been created under the specified location.
- Stop Resources: After experimenting, use Terraform to destroy the resources
terraform destroy- Again, Terraform will prompt for confirmation to ensure you’re aware of what will be destroyed.
Summary of Steps:
- Authenticate with Azure via CLI.
- Create a service principal if you want to use it for automation.
- Write your Terraform configuration to define the resources you want to deploy.
- Initialize Terraform (
terraform init). - Plan your deployment (
terraform plan). - Apply the configuration (
terraform apply). - Destroy resources when done (
terraform destroy).