🔥

【Terraform /python】- Python-Terraform ってなんだ??

に公開

執筆日

2025/5/12

Python-Terraform

Terraform をPythonから制御できるライブラリです。

https://github.com/beelit94/python-terraform

コード

ライブラリをインストールする

pip install python-terraform

以下の構成でフォルダを構成します。

main.py
from python_terraform import Terraform

tf = Terraform(working_dir='./terraform')

# initを実行
return_code, stdout, stderr = tf.init()
print('return_code:', return_code)
print('stdout:', stdout)
print('stderr:', stderr)
print("=== terraform plan ===")
# planを実行
return_code, stdout, stderr = tf.plan(refresh=False)

print('return_code:',return_code)
print('stdout:', stdout)
print('stderr:', stderr)

※Azureとの連携はしていないです

解説

項目 説明
return_code 実行結果の状態を表す数値です。0:成功、1以上:エラーや変更あり
stdout Terraformコマンドの実行結果メッセージ(標準出力)です。
stderr Terraformのエラーや警告メッセージ(標準エラー出力)です。正常終了の場合は空になります。
main.tf
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 3.0"
    }
  }
}

provider "azurerm" {
  features {}
}

# Resource Groupの作成
resource "azurerm_resource_group" "example" {
  name     = "example-rg"
  location = "Japan East"
}

# ストレージアカウントの作成
resource "azurerm_storage_account" "example" {
  name                     = "examplestorageacct01" 
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

# Blobコンテナの作成
resource "azurerm_storage_container" "example" {
  name                  = "example-container"
  storage_account_name  = azurerm_storage_account.example.name
  container_access_type = "private"
}
出力結果
return_code: 0
stdout: Initializing the backend...
Initializing provider plugins...
- Reusing previous version of hashicorp/azurerm from the dependency lock file
- Using previously-installed hashicorp/azurerm v3.117.1

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.     

stderr:
=== terraform plan ===
return_code: 2
stdout: 
Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:  
  + create

Terraform will perform the following actions:

  # azurerm_resource_group.example will be created
  + resource "azurerm_resource_group" "example" {
      + id       = (known after apply)
      + location = "japaneast"
      + name     = "example-rg"
    }

  # azurerm_storage_account.example will be created
  + resource "azurerm_storage_account" "example" {
      + access_tier                        = (known after apply)  
      + account_kind                       = "StorageV2"
      + account_replication_type           = "LRS"
      + account_tier                       = "Standard"
      + allow_nested_items_to_be_public    = true
      + cross_tenant_replication_enabled   = true
      + default_to_oauth_authentication    = false
      + dns_endpoint_type                  = "Standard"
      + enable_https_traffic_only          = (known after apply)  
      + https_traffic_only_enabled         = (known after apply)  
      + id                                 = (known after apply)  
      + infrastructure_encryption_enabled  = false
      + is_hns_enabled                     = false
      + large_file_share_enabled           = (known after apply)  
      + local_user_enabled                 = true
      + location                           = "japaneast"
      + min_tls_version                    = "TLS1_2"
      + name                               = "examplestorageacct01"
      + nfsv3_enabled                      = false
      + primary_access_key                 = (sensitive value)    
      + primary_blob_connection_string     = (sensitive value)    
      + primary_blob_endpoint              = (known after apply)  
      + primary_blob_host                  = (known after apply)  
      + primary_blob_internet_endpoint     = (known after apply)  
      + primary_blob_internet_host         = (known after apply)  
      + primary_blob_microsoft_endpoint    = (known after apply)  
      + primary_blob_microsoft_host        = (known after apply)  
      + primary_connection_string          = (sensitive value)    
      + primary_dfs_endpoint               = (known after apply)  
      + primary_dfs_host                   = (known after apply)  
      + primary_dfs_internet_endpoint      = (known after apply)  
      + primary_dfs_internet_host          = (known after apply)  
      + primary_dfs_microsoft_endpoint     = (known after apply)  
      + primary_dfs_microsoft_host         = (known after apply)  
      + primary_file_endpoint              = (known after apply)  
      + primary_file_host                  = (known after apply)  
      + primary_file_internet_endpoint     = (known after apply)  
      + primary_file_internet_host         = (known after apply)  
      + primary_file_microsoft_endpoint    = (known after apply)  
      + primary_file_microsoft_host        = (known after apply)  
      + primary_location                   = (known after apply)  
      + primary_queue_endpoint             = (known after apply)  
      + primary_queue_host                 = (known after apply)  
      + primary_queue_microsoft_endpoint   = (known after apply)  
      + primary_queue_microsoft_host       = (known after apply)  
      + primary_table_endpoint             = (known after apply)  
      + primary_table_host                 = (known after apply)  
      + primary_table_microsoft_endpoint   = (known after apply)  
      + primary_table_microsoft_host       = (known after apply)  
      + primary_web_endpoint               = (known after apply)  
      + primary_web_host                   = (known after apply)  
      + primary_web_internet_endpoint      = (known after apply)  
      + primary_web_internet_host          = (known after apply)  
      + primary_web_microsoft_endpoint     = (known after apply)  
      + primary_web_microsoft_host         = (known after apply)  
      + public_network_access_enabled      = true
      + queue_encryption_key_type          = "Service"
      + resource_group_name                = "example-rg"
      + secondary_access_key               = (sensitive value)    
      + secondary_blob_connection_string   = (sensitive value)    
      + secondary_blob_endpoint            = (known after apply)  
      + secondary_blob_host                = (known after apply)  
      + secondary_blob_internet_endpoint   = (known after apply)  
      + secondary_blob_internet_host       = (known after apply)  
      + secondary_blob_microsoft_endpoint  = (known after apply)  
      + secondary_blob_microsoft_host      = (known after apply)  
      + secondary_connection_string        = (sensitive value)    
      + secondary_dfs_endpoint             = (known after apply)  
      + secondary_dfs_host                 = (known after apply)  
      + secondary_dfs_internet_endpoint    = (known after apply)  
      + secondary_dfs_internet_host        = (known after apply)  
      + secondary_dfs_microsoft_endpoint   = (known after apply)  
      + secondary_dfs_microsoft_host       = (known after apply)  
      + secondary_file_endpoint            = (known after apply)  
      + secondary_file_host                = (known after apply)  
      + secondary_file_internet_endpoint   = (known after apply)  
      + secondary_file_internet_host       = (known after apply)  
      + secondary_file_microsoft_endpoint  = (known after apply)  
      + secondary_file_microsoft_host      = (known after apply)  
      + secondary_location                 = (known after apply)  
      + secondary_queue_endpoint           = (known after apply)  
      + secondary_queue_host               = (known after apply)  
      + secondary_queue_microsoft_endpoint = (known after apply)  
      + secondary_queue_microsoft_host     = (known after apply)  
      + secondary_table_endpoint           = (known after apply)  
      + secondary_table_host               = (known after apply)  
      + secondary_table_microsoft_endpoint = (known after apply)  
      + secondary_table_microsoft_host     = (known after apply)  
      + secondary_web_endpoint             = (known after apply)  
      + secondary_web_host                 = (known after apply)  
      + secondary_web_internet_endpoint    = (known after apply)  
      + secondary_web_internet_host        = (known after apply)  
      + secondary_web_microsoft_endpoint   = (known after apply)  
      + secondary_web_microsoft_host       = (known after apply)  
      + sftp_enabled                       = false
      + shared_access_key_enabled          = true
      + table_encryption_key_type          = "Service"

      + blob_properties (known after apply)

      + network_rules (known after apply)

      + queue_properties (known after apply)

      + routing (known after apply)

      + share_properties (known after apply)

      + static_website (known after apply)
    }

  # azurerm_storage_container.example will be created
  + resource "azurerm_storage_container" "example" {
      + container_access_type             = "private"
      + default_encryption_scope          = (known after apply)   
      + encryption_scope_override_enabled = true
      + has_immutability_policy           = (known after apply)   
      + has_legal_hold                    = (known after apply)   
      + id                                = (known after apply)
      + metadata                          = (known after apply)
      + name                              = "example-container"
      + resource_manager_id               = (known after apply)
      + storage_account_name              = "examplestorageacct01"
    }

Plan: 3 to add, 0 to change, 0 to destroy.

─────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't
guarantee to take exactly these actions if you run "terraform apply" now.

stderr:

Azureと連携する場合

Azureと連携する際は、Azure CLIやサービスプリンシパルを使った認証が必要です。
通常のTerraform運用時には refresh=True に変更してください。
実際にAzure環境に適用するには、tf.apply()を使ってください。

ヘッドウォータース

Discussion