Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[Terraform] – Terraform Beginner – Lesson 5: Terraform Provisioners and creating EC2

Posted on May 3, 2022June 5, 2022 By nim No Comments on [Terraform] – Terraform Beginner – Lesson 5: Terraform Provisioners and creating EC2

Contents

Toggle
  • 1) Introduction to AWS EC2
  • 2) AWS EC2 with Terraform
    • 2.1) Create Instance Ubuntu
    • 2.2) add Public key to VM
    • 2.3) Configure Security Group.
    • 2.4) Get IP Public
  • 3) Terraform Provisioners
    • 3.1) Remote Exec
    • 3.2) Local Exec
    • 3.3) Destroy Time Provisioner
    • 3.4) Failure Behavior
    • 3.5) Best Practice for Provisioner.

1) Introduction to AWS EC2

Nhắc đến EC2 thì anh em hiểu đơn giản đó là một máy áo trên AWS.

Nếu anh em còn xa lạ với Ec2 thì coi clip bên dưới.

Anh em có thể làm theo video để hiểu thêm.

Tiếp đến là anh em tìm hiểu về AMI.

Nếu như anh em đã tạo ami trên web console và anh em có để ý thì cũng có 1 phần chọn ami

Hoặc bạn có thể sử dụng các AMI có sẵn của AWS như hình bên dưới.

mình có lướt sơ thì có khá nhiều bài viết nói về AMI là gì?

Mình tóm đơn giản.
Nếu bạn cài win cho laptop thì bạn sẽ cấn đĩa có file ISO windows đúng hem?
Còn tạo VM trên AWS thì bạn cần đến AMI vì trong AMI nó có thông tin hệ điều hành như là: ubuntu, centos, windows11, … và 1 số thông tin khác.

Ở bài lab này mình đang cần tạo VM ubuntu. vì học hành nên chúng ta chọn các ami có chữ Free tier eligible

2) AWS EC2 with Terraform

2.1) Create Instance Ubuntu

Ở ảnh trên bạn cần nhờ Virtualization Types là Hardware Virtual Machine (HVM) hay Paravirtual (PV)

Cái mình chọn là HVM.

Chúng ta chuyển qua tab community để tìm tìm các thông số cần thiết.

###main.tf
##########

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20220420"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"]
}


resource "aws_instance" "webserver" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"

  tags = {
    Name = "webserver"
    Desciption = "A Nginx Webserver on Ubuntu" 
  }
  user_data = <<-EOF
                #!/bin/bash
                sudo apt update -y
                sudo apt install nginx -y
                systemctl enable nginx
                systemctl start nginx
                EOF
}

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

Nếu anh em apply chúng ta sẽ có 1 VM ubuntu

2.2) add Public key to VM

Vấn đề tiếp theo là làm sao ssh vào vm được?

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

Bạn cần thêm public key cho VM

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20220420"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"]
}


resource "aws_instance" "webserver" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"

  tags = {
    Name = "webserver"
    Desciption = "A Nginx Webserver on Ubuntu" 
  }
  user_data = <<-EOF
                #!/bin/bash
                sudo apt update -y
                sudo apt install nginx -y
                systemctl enable nginx
                systemctl start nginx
                EOF
    key_name = aws_key_pair.web.id
}

resource "aws_key_pair" "web" {
  key_name   = "web-key"
  public_key = file("id_rsa.pub")
}

tiếp tục terraform apply

Đã có key Pair
Tạo 1 instance mới xong đó xoá instance cũ
Instance mới đã được add key pair

2.3) Configure Security Group.

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

Giờ mình cần cấu hình security hay còn gọi là firewall.
Cho phép ssh từ internet vào thì nó là ingress

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-20220420"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"]
}


resource "aws_instance" "webserver" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"

  tags = {
    Name = "webserver"
    Desciption = "A Nginx Webserver on Ubuntu" 
  }
  user_data = <<-EOF
                #!/bin/bash
                sudo apt update -y
                sudo apt install nginx -y
                systemctl enable nginx
                systemctl start nginx
                EOF
    key_name = aws_key_pair.web.id
    vpc_security_group_ids = [aws_security_group.ssh-access.id]
}

resource "aws_key_pair" "web" {
  key_name   = "web-key"
  public_key = file("id_rsa.pub")
}

resource "aws_security_group" "ssh-access" {
  name = "ssh-access"
  description = "Allow SSH access from the Internet"

  ingress {
    from_port        = 22
    to_port          = 22
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }
}

Tiếp tục terraform apply.

đã tao Security Group
Instance đã được add security group.

2.4) Get IP Public

Giờ muốn ssh vào server để kiểm tra thì chúng ta cần có được ip public của server.

Cách thứ nhất là lên web nhìn.

Cách tiếp theo có vẻ pro hơn. thêm output vào cuối file.

output public-ip {
  value       = aws_instance.webserver.public_ip
}
rồi chạy terraform apply.

Giờ thực hiện ssh vào VM

ssh -i .ssh/id_rsa ubuntu@18.144.4.79

3) Terraform Provisioners

Provisioners can be used to model specific actions on the local machine or on a remote machine in order to prepare servers or other infrastructure objects for service.

3.1) Remote Exec

Khi thực hiện create VM bằng terraform thì bạn cũng có thể run các command trên instance vừa được tạo.

3.2) Local Exec

3.3) Destroy Time Provisioner

3.4) Failure Behavior

Ở case on_failure = fail

terraform sẽ báo lỗi nếu không run được command.
Instance đã được create trước khi run command

Ở case on_failure = continue

Bạn sẽ thấy terraform như là ingnored luôn khi mà command run fail

3.5) Best Practice for Provisioner.

AWS - Amazon Web Service, Uncategorized

Post navigation

Previous Post: [Terraform] – Terraform Beginner – Lesson 4: Remote State
Next Post: [Terraform] – Terraform Beginner – Lesson 6: Terraform Import, Tainting Resources, and Debugging

More Related Articles

[Jenkins] Share Libraries 6: Closures Jenkins
[Terraform] – Terraform Beginner – Lesson 2: Working with Terraform. AWS - Amazon Web Service
[EKS/ S3 Mount Point] Create a Persistent Volume on EKS using an S3 Bucket. AWS - Amazon Web Service
Policies as Code in Kubernetes using jsPolicy Kubernetes
[AWS] EKS IAM Roles for Service Accounts (IRSA) using Terraform AWS - Amazon Web Service
[eks] Kubernetes Cluster-AutoScaler error: Failed to watch *v1.CSIDriver AWS - Amazon Web Service

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Laravel] Laravel Helpful June 26, 2025
  • [VScode] Hướng dẫn điều chỉnh font cho terminal June 20, 2025
  • [WordPress] Hướng dấn gửi mail trên WordPress thông qua gmail. June 15, 2025
  • [Bitbucket] Git Clone/Pull/Push with Bitbucket through API Token. June 12, 2025
  • [Teamcity] How to transfer the value from pipeline A to pipeline B June 9, 2025

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.