[컴] terraform 에서 cloud-init 사용

테라폼 / 초기 설정 / init / cloud init / terraform cloud

terraform 에서 cloud-init 사용

terraform 에서 docker 설치와 swap file 생성을 instance 생성시에 하려한다. cloud-init 에 사용한 명령어들에 대한 자세한 설명은 아래 링크들을 참고하면 된다.

# init-cloud.yml

packages:
  - ca-certificates
  - curl
  - gnupg

# create the docker group
groups:
  - docker

# Add default auto created user to docker group
system_info:
  default_user:
    groups: [docker]

# ----------------------------------------
# Mount attached disk
#
# '/dev/sdf' should exist
#
bootcmd:
 - test -z "$(blkid /dev/sdf)" && mkfs -t ext4 -L mylabel /dev/sdf
 - mkdir -p /mydata

mounts:
 - [ "/dev/sdf", "/mydata", "ext4", "defaults,nofail", "0", "2" ]
# ----------------------------------------

runcmd:
# Install Docker, for production, consider pinning to stable versions  
  - install -m 0755 -d /etc/apt/keyrings
  - curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
  - chmod a+r /etc/apt/keyrings/docker.gpg
  - echo "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
  - apt-get update -y
  - apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  - systemctl start docker
  - systemctl enable docker
# Enable and activate the swap file
  - dd if=/dev/zero of=/swapfile bs=128M count=16 # 2GB = 128M x 16
  - chmod 600 /swapfile
  - mkswap /swapfile
  - swapon /swapfile
  - echo '/swapfile swap swap defaults 0 0' >> /etc/fstab
# ----------------------------------------------------
#
# data
#
# ----------------------------------------------------
data "template_file" "my_cloud_userdata" {
  template = file("./scripts/init-cloud.yml")
}

# ----------------------------------------------------
#
# resource
#
# ----------------------------------------------------

resource "aws_instance" "tf-test" {
  ...

  # This only works at the time the aws_inatance is created.
  # So if you want to use a new init script, 
  # you may need to destroy and recreate the instance.
  user_data = data.template_file.my_cloud_userdata.rendered
}

See Also

  1. 쿠…sal: [컴] Terraform 사용법
  2. Testing and debugging cloud-init — cloud-init 20.4.1 documentation

댓글 없음:

댓글 쓰기