iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 13
0
DevOps

今晚我想來點 Terraform 佐 AWS系列 第 13

今晚我想透過使用者資料建立一台網頁伺服器

我們來實際用使用者資料設定虛擬機,以下是預計要讓使用者資料處理的工作:

  • 建立一個叫做 terraform 的使用者
  • 安裝 nginx
  • 放入一個 HTML 檔案

建立使用者資料

建立使用者資料的檔案 user_data.yaml

#cloud-config

# create users
users:
  - default
  - name: terraform
    sudo: ALL=(ALL) NOPASSWD:ALL
    shell: /bin/bash

# install nginx
package_update: true
packages:
  - nginx

# put html file
write_files:
  - path: /var/www/html/terraform.html
    content: |
      <h1>Provisioning via Terraform</h1>

設定組態檔

使用 template_file 這個 data 區塊來載入 user_data.yaml,再把載入的資料放到 aws_instanceuser_data 引數中。

data template_file 的引數:

  • template: 放模版資料,可以用 file() 函數來載入檔案。

上面的設定都放在 main.tf 裡面,完整檔案可以參考: https://github.com/nyogjtrc/practice-terraform/tree/master/web-server-user-data

data "template_file" "user_data" {
  template = file("user_data.yaml")
}

resource "aws_instance" "web" {
  ami           = var.ami
  instance_type = "t2.micro"

  key_name = aws_key_pair.practice.id

  vpc_security_group_ids = [
    aws_security_group.ssh.id,
    aws_security_group.web.id,
  ]

  subnet_id = aws_subnet.this.id

  user_data = data.template_file.user_data.rendered

  tags = {
    Name  = "Web-Terraform"
    topic = "web-server-user-data"
  }
}

執行

執行指令 terraform apply

$ terraform apply
...
Apply complete! Resources: 8 added, 0 changed, 0 destroyed.

Outputs:

vpc_id = vpc-0db96967262b14fcf
web_instance_id = i-008d3a7371fba33b2
web_public_ip = 18.177.119.161

使用者資料是在虛擬機建立之後才執行的,所以需要稍微等一下

aws 自動分配了 18.177.119.161 給虛擬機,在瀏覽器開啟 http://18.177.119.161/terraform.html 就可以看到我們剛剛放上去的檔案


上一篇
今晚我想打開神秘的使用者資料
下一篇
今晚我想認識 Terraform 的好伙伴 Packer
系列文
今晚我想來點 Terraform 佐 AWS30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言