3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

terraformローカル環境準備メモ

Last updated at Posted at 2022-02-09

概要

  • terraformローカル環境を整えるメモ
  • ローカルはMac

詳細

インストール

  • パッケージマネージャはasdfを使用している
  • 各自の環境に応じて読み替え
$ asdf plugin list
$ asdf latest terraform
$ asdf list
$ asdf install terraform latest
Downloading terraform version 1.1.5 from 
:
:
$ asdf global terraform  1.1.5
$ asdf current
:
terraform       1.1.5           /Users/.tool-versions
$ terraform -v
Terraform v1.1.5
on darwin_arm64
  • asdf ディレクトリごとに(モノレポなど)バージョン別れている場合はlocalで指定
~ $ asdf global terraform 1.5.0
~ $ asdf current            
:
terraform       1.5.0           /Users/.tool-versions

~/~/~/ $ asdf local terraform 1.5.0
~/~/~/ $ asdf current              
:
terraform       1.5.0           /Users/project/infra/tf/.tool-versions ★

git-secretsインストール

  • AWSのクレデンシャルをcommitしないような環境にしておく
% brew install git-secrets
% git secrets --register-aws --global
OK
$ git secrets --install ~/.git-templates/git-secrets 
✓ Installed commit-msg hook to /Users/.git-templates/git-secrets/hooks/commit-msg
✓ Installed pre-commit hook to /Users/.git-templates/git-secrets/hooks/pre-commit
✓ Installed prepare-commit-msg hook to /Users/.git-templates/git-secrets/hooks/prepare-commit-msg

$ git config --global init.templatedir ~/.git-templates/git-secrets

$ ls -l ~/.git-templates/git-secrets
total 0
drwxr-xr-x  5 staff  staff  160  2  8 19:33 hooks
  • commitが弾かれるか確認
$ mkdir test
$ cd test
$ vi credentials 
[default]
aws_access_key_id = AKIA****************
aws_secret_access_key = ******34VWhDYZlcoZNob7fABb4Qj6pTE0******
$ git init
$ git add .
$ git commit -m "credentials commit test"
credentials:2:aws_access_key_id = **********************
credentials:3:aws_secret_access_key = ******************************

[ERROR] Matched one or more prohibited patterns

Possible mitigations:
- Mark false positives as allowed using: git config --add secrets.allowed ...
- Mark false positives as allowed by adding regular expressions to .gitallowed at repository's root directory
- List your configured patterns: git config --get-all secrets.patterns
- List your configured allowed patterns: git config --get-all secrets.allowed
- List your configured allowed patterns in .gitallowed at repository's root directory
- Use --no-verify if this is a one-time false positive
$ cd ..
$ rm -fr test

動作確認

  • EC2をAmazonLinux2の公式AMIでデフォルトVPCに作成する
  • tfファイル作成
main.tf
variable "aws_access_key" {}
variable "aws_secret_key" {}

provider "aws" {
  profile = "terraform"
  region = "ap-northeast-1"
  access_key = var.aws_access_key
  secret_key = var.aws_secret_key
}

resource "aws_instance" "hello-world" {
  ami = "ami-08a8688fb7eacb171"
  subnet_id = "subnet-************"
  instance_type = "t2.micro"
}
  • terraform.tfvars作成
terraform.tfvars
aws_access_key = "************************"
aws_secret_key = "************************"
  • 適用後インスタンスIDを確認しマネジメントコンソールと比較
$ terraform plan
$ terraform apply
:
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

$ grep -w id terraform.tfstate
            "id": "i-************,
  • 削除
$ terraform destroy

参考:遭遇しがちエラーまとめ

1.ロックファイル

 Error: Inconsistent dependency lock file
│ 
│ The following dependency selections recorded in the lock file are inconsistent with the current configuration:
│   - provider registry.terraform.io/hashicorp/aws: required by this configuration but no version is selected
│ 
│ To make the initial dependency selections that will initialize the dependency lock file, run:
│   terraform init
  • 以下で対応
% terraform providers lock \
  -platform=darwin_amd64 \
  -platform=linux_amd64

2.ロックファイル

│ Error: Required plugins are not installed
│ 
│ The installed provider plugins are not consistent with the packages selected in the dependency lock file:
│   - registry.terraform.io/hashicorp/aws: there is no package for registry.terraform.io/hashicorp/aws 3.74.1 cached in .terraform/providers
│ 
  • 以下で対応
% terraform init

3.クレデンシャルが読めない

Error: error configuring Terraform AWS Provider: no valid credential sources for Terraform AWS Provider found.
│ 
│ Please see https://registry.terraform.io/providers/hashicorp/aws
│ for more information about providing credentials.
  • 以下で対応
% export AWS_ACCESS_KEY_ID=AKIA6MHAUAV3IQTYEIII
% export AWS_SECRET_ACCESS_KEY=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

4.クレデンシャルが読めない

Error: error configuring Terraform AWS Provider: error validating provider credentials: error calling sts:GetCallerIdentity: SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.status code: 403, request id: 1d5eb251-0122-475d-b660-872daa43bc77
  • 以下で対応
$ vi terraform.tfvars
:
aws_access_key = "XXXXXXXXXXXXXXXX"
aws_secret_key = "XXXXXXXXXXXXXXXXXXXXXXXXX"

$ vi main.tf
variable "aws_access_key" {}
variable "aws_secret_key" {}

provider "aws" {
  profile = "terraform"
  region = "ap-northeast-1"
  access_key = var.aws_access_key
  secret_key = var.aws_secret_key
}

5.ネットワーク

  • デフォルトVPCで作る場合サブネットを指定
Error: Error launching source instance: MissingInput: No subnets found for the default VPC 'vpc-d32ba5b7'. Please specify a subnet.status code: 400, request id: c7c75eda-f88a-4fa7-96bc-88375db7c944
main.tf
resource "aws_instance" "hello-world" {
  ami = "ami-08a8688fb7eacb171"
  subnet_id = "subnet-XXXXXXXXXXXXXXXX"⇐ココ指定
  instance_type = "t2.micro"
}

6.asdf絡み

  • 実行できるterraformがないとのこと
$ terraform plan 
No terraform executable found for terraform 1.2.0
  • 結局入れ直しでしか解決できなかった
$ asdf plugin remove terraform
$ asdf plugin add terraform
$ asdf list
:
:
terraform
  No versions installed
$ asdf install terraform latest ※最新駄目?
$ terraform -v
No preset version installed for command terraform
Please install a version by running one of the following:

asdf install terraform 1.2.0

$ asdf install terraform 1.2.0
$ asdf list
:
:
terraform
  1.2.0
  1.4.6
  
$ terraform -v
Terraform v1.2.0
on darwin_arm64
+ provider registry.terraform.io/hashicorp/archive v2.3.0
+ provider registry.terraform.io/hashicorp/aws v4.49.0

$ terraform plan                            
$ terraform init

参考:main.tfサンプル

main.tf
variable "aws_access_key" {}
variable "aws_secret_key" {}

provider "aws" {
  profile = "terraform"
  region = "ap-northeast-1"
  access_key = var.aws_access_key
  secret_key = var.aws_secret_key
}

resource "aws_instance" "hello-world" {
  ami = "ami-XXXXXXXXXXX"
  subnet_id = "subnet-XXXXXXXXXXX"
  instance_type = "t2.micro"
  tags = {
    "Name" = "terraform-test"
  }
  user_data = <<EOF
  #!/bin/bash
  amazon-linux-extras install -y nginx1.12
  systemctl start nginx
  EOF
}
  • terrafom用.gitignore作成

  • 各ファイル整形
$ terraform fmt
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?