使用自Terraform 0.8起添加的Vault Provider后,aws云基础设施尝试从Vault而不是tfvars或环境变量中读取AWS凭证。
1 什么是vault?
vault是一种由Hashicorp发布的用于管理机密信息的工具。
2 aws使用Terraform的Vault Provider
2.1 创建静态密钥
以开发模式启动Vault。
在开发模式下,机密会记录在内存中,并在停止时清除。
$ vault server -dev
设置VAULT_ADDR环境变量以从客户端操作Vault。
$ export VAULT_ADDR=http://127.0.0.1:8200
在开发模式下,没有TLS,并且您在启动时以Unseal或root用户身份登录。
在实际环境中,访问保管库要求使用解锁密钥和用户身份验证进行解锁。
有关此区域的图像,我认为您应该体验官方的交互式教程。
静态写入AWS访问密钥/秘密访问密钥。
$ vault write secret/aws_test access_key=xxxxxxxxxxxxxx secret_key=xxxxxxxxxxxxxxxxxxxxSuccess! Data written to: secret/aws_test
如果您不想将其保留在shell历史记录中,请以JSON格式编写,并使用@指定文件
$ vault write secret/aws_test @data.json
2.2 创建一个TF文件
vault_generic_secret使用数据源。
我使用Terraform Module Registry中的ec2-instance模块启动了EC2。
data "vault_generic_secret" "aws_test" {
path = "secret/aws_test"
}
provider "aws" {
access_key = "${data.vault_generic_secret.aws_test.data["access_key"]}"
secret_key = "${data.vault_generic_secret.aws_test.data["secret_key"]}"
region = "ap-northeast-1"
}
# fileter latest AMI
data "aws_ami" "amazon_linux" {
most_recent = true
filter {
name = "name"
values = [
"amzn-ami-hvm-*-x86_64-gp2",
]
}
filter {
name = "owner-alias"
values = [
"amazon",
]
}
}
module "ec2-instance" {
source = "terraform-aws-modules/ec2-instance/aws"
name = "aws_test_ec2"
count = 1
ami = "${data.aws_ami.amazon_linux.id}"
instance_type = "t2.micro"
key_name = "keyname"
vpc_security_group_ids = ["sg-12345678"]
}
2.3 运行
-
terraform init
-
terraform plan
-
terraform apply
$terraform plan
Refreshing Terraform state in-memory prior to plan...
T he refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.data.vault_generic_secret.aws_test: Refreshing state...
data.aws_ami.amazon_linux: Refreshing state...
以下略..
如果未设置vault为unseal,则将输出以下错误 :
$ terraform plan
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.
Error refreshing state: 1 error(s) occurred:
* provider.vault: failed to create limited child token: Error making API request.
URL: POST http://127.0.0.1:8200/v1/auth/token/create
Code: 503. Errors:
* Vault is sealed
很重要的一点,从vault读取的数据以明文形式记录在tfstate中。因此TFstate管理必须严格。