DevOps/Terraform

[Terraform] Security Group과 Remote-exec의 관계

Background

  • Security Group의 Inbound Rule에 대한 description과 몇몇의 규칙을 수정한 후 생긴 문제이다.
  • 평소처럼 terraform apply 를 통해 Provisioning 중에 특정 null_resource가 Still creating을 반복하는 문제가 발생했다.
  • null_resource의 의존성 문제 (depend_on)은 수정한적이 없다. 즉, 이전에는 정상작동했다.

 

Solution

한 가지 null_resource를 예로 들어보자면

resource "null_resource" "web_env" {
  depends_on = [aws_instance.web]
  count = length(var.availability_zones)

  connection {
    user = var.remote_user
    type = "ssh"
    host = aws_instance.web[count.index].public_ip
    private_key = file("~/.ssh/${var.key_pair}.pem")
    timeout = "10m"
  }

  provisioner "remote-exec" {
    inline = [
      "sudo dnf install python3 -y",
      "sudo dnf install mysql -y",
      "sudo dnf install expect -y", # expect package for Automation Some commands output to input
    ]
  }
}
  • "remote-exec"를 위해서는 반드시 connection {} 이 필요하다.
    여기서는 ssh connection을 key 교환을 통해 ec2 instance와 연결하여 provisioner "remote-exec"{} 가 실행된다.
  • 문제가 발생하기 전 마지막으로 수정했던 부분이 현재 Terraform과 Ansible을 통해서 Project를 진행하고 있어서 WEB Instance에 대해서 SSH 연결은 Ansible master Node만 허락하도록 변경했었다.
  • 즉, Terraform이 Provisioning을 위한 SSH 연결은 Inbound rule에 등록되지 않아 계속 연결을 반복하게 된다.

 

💡기존의 Inbound Rule을 변경한다.

ingress {
-   description = "SSH from Ansible Security group"
+   description = "SSH from Anywhere"
    from_port = 22
    to_port = 22
    protocol = "tcp"
-   security_groups = [aws_security_group.ans_sg.id] # 기존 ansible에서의 ssh inbound만 허락
+   cidr_blocks = ["0.0.0.0/0"] # ssh from Anywhere
}