티스토리 뷰

Azure와 함께 하는 DevOps

12 Azure의 Terraform

zerobig-k8s 2019. 12. 30. 07:45

<참조>

https://docs.microsoft.com/ko-kr/azure/terraform/terraform-overview

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

https://docs.microsoft.com/ko-kr/azure/virtual-machines/linux/terraform-install-configure

https://docs.microsoft.com/en-us/azure/virtual-machines/linux/terraform-install-configure

 

 

 

 

 

 

그동안 우리는 ARM(Azure Resource Manage) 템플릿을 사용하여 IaC(Infra as Code)를 실현해보는 실습을 진행해왔다.

ARM 템플릿도 훌륭하지만 제작이 어려울 수 있다. 이에 대해 Terraform은 훌륭한 옵션이 될 수 있다.

Terraform을 Azure의 IaC로 사용할 수있을 뿐만 아니라 여러 클라우드 또는 On-Premises 에서 작동한다.

 

 

 

 

 

Azure의 Terraform

 

Hashicorp Terraform은 클라우드 인프라를 프로비전하고 관리하기 위한 오픈 소스 도구이다. 클라우드 리소스의 토폴로지를 설명하는 구성 파일의 인프라를 체계화한다. 이러한 리소스에는 가상 머신, 스토리지 계정 및 네트워킹 인터페이스가 포함된다. Terraform CLI는 Azure에 구성 파일을 배포하고 버전을 지정하는 간단한 메커니즘을 제공한다.

이번 자습서에서는 Terraform을 사용하여 Azure 인프라를 관리하는 이점에 대해 설명하고 Terraform을 설치하고 Azure를 사용하도록 구성해본다.

 

 

 

 

 

 

인프라 관리 자동화

Terraform의 템플릿 기반 구성 파일을 사용하면 반복 가능하고 예측 가능한 방식으로 Azure 리소스를 정의하고, 프로비전하고 구성할 수 있다. 인프라 자동화에는 다음과 같은 몇 가지 이점이 있다.

  • 인프라를 배포하고 관리하는 동안 사람의 실수 가능성을 줄인다.
  • 동일한 템플릿을 여러 번 배포하여 동일한 개발, 테스트 및 프로덕션 환경을 만든다.
  • 개발 및 테스트 환경을 요구사항 발생 시(on-demand) 만들므로 비용을 줄인다.

 

 

 

적용하기 전에 인프라 변경 내용 이해

리소스 토폴로지가 복잡해지면서 인프라 변경의 의미와 영향을 이해하는 것이 어려울 수 있다.

Terraform CLI를 통해 사용자는 애플리케이션 전에 인프라 변경 내용을 확인하고 미리 볼 수 있다. 인프라 변경 사항을 안전한 방식으로 미리 보면 다음과 같은 여러 가지 이점이 있다.

  • 제안된 변경사항과 그 영향을 팀 멤버가 신속하게 이해하기 때문에 보다 효과적으로 협업할 수 있다.
  • 의도하지 않은 변경을 개발 프로세스 초기에 파악할 수 있다.

 

 

 

여러 클라우드에 인프라 배포

Terraform은 여러 클라우드 공급자에 걸쳐 인프라를 배포하는 데 능숙하다. 이를 통해 개발자는 일관된 도구를 사용하여 각 인프라 정의를 관리할 수 있다.

 

 

 

 

 

Azure 리소스를 프로 비전 하기 위해 Terraform 설치 및 구성

 

Terraform은 간단한 템플릿 언어를 사용하여 클라우드 인프라를 정의, 미리 보기 및 배포하는 쉬운 방법을 제공한다. Azure에서 Terraform을 사용하는 방법에 대한 자세한 내용은 Terraform 허브를 참조한다.

 

 

 

Terraform 설치

여기서는 기존에 실습해왔던 환경인 Linux용 Windows 하위 시스템 기준으로 진행한다. VS Code내 bash (wsl) 터미널 창을 열어 실습을 진행한다.

Terraform을 설치하려면 운영 체제에 적합한 패키지의 최신버전에 대한 다운로드 주소를 복사하고 다음을 진행한다. 이 글을 작성하는 현재 시점의 최신버전은 0.12.18이다. Linux 환경에서의 설치 방법에 대한 전체 지침은 이 웹 페이지지를 참조한다.

zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise$ sudo apt-get update
Get:1 https://packages.microsoft.com/repos/azure-cli bionic InRelease [3965 B]
Get:2 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]
Hit:3 http://archive.ubuntu.com/ubuntu bionic InRelease
Get:4 http://archive.ubuntu.com/ubuntu bionic-updates InRelease [88.7 kB]
Get:5 http://archive.ubuntu.com/ubuntu bionic-backports InRelease [74.6 kB]
Get:6 https://packages.microsoft.com/repos/azure-cli bionic/main amd64 Packages [7578 B]
Get:7 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages [593 kB]
Get:8 http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 Packages [817 kB]
Get:9 http://security.ubuntu.com/ubuntu bionic-security/main Translation-en [194 kB]
Get:10 http://security.ubuntu.com/ubuntu bionic-security/restricted amd64 Packages [15.1 kB]
Get:11 http://security.ubuntu.com/ubuntu bionic-security/restricted Translation-en [4684 B]
Get:12 http://security.ubuntu.com/ubuntu bionic-security/universe amd64 Packages [627 kB]
Get:13 http://security.ubuntu.com/ubuntu bionic-security/universe Translation-en [210 kB]
Get:14 http://security.ubuntu.com/ubuntu bionic-security/multiverse amd64 Packages [6120 B]
Get:15 http://security.ubuntu.com/ubuntu bionic-security/multiverse Translation-en [2600 B]
Get:16 http://archive.ubuntu.com/ubuntu bionic-updates/main Translation-en [288 kB]
Get:17 http://archive.ubuntu.com/ubuntu bionic-updates/restricted amd64 Packages [24.1 kB]
Get:18 http://archive.ubuntu.com/ubuntu bionic-updates/restricted Translation-en [6620 B]
Get:19 http://archive.ubuntu.com/ubuntu bionic-updates/universe amd64 Packages [1033 kB]
Get:20 http://archive.ubuntu.com/ubuntu bionic-updates/universe Translation-en [319 kB]
Get:21 http://archive.ubuntu.com/ubuntu bionic-updates/multiverse amd64 Packages [9284 B]
Get:22 http://archive.ubuntu.com/ubuntu bionic-updates/multiverse Translation-en [4508 B]
Get:23 http://archive.ubuntu.com/ubuntu bionic-backports/universe amd64 Packages [4028 B]
Fetched 4421 kB in 17s (257 kB/s)
Reading package lists... Done
zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise$ sudo apt-get install wget unzip
Reading package lists... Done
Building dependency tree
Reading state information... Done
wget is already the newest version (1.19.4-1ubuntu2.2).
wget set to manually installed.
The following package was automatically installed and is no longer required:
  libfreetype6
Use 'sudo apt autoremove' to remove it.
Suggested packages:
  zip
The following NEW packages will be installed:
  unzip
0 upgraded, 1 newly installed, 0 to remove and 129 not upgraded.
Need to get 167 kB of archives.
After this operation, 558 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://archive.ubuntu.com/ubuntu bionic/main amd64 unzip amd64 6.0-21ubuntu1 [167 kB]
Fetched 167 kB in 2s (104 kB/s)
Selecting previously unselected package unzip.
(Reading database ... 68029 files and directories currently installed.)
Preparing to unpack .../unzip_6.0-21ubuntu1_amd64.deb ...
Unpacking unzip (6.0-21ubuntu1) ...
Processing triggers for mime-support (3.60ubuntu1) ...
Setting up unzip (6.0-21ubuntu1) ...
Processing triggers for man-db (2.8.3-2ubuntu0.1) ...
zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise$ sudo wget https://releases.hashicorp.com/terraform/0.12.18/terraform_0.12.18_linux_amd64.zip
Will not apply HSTS. The HSTS database must be a regular and non-world-writable file.
ERROR: could not open HSTS store at '/home/zerobig/.wget-hsts'. HSTS will be disabled.
--2019-12-29 09:16:05--  https://releases.hashicorp.com/terraform/0.12.18/terraform_0.12.18_linux_amd64.zip
Resolving releases.hashicorp.com (releases.hashicorp.com)... 151.101.109.183, 2a04:4e42:1a::439
Connecting to releases.hashicorp.com (releases.hashicorp.com)|151.101.109.183|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 16519860 (16M) [application/zip]
Saving to: ‘terraform_0.12.18_linux_amd64.zip’
 
terraform_0.12.18_linux_amd64.zip                                 100%[==========================================================================================================================================================>]  15.75M  37.7MB/s    in 0.4s
 
2019-12-29 09:16:06 (37.7 MB/s) - ‘terraform_0.12.18_linux_amd64.zip’ saved [16519860/16519860]
 
zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise$ sudo unzip ./terraform_0.12.18_linux_amd64.zip -d /usr/local/bin
Archive:  ./terraform_0.12.18_linux_amd64.zip
  inflating: /usr/local/bin/terraform
zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise$ terraform -v
Terraform v0.12.18

 

 

 

Azure에 대한 Terraform 액세스 설정

Terraform에서 Azure로 리소스를 프로비전할 수 있도록 Azure AD 서비스 사용자를 만든다. 서비스 사용자는 Azure 구독에서 리소스를 프로비전하는 권한을 Terraform 스크립트에 부여한다.

여러 Azure 구독이 있는 경우 먼저 az account list 를 사용하여 계정을 쿼리하여 구독 id 및 테넌트 id 값의 목록을 가져온다.

zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise/20191229$ az account list --query "[].{name:name, subscriptionId:id, tenantId:tenantId}"
A few accounts are skipped as they don't have 'Enabled' state. Use '--all' to display them.
[
  {
    "name": "Visual Studio Enterprise 2019",
    "subscriptionId": "2e5d848e-xxxx-xxxx-xxxx-fd25ae915bcd",
    "tenantId": "54a472fb-1510-4554-922c-fe808f9e6e64"      
  },
  {
    "name": "Visual Studio Enterprise 201907",
    "subscriptionId": "f8764f39-xxxx-xxxx-xxxx-77b286ed971b",
    "tenantId": "917bfe84-0ca6-488d-ad3a-236e41ceafe9"      
  },
  {
    "name": "Visual Studio Enterprise – MPN",
    "subscriptionId": "2dce383a-xxxx-xxxx-xxxx-5fc758f9cf1d",
    "tenantId": "22921252-b61a-4ab3-ac9a-8f160db61f8d"      
  }
]

 

선택한 구독을 사용하려면 az account set 명령을 사용하여 이 세션에 대한 구독을 설정한다. 사용하려는 구독에서 반환된 SUBSCRIPTION_ID 필드 값을 보유하도록 id 환경 변수를 설정한다.

zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise/20191229$ az account set --subscription="2e5d848e-xxxx-xxxx-xxxx-fd25ae915bcd"

 

이제 Terraform에 사용할 서비스 사용자를 만들 수 있다. 다음과 같이 az ad sp create-for-rbac를 사용하고, 범위를 구독으로 설정한다.

zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise/20191229$ az account set --subscription="2e5d848e-xxxx-xxxx-xxxx-fd25ae915bcd"

 

appId, password, sp_name 및 tenant가 반환된다. appId 및 password를 기록해 둔다.

zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise/20191229$ az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/2e5d848e-xxxx-xxxx-xxxx-fd25ae915bcd"
Creating a role assignment under the scope of "/subscriptions/2e5d848e-xxxx-xxxx-xxxx-fd25ae915bcd"
  Retrying role assignment creation: 1/36
  Retrying role assignment creation: 2/36
  Retrying role assignment creation: 3/36
  Retrying role assignment creation: 4/36
{
  "appId": "3381f28b-cbb3-4235-848b-f0225616d90a",
  "displayName": "azure-cli-2019-12-29-00-37-40",
  "name": "http://azure-cli-2019-12-29-00-37-40",
  "password": "34e94183-xxxx-xxxx-xxxx-1e2fd6f7d160",
  "tenant": "54a472fb-1510-4554-922c-fe808f9e6e64"
}

 

 

 

 

 

Terraform 환경 변수 구성

Azure AD 서비스 사용자를 사용하도록 Terraform을 구성하려면 다음 환경 변수를 설정한다. 이 환경 변수는 Azure Terraform 모듈에 사용된다. Azure 공용이 아닌 Azure 클라우드에서 작업하는 경우 환경을 설정할 수도 있다.

  • ARM_SUBSCRIPTION_ID
  • ARM_CLIENT_ID
  • ARM_CLIENT_SECRET
  • ARM_TENANT_ID
  • ARM_ENVIRONMENT

terraform-var.sh 셸 스크립트를 사용하여 해당 변수를 설정할 수 있다.

zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise/20191229$ vi terraform-var.sh
#!/bin/sh
echo "Setting environment variables for Terraform"
export ARM_SUBSCRIPTION_ID=2e5d848e-xxxx-xxxx-xxxx-fd25ae915bcd
export ARM_CLIENT_ID=3381f28b-cbb3-4235-848b-f0225616d90a
export ARM_CLIENT_SECRET=34e94183-xxxx-xxxx-xxxx-1e2fd6f7d160
export ARM_TENANT_ID=54a472fb-1510-4554-922c-fe808f9e6e64
 
# Not needed for public, required for usgovernment, german, china
export ARM_ENVIRONMENT=public
~
~
~
~
~
~
~
zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise/20191229$ sh terraform-env.sh
Setting environment variables for Terraform
zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise/20191229$ source terraform-env.sh
Setting environment variables for Terraform
zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise/20191229$ echo $ARM_TENANT_ID             
54a472fb-1510-4554-922c-fe808f9e6e64

 

 

 

 

 

 

샘플 스크립트 실행

빈 디렉터리에 test.tf 파일을 만들고 다음 스크립트에 붙여넣는다.

zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise/20191229$ vi test.tf
provider "azurerm" {
}
resource "azurerm_resource_group" "rg" {
        name = "testResourceGroup"
        location = "koreacentral"
}

 

파일을 저장하고 Terraform 배포를 초기화한다. 이 단계에서는 Azure 리소스 그룹을 만드는 데 필요한 Azure 모듈을 다운로드한다.

zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise/20191229$ terraform init
 
Initializing the backend...
 
Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "azurerm" (hashicorp/azurerm) 1.39.0...
 
The following providers do not have any version constraints in configuration,
so the latest version was installed.
 
To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.
 
* provider.azurerm: version = "~> 1.39"
 
Terraform has been successfully initialized!
 
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
 
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

 

terraform plan 명령을 사용하면 Terraform 스크립트에서 완료할 작업을 미리 볼 수 있다. 리소스 그룹을 만들 준비가 완료되면 다음과 같이 Terraform 계획을 적용한다.

zerobig@ZEROBIG-NT800:/mnt/c/AzureDevOps-Exercise/20191229$ terraform apply
 
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create
 
Terraform will perform the following actions:
 
  # azurerm_resource_group.rg will be created
  + resource "azurerm_resource_group" "rg" {
      + id       = (known after apply)
      + location = "koreacentral"
      + name     = "testResourceGroup"
      + tags     = (known after apply)
    }
 
Plan: 1 to add, 0 to change, 0 to destroy.
 
Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.
 
  Enter a value: yes
 
azurerm_resource_group.rg: Creating...
azurerm_resource_group.rg: Creation complete after 0s [id=/subscriptions/2e5d848e-xxxx-xxxx-xxxx-fd25ae915bcd/resourceGroups/testResourceGroup]
 
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

 

Azure Portal로 이동하여 배포 상태를 확인한다. 다음과 같이 정상적으로 리소스 그룹이 생성되어 있음을 확인할 수 있다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/02   »
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
글 보관함