6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Terrafrom】Moduleに変数を渡す際に Error: Unsupported argument が発生する

Last updated at Posted at 2020-07-31

はじめに

Terraformを勉強中にハマった箇所があり、調べても中々出てこなかったので共有します。

結論

変数を渡そうとしているModuleのディレクトリ(本記事ではbaseディレクトリ)内に、variables.tfを作成し、渡そうとしている変数を定義しましょう。

# base/variables.tf

variable "vpc_id" {}
variable "region" {}

状況

発生した状況は以下のような形です。
Moduleを使用しており、ルートモジュールから子モジュールへ変数を渡そうとしています。

# ディレクトリ構成

❯ tree .
.
├── base
│   └── vpc.tf
├── main.tf
└── variables.tf

# main.tf

variable "vpc_id" {}
variable "region" {}

provider "aws" {
  profile = "default"
  region  = var.region
}

module "base" {
  source = "./base"

  vpc_id = var.vpc_id
  region = var.region
}
# variables.tf

variable "vpc_id" { default = "xxxxxxxxxxxxxx" }
variable "region" { default = "ap-northeast-1" }
# base/vpc.tf

data "aws_vpc" "selected" {
  id = "${var.vpc_id}"
}

resource "aws_subnet" "example" {
  vpc_id            = "${data.aws_vpc.selected.id}"
  availability_zone = "${var.region}a"
  cidr_block        = "${cidrsubnet(data.aws_vpc.selected.cidr_block, 4, 1)}"
}

エラー内容

この状況でterraform applyを実行するとエラーが発生します。

❯ terraform apply

Error: Unsupported argument

  on main.tf line 12, in module "base":
  12:   vpc_id = var.vpc_id

An argument named "vpc_id" is not expected here.


Error: Unsupported argument

  on main.tf line 13, in module "base":
  13:   region  = var.region

An argument named "region" is not expected here.

原因

子モジュール内で変数を定義していないことが原因です。
TerraformのMuduleは、あるディレクトリ内の設定ファイル(.tfファイル)の集合体です。
モジュールで使用する変数は、モジュール毎に定義してあげる必要があります。
そのため、変数を渡そうとしているModuleのディレクトリ内で、変数を定義する必要があります。

個人的には、Moduleブロック内で変数を渡すだけで、子モジュールで使用可能になると勘違いしていました。

Terraform Modules - 公式ドキュメント

最後に

公式ドキュメントは一通り読んでいましたが、モジュール毎に変数の定義が必要とは書いていなかったような気が、、、。(見落としていたのかもしれません)

見落としていました!
@raki さんコメントで教えて頂きありがとうございます!
Terraform Creating Modules - 公式ドキュメント

最終的にはStackOverflowの回答からヒントを得て解決しました。
何方かの助けになれば幸いです。

6
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?