0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Local環境からTerraformでS3を作成する。

0
Last updated at Posted at 2025-08-09

Terraformとは

Terraformとはインフラ構成をコードで管理するためのツール。
.tf ファイルからAWSのリソースを作成することができる。

TerraformでS3バケットを作成する。

まずは次のファイルを作成。

main.tf
data "aws_caller_identity" "self" {}
data "aws_region" "current" {}

locals {
  bucket_name = "kabubato-${data.aws_caller_identity.self.account_id}-${data.aws_region.current.name}-dev"
}

resource "aws_s3_bucket" "this" {
  bucket = local.bucket_name
  tags = {
    Name = local.bucket_name
  }
}

Terraformのコマンドを実行すると、まずこのファイルが実行されることになる。

AWS Access Key ID の取得

  • AWSのマネジメントコンソールに移動
  • 対象ユーザーを選択した後に、アクセスキーとシークレットアクセスキーを取得
  • AWS Access Key ID と AWS Secret Access Key を入力する。regionとoutputはデフォルトのものを利用。
AWS Access Key ID [None]: 
AWS Secret Access Key [None]:
Default region name [None]: 
Default output format [None]: 

Terraformコマンドの実行

cd ~/s3
terraform init -input=false
terraform validate
terraform plan -var="bucket_name=kabubato-bucket-$(date +%s)"
terraform apply -auto-approve -var="bucket_name=bucket-$(date +%s)"

発生するエラー

Planning failed. Terraform encountered an error while generating this plan.

╷
│ Error: Retrieving AWS account details: validating provider credentials: retrieving caller identity from STS: operation error STS: GetCallerIdentity, https response error StatusCode: 403, RequestID: df28760f-58b1-4fad-ba3f-25a7b843251f, api error InvalidClientTokenId: The security token included in the request is invalid.
│ 
│   with provider["registry.terraform.io/hashicorp/aws"],
│   on providers.tf line 1, in provider "aws":
│    1: provider "aws" {
│ 

次のエラーが出るため、AWSのアクセスキーとシークレットアクセスキーが有効かを確認する。

$ aws sts get-caller-identity
An error occurred (InvalidClientTokenId) when calling the GetCallerIdentity operation: The security token included in the request is invalid.

$ aws configure list 
$ aws sts get-caller-identity        

成功。AWSのアクセスキーは2つしか作成できないようなので注意が必要。

Terraform コマンドの実行

$ terraform plan -out=tfplan

$ terraform apply tfplan
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?