Terraform: аргумент требуется, но не найден - PullRequest
0 голосов
/ 30 сентября 2019

Вот моя структура каталогов:

├── main.tf
├── modules
│   ├── subnets
│   │   ├── main.tf
│   │   ├── outputs.tf
│   │   └── variables.tf
│   ├── variables.tf
│   └── vpc
│       ├── main.tf
│       ├── outputs.tf
│       └── variables.tf
├── outputs.tf
└── variables.tf

и мой modules/vpc/main.tf

resource "aws_vpc" "env_vpc" {
  cidr_block           = "${var.vpc_cidr_block}"
  enable_dns_support   = "${var.vpc_enable_dns_support}"
  enable_dns_hostnames = "${var.vpc_enable_dns_hostnames}"

  tags = {
    Name        = "${var.env_name}-vpc"
    Provisioner = "Terraform"
  }

  lifecycle {
    create_before_destroy = true
  }
}

и мой modules/vpc/variables.tf

variable "env_name" {
    description = "The name of the env the VPC will belong to"
    # no default provided
}

Когда я выполняю terraform plan

➢  terraform plan

Error: Missing required argument

  on main.tf line 1, in module "vpc":
   1: module "vpc" {

The argument "env_name" is required, but no definition was found.

Когда я передаю переменную в cmd:

➢  terraform plan -var 'env_name=ffff'

Error: Value for undeclared variable

A variable named "env_name" was assigned on the command line, but the root
module does not declare a variable of that name. To use this value, add a
"variable" block to the configuration.

Проблема не исчезает, даже когда я объявляю переменную в корне variables.tf

как в

➢  cat variables.tf
variable "env_name" {}

какие-либо предложения?

edit : Когда я предоставил значение default для этой переменной, plan сработало. Он действительно запрашивал у меня в интерактивном режиме значение env_name, но вывод plan был со значением default. Почему это так?

edit2 : Разъяснение о содержании файлов variables.tf:

  • В каталоге root :
➢  ls
main.tf      modules      outputs.tf   variables.tf
➢  cat variables.tf
variable "env_name" {}

В каталоге modules/vpc:

➢  ls
main.tf      outputs.tf   variables.tf
aws_vpc/modules/vpc  stand_alone_vpc ✗   

➢  cat variables.tf
variable "env_name" {
    description = "The name of the environment/microservice the VPC will belong to"
    default = "wbl"
}

просит меня ввести значение env_name, но оно игнорирует это и использует default, как установлено в modules/vpc/variables.tf. Вот это plan:

➢  terraform plan
var.env_name
  Enter a value: foo

Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.


------------------------------------------------------------------------

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:

  # module.vpc.aws_internet_gateway.env_igw will be created
  + resource "aws_internet_gateway" "env_igw" {
      + id       = (known after apply)
      + owner_id = (known after apply)
      + tags     = {
          + "Name"        = "wbl-igw"
          + "Provisioner" = "Terraform"
        }
      + vpc_id   = (known after apply)
    }

  # module.vpc.aws_vpc.env_vpc will be created
  + resource "aws_vpc" "env_vpc" {
      + arn                              = (known after apply)
      + assign_generated_ipv6_cidr_block = false
      + cidr_block                       = "10.0.0.0/16"
      + default_network_acl_id           = (known after apply)
      + default_route_table_id           = (known after apply)
      + default_security_group_id        = (known after apply)
      + dhcp_options_id                  = (known after apply)
      + enable_classiclink               = (known after apply)
      + enable_classiclink_dns_support   = (known after apply)
      + enable_dns_hostnames             = true
      + enable_dns_support               = true
      + id                               = (known after apply)
      + instance_tenancy                 = "default"
      + ipv6_association_id              = (known after apply)
      + ipv6_cidr_block                  = (known after apply)
      + main_route_table_id              = (known after apply)
      + owner_id                         = (known after apply)
      + tags                             = {
          + "Name"        = "wbl-vpc"
          + "Provisioner" = "Terraform"
        }
    }

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

------------------------------------------------------------------------

Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.

1 Ответ

1 голос
/ 01 октября 2019

Кажется, что способ обойти это (то есть, чтобы иметь возможность переопределить значение default, установленное в variable.tf подмодуля), следующий:

1 ) объявитьпеременная на верхнем (корневом) уровне variables.tf, как в

> $ cat variables.tf
variable "env_name" {
  default = "top-level"
}

2 ), объявляет переменную в разделе корневого модуля main.tf, который вызывает подмодуль, как в:

module "vpc" {
  source = "./modules/vpc"
  # variables
  env_name = "${var.env_name}"
}

Таким образом, переменная, которая в итоге будет передана в подмодуле, будет объявлена ​​в родительском модуле variables.tf

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...