Terraform模块具有访问密钥

时间:2017-10-07 20:44:31

标签: terraform

我使用以下内容:

  • Windows 10
  • Visual Studio Code v1.17.0
  • Terraform v0.10.3
  • AWS

我对Terraform很新。我一直在阅读一系列非常有帮助的帖子here

在将AWS访问密钥传递给我的模块时,我很挣扎。我有一个非常基本的文件夹结构:

root
|__terraform.tfvars
|__management
    |__network
        |__main.tf
        |__vars.tf
|__modules
    |__network
        |__main.tf
        |__vars.tf

相关文件的内容位于帖子的底部。

root/management/network目录中,我运行terraform get命令导入模块。

然后我运行以下命令,希望一切正常:

terraform plan -var-file="../../terraform.tfvars" -state="../management.tfstate"

但是,我收到以下错误:

Error asking for user input: 1 error(s) occurred:

* module.mgmt-network.provider.aws: 1:3: unknown variable accessed: 
var.aws_region in:

${var.aws_region}

我尝试了对该区域进行硬编码,但是它只会引发相同的错误,但对于aws_access_key

本质上,我只是想了解如何指定这些变量以在我的所有模块中使用。

根/ terraform.tfvars

aws_access_key  = "XXX"
aws_secret_key  = "YYYYYY"
aws_region      = "eu-west-2"

根/管理/网络/ main.tf

module "mgmt-network" {
    source                          = "../../modules/network"

    network_address_space           = "${var.network_address_space}"
    enable_dns_hostnames            = true
    public_subnet_1_address_space   = "${var.public_subnet_1_address_space}"
    map_public_ip_on_launch         = true
}

根/模块/网络/ main.tf

--   PROVIDER
provider "aws" {
    access_key  = "${var.aws_access_key}"
    secret_key  = "${var.aws_secret_key}"
    region      = "${var.aws_region}"
}

--   DATA
data "aws_availability_zones" "availability_zones" {}

resource "aws_vpc" "vpc" {
    cidr_block              = "${var.network_address_space}"
    enable_dns_hostnames    = "${var.enable_dns_hostnames}"
}

resource "aws_subnet" "public-subnet1" {
    cidr_block              = "${var.public_subnet_1_address_space}"
    vpc_id                  = "${aws_vpc.vpc.id}"
    map_public_ip_on_launch = "${var.map_public_ip_on_launch}"
    availability_zone       = "${data.aws_availability_zones.availability_zones.names[0]}"
}

root / modules / network / vars.tf

variable "aws_access_key" {}
variable "aws_secret_key" {}
variable "aws_region" {}

variable "network_address_space" {
    description = "cidr block of available ips in the network"
}

variable "enable_dns_hostnames" {
    description = "boolean to enable dns names"
}

variable "public_subnet_1_address_space" {
    description = "cidr block of available ips in the first public subnet"
}

variable "map_public_ip_on_launch" {
    description = "boolean to enable public ips in subnet"
}

1 个答案:

答案 0 :(得分:2)

我相信你所缺少的是在使用它们之前声明你的变量。我希望这些定义位于modules / network和root / management文件夹中的vars.tf文件中。

看起来像这样:

variable "aws_access_key" { }
variable "aws_secret_key" { }
variable "aws_region"     { }

这是一个变量.tf文件的例子,我猜这是vars.tf应该在这个项目中:https://github.com/terraform-aws-modules/terraform-aws-vpc/blob/master/variables.tf

有关变量的更多详细信息:https://www.terraform.io/docs/configuration/variables.html