Terraform-如何在模块中使用tfvars

luc*_*axi 5 terraform

在三个不同的环境中,我希望能够根据环境动态设置变量。在下面的示例中,假设开发人员和生产人员之间的实例类型不同。我无法instance_type在模块中进行引用,除非我vars.tf旁边有一个文件terraform.tfvars

我得到的错误是:

unknown variable referenced: 'instance_type'. define it with 'variable' blocks

如果是这种情况,那么该文件不是与下一个完全相同的文件modules/apollo/vars.tf吗?

我认为modules/apollo/vars.tf定义了模块所需的必要变量。我认为在的“根”级别下没有必要env-dev/services/apollo/。如果有一种“更好”的方法,我会全神贯注的。

??? env-dev
?   ??? services
?       ??? apollo
?           ??? main.tf
?           ??? terraform.tfvars    
?           ??? vars.tf # Do i need this?
??? env-test
??? global
??? mgmt
??? modules
    ??? apollo
    ?   ??? main.tf
    ?   ??? user_data.tpl
    ?   ??? vars.tf
    ??? defaults
        ??? main.tf
Run Code Online (Sandbox Code Playgroud)

env-dev / services / apollo / terraform.tfvars

instance_type    = "t2.medium"
Run Code Online (Sandbox Code Playgroud)

env-prod / services / apollo / terraform.tfvars

instance_type    = "t2.large"
Run Code Online (Sandbox Code Playgroud)

modules / apollo / vars.tf

variable "instance_type" {
  description = "EC2 Instance Type"
}
Run Code Online (Sandbox Code Playgroud)

modules / apollo / main.tf

resource "aws_instance" "instance" {     
  ...
  instance_type           = "${var.instance_type}"
  ...
}
Run Code Online (Sandbox Code Playgroud)

BMW*_*BMW 4

调整结构,这是我对你的应用的理解。

\n\n
\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 dev\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 apollo_terraform.tfvars    \n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 test\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 apollo_terraform.tfvars\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 global\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 apollo_terraform.tfvars\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 mgmt\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 apollo_terraform.tfvars\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.tf,  vars.tf, output.tf, apollo.tf, default.tf, etc\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 modules\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 apollo\n    \xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main.tf\n    \xe2\x94\x82   \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 user_data.tpl\n    \xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 vars.tf\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 defaults\n        \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.tf\n
Run Code Online (Sandbox Code Playgroud)\n\n

apollo.tf将有源模块代码来使用共享模块apollo。相同的设置default.tf

\n\n

你的计划/应用命令应该是这样的:

\n\n
terraform plan -var-file=${env}/apollo_terraform.tfvars\n
Run Code Online (Sandbox Code Playgroud)\n

  • 在这种情况下,您将在同一文件中声明所有环境的基础架构配置,并且还会有一个状态文件,这不是理想的情况吗? (6认同)