プロバイダーバージョンエラーの原因と解決方法

1. 概要

  • 「Failed to query available provider packages」エラー
  • 「Could not retrieve the list of available versions for provider」エラー
  • 「lock file has constraints that are not met」エラー
  • 原因と解決方法(terraform init -upgrade・lock.hclの更新)

プロバイダーのバージョン関連エラーは、required_providersの制約と.terraform.lock.hclの記録が一致しないときや、ネットワーク接続の問題で発生します。


2. よくあるエラーメッセージ

エラー1: lock.hclとrequired_providersが不一致

Error: Failed to satisfy version constraints

  "hashicorp/aws": constraints "~> 5.0" but lock file "4.67.0"

Because the installed provider "hashicorp/aws" version 4.67.0 does not satisfy
the version constraint "~> 5.0", Terraform ran into an error.

エラー2: lock.hclなしでprovider指定なし

│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider
│ hashicorp/aws: could not connect to registry.terraform.io

エラー3: バージョン制約の競合

Error: Incompatible provider version
Provider hashicorp/aws 5.60.0 was already selected, but the root module
requires >= 4.0, < 5.0.

3. 解決方法1: terraform init -upgrade(最も一般的)

terraform {
  required_version = ">= 1.9"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"  # バージョンを上げた場合
    }
  }
}

provider "aws" {
  region = "ap-northeast-1"
}

variable "environment" {
  description = "環境名"
  type        = string
  default     = "dev"
}
# lock.hclを更新して新しい制約に合わせたバージョンをインストール
terraform init -upgrade

# 確認
terraform version
# Terraform v1.9.x
# on linux_amd64
# + provider registry.terraform.io/hashicorp/aws v5.60.0

4. 解決方法2: .terraform.lock.hclを削除して再init

# lock.hclを削除(通常は-upgradeで十分)
rm .terraform.lock.hcl
terraform init

# ⚠️ 注意: 削除後は制約を満たす最新バージョンがインストールされる
# チームに共有する前に terraform plan でテストすること

5. バージョン制約の競合を解消する

# ❌ 競合: モジュールとルートの制約が重複しない
# root: version = "~> 5.0"(5.x系のみ)
# module: version = "< 5.0"(5.0未満のみ)→ 重複なし → エラー

# ✅ 解消: ルートで範囲を広げる
terraform {
  required_version = ">= 1.9"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 4.0"  # モジュールが<5.0を要求する場合はこれで両方満たせる
    }
  }
}

6. レジストリに接続できない場合

# プロキシ環境や閉域網でregistry.terraform.ioに接続できない場合
export HTTPS_PROXY=http://proxy.example.com:8080
terraform init

# またはproviderをローカルミラーから使う
# ~/.terraform.d/plugins/ にプロバイダーバイナリを配置

7. 関連記事


8. まとめ

  • lock.hclとrequired_providersが不一致terraform init -upgradeで解消
  • レジストリへの接続エラー → ネットワーク・プロキシ設定を確認
  • 複数モジュール間のバージョン制約競合 → 制約が重複する範囲になるよう調整
  • .terraform.lock.hclはGitにコミットし、バージョンをチームで統一すること

動作確認バージョン: Terraform >= 1.9 公式ドキュメント: https://developer.hashicorp.com/terraform/language/files/dependency-lock