본문 바로가기
Infra/Terraform

Terraform으로 AWS Key Pair 등록하기

by devson 2021. 11. 19.

AWS에서 Key Pair를 생성하고 이를 다운받아 사용할 수 있지만, 반대로 내가 생성한 Key Pair를 AWS에 등록해서 사용할 수도 있다.

이번 포스팅에서는 Key Pair를 생성하고 Terraform을 통해 AWS에 Key Pair를 등록하는 과정에 대해 알아보도록 하겠다.

 

ssh-keygen을 통한 Key Pair 생성

ssh-keygen을 통해 Key Pair를 생성한다.

나는 tf-key-pair라고 이름을 짓도록 하겠다.

# -t: 암호화 타입
# -b: 비트 수
# -C: 코멘트
# -f: 파일 저장 경로
# -N: 암호화 옵션
$ ssh-keygen -t rsa -b 4096 -C "" -f "{저장하고자하는 경로}/tf-key-pair" -N ""


# key pair 확인
$ ls {저장하고자하는 경로}
tf-key-pair  tf-key-pair.pub

 

위와 같이 private key인 tf-key-pair와 public-key인 tf-key-pair.pub가 생성된 것을 확인할 수 있다.

 

Terraform 코드 작성

Terraform Registry에서 Resource를 제공하기 때문에 이를 사용하여 Key Pair를 import하는 코드를 작성하도록 하겠다.

 

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/key_pair

 

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/key_pair

 

registry.terraform.io

 

# aws provider 설정
provider "aws" {
  region = "ap-northeast-2"
}

# aws_key_pair resource 설정
resource "aws_key_pair" "terraform-key-pair" {
  # 등록할 key pair의 name
  key_name   = "tf-key-pair"
  
  # public_key = "{.pub 파일 내용}"
  public_key = file("{.pub 파일 경로}/.ssh/tf-key-pair.pub")
  
  tags = {
  	description = "terraform key pair import"
  }
}

 

AWS Credential 관련해서는 여러가지 설정이 있지만 간단하게 Access Key로 설정하고 싶다면 AWS provider 관련해서 아래를 참고하자

https://registry.terraform.io/providers/hashicorp/aws/latest/docs#static-credentials

https://registry.terraform.io/providers/hashicorp/aws/latest/docs#environment-variables

 

위 Terraform 코드에서 public_key 인자는 .pub 파일의 내용(지금 예제에서는 ssh-rsa로 시작하는) 자체를 입력해도 되고, .pub 파일의 경로를 지정해도 된다.

 

Terraform을 통한 AWS Key Pair 등록

Key Pair 생성과 코드 작성은 다 했으니 이제 등록만하면 된다.

 

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/aws...
- Installing hashicorp/aws v3.66.0...
- Installed hashicorp/aws v3.66.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

 

$ terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_key_pair.terraform-key-pair will be created
  + resource "aws_key_pair" "terraform-key-pair" {
      + arn             = (known after apply)
      + fingerprint     = (known after apply)
      + id              = (known after apply)
      + key_name        = "tf-key-pair"
      + key_name_prefix = (known after apply)
      + key_pair_id     = (known after apply)
      + public_key      = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDPyfFBccvEZNMo/xnrA1lQNf6g9/grhgPwM1uJHEi3DSTU15vHWA6NXjLhgZH+A4wgrWgRhg/pb2iLa0snWJWLdB92Iad3dknSp3Nquz3kJma3PBfV8WPHduYu20fGL76L1SmB4jYEu/flE0mnCyIUoI1bsKz8vAl7tM+S8DpkfaPG7FXMEgy3E12Ct99CmLFd5ceoluEzRVwIaN705nYN5R3Q3RZIVptsGn/kjD2BwyR2yToSTHhA/eSWGgPF2ASOnFGM5QxOY1UzUqFAqFCW0h1o/iMqb/E4+VfIazK2lSohPdZu67PXEQEJF9zBAgDCbJfDMgSy+eEWUpHVZcg/sYPl794mDX5jtW5/1ejCbPc9xG4TylMQzRIKGG30qG1QqlsRxMUNzLYf19szjaHbxF4SBgvnVpXooRabixoW8SCicA33QubpEK8PWk1oSxNxgPDspKs6I4kOyTNrOgpNLMCOFxT0ttl6lwHxj988TA6mY7rHB01xmLjWPrrCGBxQpRh329KzaIgJu+UBX0vXjAxKxriv25qZoc6qmSaTRtCrBV08FMJuY7zYWVVYZmYh3VidKsodl7vx3DF2WPvtxQTnca857iXgJMRxUIxEnbrgjY9eB7ElA/3kVd4cu4nJ4M04NTCgrRh7EmR1Y0pXxkE3ZIGX6Nn71RzQrg8nLQ=="
      + tags            = {
          + "description" = "terraform key pair import"
        }
      + tags_all        = {
          + "description" = "terraform key pair import"
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

 

$ terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_key_pair.terraform-key-pair will be created
  + resource "aws_key_pair" "terraform-key-pair" {
      + arn             = (known after apply)
      + fingerprint     = (known after apply)
      + id              = (known after apply)
      + key_name        = "tf-key-pair"
      + key_name_prefix = (known after apply)
      + key_pair_id     = (known after apply)
      + public_key      = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDPyfFBccvEZNMo/xnrA1lQNf6g9/grhgPwM1uJHEi3DSTU15vHWA6NXjLhgZH+A4wgrWgRhg/pb2iLa0snWJWLdB92Iad3dknSp3Nquz3kJma3PBfV8WPHduYu20fGL76L1SmB4jYEu/flE0mnCyIUoI1bsKz8vAl7tM+S8DpkfaPG7FXMEgy3E12Ct99CmLFd5ceoluEzRVwIaN705nYN5R3Q3RZIVptsGn/kjD2BwyR2yToSTHhA/eSWGgPF2ASOnFGM5QxOY1UzUqFAqFCW0h1o/iMqb/E4+VfIazK2lSohPdZu67PXEQEJF9zBAgDCbJfDMgSy+eEWUpHVZcg/sYPl794mDX5jtW5/1ejCbPc9xG4TylMQzRIKGG30qG1QqlsRxMUNzLYf19szjaHbxF4SBgvnVpXooRabixoW8SCicA33QubpEK8PWk1oSxNxgPDspKs6I4kOyTNrOgpNLMCOFxT0ttl6lwHxj988TA6mY7rHB01xmLjWPrrCGBxQpRh329KzaIgJu+UBX0vXjAxKxriv25qZoc6qmSaTRtCrBV08FMJuY7zYWVVYZmYh3VidKsodl7vx3DF2WPvtxQTnca857iXgJMRxUIxEnbrgjY9eB7ElA/3kVd4cu4nJ4M04NTCgrRh7EmR1Y0pXxkE3ZIGX6Nn71RzQrg8nLQ=="
      + tags            = {
          + "description" = "terraform key pair import"
        }
      + tags_all        = {
          + "description" = "terraform key pair import"
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes  # <==== "yes" 입력

aws_key_pair.terraform-key-pair: Creating...
aws_key_pair.terraform-key-pair: Creation complete after 0s [id=tf-key-pair]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

 

apply가 정상적으로 되었다면 AWS console EC2 대시보드를 통해 Key Pair가 정상적으로 등록되었는지 확인해보자.

tf-key-pair가 잘 등록되었다면 tag도 아마 잘 등록되어있을 것이다.

 

실습을 마쳤다면 해당 리소스를 제거하도록 하자.

$ terraform destroy
aws_key_pair.terraform-key-pair: Refreshing state... [id=tf-key-pair]

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  # aws_key_pair.terraform-key-pair will be destroyed
  - resource "aws_key_pair" "terraform-key-pair" {
      - arn         = "arn:aws:ec2:ap-northeast-2:157697218497:key-pair/tf-key-pair" -> null
      - fingerprint = "26:aa:70:ce:2a:ce:c6:c7:51:b7:97:95:a8:5e:ea:b4" -> null
      - id          = "tf-key-pair" -> null
      - key_name    = "tf-key-pair" -> null
      - key_pair_id = "key-0dc3ee2590f2860ea" -> null
      - public_key  = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDPyfFBccvEZNMo/xnrA1lQNf6g9/grhgPwM1uJHEi3DSTU15vHWA6NXjLhgZH+A4wgrWgRhg/pb2iLa0snWJWLdB92Iad3dknSp3Nquz3kJma3PBfV8WPHduYu20fGL76L1SmB4jYEu/flE0mnCyIUoI1bsKz8vAl7tM+S8DpkfaPG7FXMEgy3E12Ct99CmLFd5ceoluEzRVwIaN705nYN5R3Q3RZIVptsGn/kjD2BwyR2yToSTHhA/eSWGgPF2ASOnFGM5QxOY1UzUqFAqFCW0h1o/iMqb/E4+VfIazK2lSohPdZu67PXEQEJF9zBAgDCbJfDMgSy+eEWUpHVZcg/sYPl794mDX5jtW5/1ejCbPc9xG4TylMQzRIKGG30qG1QqlsRxMUNzLYf19szjaHbxF4SBgvnVpXooRabixoW8SCicA33QubpEK8PWk1oSxNxgPDspKs6I4kOyTNrOgpNLMCOFxT0ttl6lwHxj988TA6mY7rHB01xmLjWPrrCGBxQpRh329KzaIgJu+UBX0vXjAxKxriv25qZoc6qmSaTRtCrBV08FMJuY7zYWVVYZmYh3VidKsodl7vx3DF2WPvtxQTnca857iXgJMRxUIxEnbrgjY9eB7ElA/3kVd4cu4nJ4M04NTCgrRh7EmR1Y0pXxkE3ZIGX6Nn71RzQrg8nLQ==" -> null
      - tags        = {
          - "description" = "terraform key pair import"
        } -> null
      - tags_all    = {
          - "description" = "terraform key pair import"
        } -> null
    }

Plan: 0 to add, 0 to change, 1 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes    # <=== "yes" 입력

aws_key_pair.terraform-key-pair: Destroying... [id=tf-key-pair]
aws_key_pair.terraform-key-pair: Destruction complete after 0s

Destroy complete! Resources: 1 destroyed.

 

Key Pair 삭제 확인

 

 


 

이상으로 Terraform를 통해 AWS Key Pair를 등록하는 방법에 대해 알아보았다.

댓글