前言

本文以Terraform Azure微软云为实践案例

更新历史

2021年02月26日 - 初稿

阅读原文 - https://wsgzao.github.io/post/terraform-azure/


学习路径

Terraform Get Started - Azure

Terraform on Azure documentation

Azure on Microsoft Learn

Provision an AKS Cluster learn guide

Getting started with Terraform and Kubernetes on Azure AKS

Azure Provider

The Azure Provider can be used to configure infrastructure in Microsoft Azure using the Azure Resource Manager API’s. Documentation regarding the Data Sources and Resources supported by the Azure Provider can be found in the navigation to the left.

Interested in the provider’s latest features, or want to make sure you’re up to date? Check out the changelog for version information and release notes.

Azure Terraform相关API都可以通过官网查询,注意版本

https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs

如果遇到描述不清楚的细节建议回头阅读Azure官方文档,以下链接优先提供英文版,中文翻译不及时,有需要可以替换en-uszh-cn

https://docs.microsoft.com/en-us/azure/

https://docs.microsoft.com/zh-cn/azure/

由世纪互联运营的Microsoft Azure

理解Azure RBAC

Azure role-based access control (Azure RBAC) is a system that provides fine-grained access management of Azure resources. Using Azure RBAC, you can segregate duties within your team and grant only the amount of access to users that they need to perform their jobs.

https://docs.microsoft.com/en-us/azure/role-based-access-control/

基于 Azure 角色的访问控制 (Azure RBAC) 是一个系统,它为 Azure 资源提供精细的访问管理。 使用 Azure RBAC,可以在团队中实现职责分离,并且可以仅向用户授予执行作业所需的访问权限。

https://docs.microsoft.com/zh-cn/azure/role-based-access-control/

Azure登录验证方式

Terraform supports a number of different methods for authenticating to Azure:

We recommend using either a Service Principal or Managed Service Identity when running Terraform non-interactively (such as when running Terraform in a CI server) - and authenticating using the Azure CLI when running Terraform locally.

Creating a Service Principal in the Azure Portal

There are three tasks necessary to create a Service Principal using the Azure Portal:

  1. Create an Application in Azure Active Directory, which will create an associated Service Principal
  2. Generating a Client Secret for the Azure Active Directory Application, which you’ll to authenticate
  3. Grant the Service Principal access to manage resources in your Azure subscriptions

How to: Use the portal to create an Azure AD application and service principal that can access resources

如果各位没有看明白英文描述和各字段值的获取,微软官方也有中文翻译

如何使用门户创建可访问资源的 Azure AD 应用程序和服务主体

说明一下:

  • subscription_id:你的Azure订阅ID
  • client_id:创建Service Principal后的Application (client) ID
  • client_secret:创建Service Principal后,创建application secret
  • tenant_id:创建Service Principal后,application的Directory (tenant) ID

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# create azureEnv.sh (can skip)
vim azureEnv.sh

#!/bin/sh
echo "Setting environment variables for Terraform"
export ARM_SUBSCRIPTION_ID=your_subscription_id
export ARM_CLIENT_ID=your_appId
export ARM_CLIENT_SECRET=your_password
export ARM_TENANT_ID=your_tenant_id
# Not needed for public, required for usgovernment, german, china
export ARM_ENVIRONMENT=public

# source azureEnv.sh
. azureEnv.sh

# create provider.tf
vim provider.tf

# Configure the Azure provider
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = ">= 2.26"
}
}
}

provider "azurerm" {
features {}
# Not needed for public, required for usgovernment, german, china
# environment = "china"
subscription_id = "00000000-0000-0000-0000-000000000000"
client_id = "00000000-0000-0000-0000-000000000000"
client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
tenant_id = "00000000-0000-0000-0000-000000000000"
}

# create main.tf

resource "azurerm_resource_group" "tfrg" {
name = "ResourceGroup"
location = "eastasia"

tags = {
environment = "demo"
}
}

# terraform test
terraform plan
terraform apply

这是Azure官方文档给的一个案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# We strongly recommend using the required_providers block to set the
# Azure Provider source and version being used
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "=2.46.0"
}
}
}

# Configure the Microsoft Azure Provider
provider "azurerm" {
features {}

# More information on the authentication methods supported by
# the AzureRM Provider can be found here:
# https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs

# subscription_id = "..."
# client_id = "..."
# client_secret = "..."
# tenant_id = "..."
}

# Create a resource group
resource "azurerm_resource_group" "example" {
name = "production-resources"
location = "West US"
}

# Create a virtual network in the production-resources resource group
resource "azurerm_virtual_network" "test" {
name = "production-network"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
address_space = ["10.0.0.0/16"]
}

安装Azure CLI

Install the Azure CLI

https://docs.microsoft.com/en-us/cli/azure/install-azure-cli

以下操作均以macOS为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# Install
# brew update && brew install azure-cli
brew install azure-cli
az login

# Update
az upgrade
brew update && brew upgrade azure-cli

# Uninstall
brew uninstall azure-cli

# az command


/\
/ \ _____ _ _ ___ _
/ /\ \ |_ / | | | \'__/ _\
/ ____ \ / /| |_| | | | __/
/_/ \_\/___|\__,_|_| \___|


Welcome to the cool new Azure CLI!

Use `az --version` to display the current version.
Here are the base commands:

account : Manage Azure subscription information.
acr : Manage private registries with Azure Container Registries.
ad : Manage Azure Active Directory Graph entities needed for Role Based Access
Control.
advisor : Manage Azure Advisor.
aks : Manage Azure Kubernetes Services.
ams : Manage Azure Media Services resources.
apim : Manage Azure API Management services.
appconfig : Manage App Configurations.
appservice : Manage App Service plans.
aro : Manage Azure Red Hat OpenShift clusters.
backup : Manage Azure Backups.
batch : Manage Azure Batch.
billing : Manage Azure Billing.
bot : Manage Microsoft Azure Bot Service.
cache : Commands to manage CLI objects cached using the `--defer` argument.
cdn : Manage Azure Content Delivery Networks (CDNs).
cloud : Manage registered Azure clouds.
cognitiveservices : Manage Azure Cognitive Services accounts.
config : Manage Azure CLI configuration.
configure : Manage Azure CLI configuration. This command is interactive.
consumption : Manage consumption of Azure resources.
container : Manage Azure Container Instances.
cosmosdb : Manage Azure Cosmos DB database accounts.
databoxedge : Support data box edge device and management.
deployment : Manage Azure Resource Manager template deployment at subscription scope.
deployment-scripts : Manage deployment scripts at subscription or resource group scope.
deploymentmanager : Create and manage rollouts for your service.
disk : Manage Azure Managed Disks.
disk-access : Manage disk access resources.
disk-encryption-set : Disk Encryption Set resource.
dla : Manage Data Lake Analytics accounts, jobs, and catalogs.
dls : Manage Data Lake Store accounts and filesystems.
dms : Manage Azure Data Migration Service (DMS) instances.
eventgrid : Manage Azure Event Grid topics, domains, domain topics, system topics
partner topics, event subscriptions, system topic event subscriptions and
partner topic event subscriptions.
eventhubs : Manage Azure Event Hubs namespaces, eventhubs, consumergroups and geo
recovery configurations - Alias.
extension : Manage and update CLI extensions.
feature : Manage resource provider features.
feedback : Send feedback to the Azure CLI Team!
find : I'm an AI robot, my advice is based on our Azure documentation as well as
the usage patterns of Azure CLI and Azure ARM users. Using me improves
Azure products and documentation.
functionapp : Manage function apps. To install the Azure Functions Core tools see
https://github.com/Azure/azure-functions-core-tools.
group : Manage resource groups and template deployments.
hdinsight : Manage HDInsight resources.
identity : Managed Service Identities.
image : Manage custom virtual machine images.
interactive : Start interactive mode. Installs the Interactive extension if not
installed already.
iot : Manage Internet of Things (IoT) assets.
keyvault : Manage KeyVault keys, secrets, and certificates.
kusto : Manage Azure Kusto resources.
lab : Manage Azure DevTest Labs.
local-context : Manage Local Context.
lock : Manage Azure locks.
login : Log in to Azure.
logout : Log out to remove access to Azure subscriptions.
managedapp : Manage template solutions provided and maintained by Independent Software
Vendors (ISVs).
managedservices : Manage the registration assignments and definitions in Azure.
maps : Manage Azure Maps.
mariadb : Manage Azure Database for MariaDB servers.
monitor : Manage the Azure Monitor Service.
mysql : Manage Azure Database for MySQL servers.
netappfiles : Manage Azure NetApp Files (ANF) Resources.
network : Manage Azure Network resources.
openshift : Manage Azure Red Hat OpenShift 3.11 clusters.
policy : Manage resource policies.
postgres : Manage Azure Database for PostgreSQL servers.
ppg : Manage Proximity Placement Groups.
provider : Manage resource providers.
redis : Manage dedicated Redis caches for your Azure applications.
relay : Manage Azure Relay Service namespaces, WCF relays, hybrid connections, and
rules.
reservations : Manage Azure Reservations.
resource : Manage Azure resources.
rest : Invoke a custom request.
role : Manage user roles for access control with Azure Active Directory and
service principals.
search : Manage Azure Search services, admin keys and query keys.
security : Manage your security posture with Azure Security Center.
servicebus : Manage Azure Service Bus namespaces, queues, topics, subscriptions, rules
and geo-disaster recovery configuration alias.
sf : Manage and administer Azure Service Fabric clusters.
sig : Manage shared image gallery.
signalr : Manage Azure SignalR Service.
snapshot : Manage point-in-time copies of managed disks, native blobs, or other
snapshots.
sql : Manage Azure SQL Databases and Data Warehouses.
sshkey : Manage ssh public key with vm.
staticwebapp : Manage static apps.
storage : Manage Azure Cloud Storage resources.
synapse : Manage and operate Synapse Workspace, Spark Pool, SQL Pool.
tag : Tag Management on a resource.
ts : Manage template specs at subscription or resource group scope.
upgrade : Upgrade Azure CLI and extensions.
version : Show the versions of Azure CLI modules and extensions in JSON format by
default or format configured by --output.
vm : Manage Linux or Windows virtual machines.
vmss : Manage groupings of virtual machines in an Azure Virtual Machine Scale Set
(VMSS).
webapp : Manage web apps.

Popular articles using the Azure CLI

Terraform on Azure

Configure Terraform using Azure Cloud Shell

使用 Azure Cloud Shell 配置 Terraform

Create a Linux VM with infrastructure in Azure using Terraform

使用 Terraform 在 Azure 中创建带有基础结构的 Linux VM

Terraform Azure常见问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
az login
Port '8400' is taken with error '[Errno 8] nodename nor servname provided, or not known'. Trying with the next one
Port '8401' is taken with error '[Errno 8] nodename nor servname provided, or not known'. Trying with the next one
Port '8402' is taken with error '[Errno 8] nodename nor servname provided, or not known'. Trying with the next one
Port '8403' is taken with error '[Errno 8] nodename nor servname provided, or not known'. Trying with the next one
Port '8404' is taken with error '[Errno 8] nodename nor servname provided, or not known'. Trying with the next one
Port '8405' is taken with error '[Errno 8] nodename nor servname provided, or not known'. Trying with the next one
Error: can't reserve a port for authentication reply url
Login failed

# macOS中添加localhost可解决
sudo vi /etc/hosts
127.0.0.1 localhost


Azure Best Practices

A collection of all the best practice references that I can find.

Governance

Identity and Access Management

DevOps

Security

Networking

Storage

Compute

AppServices

参考文章

Azure 文档

Azure Provider

terraform-provider-azurerm

Azure Terraform(二)语法详解

文章目录
  1. 1. 前言
  2. 2. 更新历史
  3. 3. 学习路径
  4. 4. Azure Provider
  5. 5. 理解Azure RBAC
    1. 5.1. Azure登录验证方式
    2. 5.2. 安装Azure CLI
  6. 6. Terraform on Azure
  7. 7. Terraform Azure常见问题
  8. 8. Azure Best Practices
    1. 8.1. Governance
    2. 8.2. Identity and Access Management
    3. 8.3. DevOps
    4. 8.4. Security
    5. 8.5. Networking
    6. 8.6. Storage
    7. 8.7. Compute
    8. 8.8. AppServices
  9. 9. 参考文章