LoginSignup
0
0

More than 1 year has passed since last update.

既存のサーバを Terraform で管理できるようにする

Posted at

Terraform で既存の AWS リソースを管理できるようにします。

Terraform で管理するリソースの確認

今回は以下の通り
- VPC
- subnet
- SecurityGroup
- Key Pair
- Elastic IP Address
- EC2

下準備

IAM ユーザーのアクセスキーを設定し、リソースへアクセスできるようにした準備を行います。
まず direnv をインストールします、以下の記事が参考になります。

direnv のインストールが完了したら、.envrcファイルを作成します。

.envrc
export AWS_ACCESS_KEY_ID = "{アクセスキーId}"
export AWS_SECRET_ACCESS_KEY="{シークレットアクセスキー}"

これで、.envrc以下の階層に入ると自動的に認証情報が適用されリソースへのアクセスが可能になります。

テンプレートの作成

公式ページで各リソースの基本的なテンプレートを確認。

VPC

VPC_BasicUsageWithTags
resource "aws_vpc" "main" {
  cidr_block       = "10.0.0.0/16"
  instance_tenancy = "default"

  tags = {
    Name = "main"
  }
}

subnet

subnet_BasicUsage
resource "aws_subnet" "main" {
  vpc_id     = aws_vpc.main.id
  cidr_block = "10.0.1.0/24"

  tags = {
    Name = "Main"
  }
}

まず VPC のテンプレートを作成する。
ローカルでvpc.tfを作成し、先程のコードをコピー。

vpc.tf
resource "aws_vpc" "main" {
  cidr_block       = "10.0.0.0/16"
  instance_tenancy = "default"

  tags = {
    Name = "main"
  }
}

テンプレートファイルの先頭でリソースの種類の指定と、名付けを行っています。
vpc.tfと同じ階層でterraform importを実行。
テンプレートファイルで指定したリソースの種類と名前、読み込むリソースの ID を指定して実行します。

terraform-server % ls
vpc.tf
terraform-server % terraform import aws_vpc.main {VPC ID}
aws_security_group_name: Importing from ID "xxxxxxxxxxxxxxxxxxxx"...
aws_security_group_name: Import prepared!
  Prepared aws_security_group for import
aws_security_group_name: Refreshing state... [id=xxxxxxxxxxxxxxxxxxxx]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

続いてterraform planを実行して現在の環境とvpc.tfの差分を確認します。
vpc.tfを編集し、terraform planの実行結果が以下のようになったら次のリソースのテンプレート作成に移ります。

terraform-server % terraform plan
aws_vpc.main: Refreshing state... [id=vpc-xxxxxxxx]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.

参考資料

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