{Terraform} Resources encryption with Secrets Stores

参考文献: Terraform Up & Running (Yevgeniy Brikman著)


-- 1. シークレット作成


aws secretsmanager list-secrets

aws secretsmanager create-secret \
--name secret01 \
--description secret01

aws secretsmanager describe-secret \
--secret-id secret01


aws secretsmanager put-secret-value \
--secret-id secret01 \
--secret-string '
{"username":"root", 
 "password":"password"
}
'


aws secretsmanager get-secret-value \
--secret-id secret01

 

-- 2. tfファイル作成

cat <<-'EOF' >  main.tf

terraform {
  required_version = "= 1.6.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "= 4.17.0"
    }
  }
}


provider "aws" {
  region = "ap-northeast-1"
}

data "aws_secretsmanager_secret_version" "creds" {
  secret_id = "secret01"
}

locals {
  secret01 = jsondecode(
    data.aws_secretsmanager_secret_version.creds.secret_string
  )
}


resource "aws_db_instance" "mysql01" {
  identifier                   = "mysql01"
  allocated_storage            = 20
  storage_type                 = "gp2"
  engine                       = "mysql"
  engine_version               = "8.0.28"
  instance_class               = "db.t3.micro"
  username                     = local.secret01.username
  password                     = local.secret01.password
  skip_final_snapshot          = true
  allow_major_version_upgrade  = false
  auto_minor_version_upgrade   = false
  delete_automated_backups     = true
  deletion_protection          = false
  multi_az                     = false
  performance_insights_enabled = false
  publicly_accessible          = true
}

EOF

cat <<-'EOF' >  outputs.tf

output "address" {
  value = aws_db_instance.mysql01.address
  description = "Connect to the database at this endpoint"
}

output "port" {
  value = aws_db_instance.mysql01.port
  description = "The port the database is listening on"
}

EOF


-- 3. terraform 実行

terraform init
terraform fmt
terraform -version

terraform plan
terraform apply -auto-approve
terraform output

 

aws rds describe-db-instances
mysql -h mysql01.xxxxxxxxxxxx.ap-northeast-1.rds.amazonaws.com  -P 3306 -u root -p

 

-- 4. クリーンアップ


terraform destroy -auto-approve

 


-- シークレット削除
aws secretsmanager list-secrets

aws secretsmanager delete-secret \
--secret-id secret01 \
--force-delete-without-recovery