【Terraform】004. EC2インスタンスのプロビジョニングでキーペアを指定する - AWS


はじめに

本投稿では、EC2インスタンスをプロビジョニングする際にSSHキーペアを指定する方法について記載しています。

作業環境

$  hostnamectl status
 Static hostname: terraform
       Icon name: computer-container
         Chassis: container
      Machine ID: ---
         Boot ID: ---
  Virtualization: lxc
Operating System: Ubuntu 22.04 LTS                
          Kernel: Linux 5.4.0-113-generic
    Architecture: x86-64

※ SHELLは、Bashを利用しています。

設定例

既存の登録済みキーペアを指定


「aws_instance」の「key_name」に登録済みのキーペア名を指定します。

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
  # 東京リージョン
  region = "ap-northeast-1"
}

resource "aws_instance" "app_server" {
  # Canonical, Ubuntu, 22.04 LTS, amd64 jammy image build on 2022-06-09
  ami           = "ami-07200fa04af91f087"
  instance_type = "t2.micro"

  # 登録済みのSSHキーペア名を指定
  key_name      = "awskey"

  tags = {
    Name = "ExampleAppServerInstance"
  }
}

新規にキーペアを登録及び指定


「aws_instance」の「key_name」に登録済みのキーペア名を指定します。

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.16"
    }
  }

  required_version = ">= 1.2.0"
}

provider "aws" {
  # 東京リージョン
  region = "ap-northeast-1"
}

resource "aws_instance" "app_server" {
  # Canonical, Ubuntu, 22.04 LTS, amd64 jammy image build on 2022-06-09
  ami           = "ami-07200fa04af91f087"
  instance_type = "t2.micro"

  # aws_key_pairで新規登録したキーペアのIDを指定
  key_name      = aws_key_pair.app_server.id

  tags = {
    Name = "ExampleAppServerInstance"
  }
}

resource "aws_key_pair" "app_server" {
  key_name   = "awskey"
  public_key = file("./awskey.pub")
}

参考サイト