传统运维 - Packer + Ansible

2023-08-08

目录结构如下:

/opt/packer/
├── ansible
│   ├── roles
│   │   ├── node_exporter # 通用
│   │   │   ├── files
│   │   │   └── tasks
│   │   │       └── main.yaml
│   │   ├── prepare # 通用
│   │   │   ├── files
│   │   │   │   └── authorized_keys
│   │   │   └── tasks
│   │   │       └── main.yaml
│   │   ├── tencent-TKE4 # 腾旭云tke4镜像独属
│   │   │   ├── files
│   │   │   └── tasks
│   │   │       └── main.yaml
│   │   └── tencent-ubuntu22 # 腾旭云ubuntu22镜像独属
│   │       ├── files
│   │       └── tasks
│   │           └── main.yaml
│   ├── tencent-TKE4.yaml # TKE4.pkr.hcl使用
│   └── tencent-ubuntu22.yaml # ubuntu22.pkr.hcl使用
└── tencent
├── plugins.pkr.hcl # 三方插件
├── TKE4.pkr.hcl # 用于生成TKE4镜像
└── ubuntu22.pkr.hcl # 用于生成ubuntu22镜像

Packer配置,功能描述

  1. AK/SK使用服务器环境变量
  2. 基于公共镜像“img-eb30mz89”为基础,在广州,创建临时服务器
  3. 使用ansible在临时服务器上进行初始化
  4. 初始化完毕后生成镜像
  5. 镜像完成后同步至上海、北京、成都、香港
# https://developer.hashicorp.com/packer/plugins/builders/tencentcloud
source "tencentcloud-cvm" "root" {
  source_image_id             = "img-eb30mz89"
  disk_size                   = 20
  disk_type                   = "CLOUD_SSD"
  communicator                = "ssh"
  secret_id                   = var.TENCENT_AK
  secret_key                  = var.TENCENT_SK
  image_name                  = var.IMAGE_NAME
  instance_name               = var.IMAGE_NAME
  region                      = "ap-guangzhou"
  zone                        = "ap-guangzhou-6"
  instance_type               = "SA3.MEDIUM4"
  ssh_username                = "root"
  ssh_port                    = 22
  force_poweroff              = true
  associate_public_ip_address = true
  internet_max_bandwidth_out  = 100
  vpc_id                      = "vpc-mkcfuuv9"
  subnet_id                   = "subnet-5wxsh318"
  security_group_id           = "sg-q8ap75nt"
  image_copy_regions          = ["ap-shanghai", "ap-beijing", "ap-chengdu", "ap-hongkong"]
}

build {
  sources = [
    "source.tencentcloud-cvm.root"
  ]

  provisioner "ansible" {
    playbook_file = "/opt/packer/ansible/tencent-TKE4.yaml"
  }
}


variable "TENCENT_AK" {
  type    = string
  default = env("TENCENT_AK")
}

variable "TENCENT_SK" {
  type    = string
  default = env("TENCENT_SK")
}

variable "IMAGE_NAME" {
  type    = string
  default = "image"
}

使用方式:

如创建腾讯云TKE4镜像,则

cd /opt/packer/tencent
packer build  -var 'IMAGE_NAME=TKE4-20230808'  TKE.pkr.hcl

标题:传统运维 - Packer + Ansible
地址:https://blog.njqhome.com:8443/articles/2023/08/08/1691482014532.html