使用 Ansible 创建混合 Spot/On-Demand 的 K8s 节点组。

解读

在国内云厂商(阿里云、腾讯云、华为云、AWS 中国)的面试场景里,这道题考察的是“用 Ansible 把不可变基础设施与成本优化结合起来”。
面试官希望你证明三点:

  1. 能用 Ansible 把节点组抽象成代码(IaC),而不是手工控制台点选;
  2. 能在同一条 Playbook 里同时创建 Spot 与 On-Demand 实例,并保证标签、污点、自动伸缩策略一致;
  3. 能处理国内云特有的坑:Spot 实例叫“抢占式实例”,5 分钟释放通知;国内账号默认没有 Spot 服务角色;部分可用区 Spot 库存不足;需要备案安全组等。

回答时务必体现“声明式终态”思想:Playbook 只描述“最终要几台 Spot、几台 On-Demand、打上什么标签”,而不写“先创建谁后创建谁”。

知识点

  • 动态库存插件:community.aws.aws_ec2、alicloud.ecs.ecs,用于把创建出来的实例实时拉入 Ansible 库存。
  • instance_market_options:AWS 的 Spot 参数;国内阿里云对应 spot_strategy=SpotWithPriceLimit。
  • mixed_instances_policy / auto_scaling_group:AWS 官方推荐用 ASG 混合实例策略;国内云直接用弹性伸缩组 + 多实例规格实现同等效果。
  • node_labels 与 taints:K8s 侧通过 kubelet --node-labels=node.kubernetes.io/lifecycle=spot 和 --register-with-taints=spotInstance=true:NoSchedule 把调度信息写死,防止业务 Pod 误跑。
  • 幂等校验:ec2_instance_info / ali_instance_info 模块的 filters="tag:NodeGroup=hybrid",保证重复跑 Playbook 不会多开机器。
  • 国内合规:按量付费实例必须绑定已备案的公网 IP 或 NAT 网关;Spot 实例释放前 5 分钟会触发云监控事件,需用 cloudwatch_event / 云监控函数 触发 Ansible Runner 做优雅排水(cordon + drain)。

答案

下面给出一条可在 AWS 中国宁夏区域(cn-northwest-1)直接跑的最小可复现 Playbook;如用阿里云,把模块换成 alicloud.ecs_instance 即可,逻辑不变。
核心思路:

  1. 用 mixed_instances_policy 一次性声明“80% Spot + 20% On-Demand”;
  2. 用 launch_template 把 kubelet 参数、标签、污点写进 UserData;
  3. 用 auto_scaling_group 保证节点组后续自动补容;
  4. 用 dynamic inventory 让新节点立即被 Ansible 纳管;
  5. 用 unique_tag 实现幂等,重复跑不会重复创建。
# group_vars/all
cluster_name: prod
node_group: hybrid
spot_percent: 80
on_demand_percent: 20
vpc_id: vpc-12345
subnet_ids: [subnet-12345, subnet-67890]
keypair: k8s-cn-northwest-1
image_id: ami-0c3c0f7f0c7c3f0c7  # 官方 EKS 优化镜像
security_group_ids: [sg-12345]
instance_types: [c6i.large, c5.large, c6a.large]  # 国内库存充足
kube_version: "1.28"
lifecycle_label: "node.kubernetes.io/lifecycle"
lifecycle_value_spot: "spot"
lifecycle_value_od: "on-demand"

# site.yml
- name: 创建混合 Spot/On-Demand K8s 节点组
  hosts: localhost
  gather_facts: no
  tasks:
    - name: 创建启动模板
      amazon.aws.ec2_launch_template:
        name: "{{ cluster_name }}-{{ node_group }}-lt"
        image_id: "{{ image_id }}"
        key_name: "{{ keypair }}"
        security_group_ids: "{{ security_group_ids }}"
        user_data: |
          MIME-Version: 1.0
          Content-Type: multipart/mixed; boundary="==MYBOUNDARY=="

          --==MYBOUNDARY==
          Content-Type: text/x-shellscript; charset="us-ascii"

          #!/bin/bash
          set -o xtrace
          /etc/eks/bootstrap.sh {{ cluster_name }}
          # 打标签和污点
          sed -i "/KUBELET_EXTRA_ARGS=/c\KUBELET_EXTRA_ARGS='--node-labels={{ lifecycle_label }}={{ lifecycle_value_spot }},nodegroup={{ node_group }} --register-with-taints={{ lifecycle_value_spot }}Instance=true:NoSchedule'" /etc/eks/bootstrap.sh
        tag_specifications:
          - resource_type: instance
            tags:
              Name: "{{ cluster_name }}-{{ node_group }}"
              NodeGroup: "{{ node_group }}"
              Cluster: "{{ cluster_name }}"
      register: lt

    - name: 创建混合实例策略 ASG
      community.aws.autoscaling_group:
        name: "{{ cluster_name }}-{{ node_group }}-asg"
        vpc_zone_identifier: "{{ subnet_ids }}"
        min_size: 3
        max_size: 30
        desired_capacity: 10
        mixed_instances_policy:
          launch_template:
            launch_template_specification:
              launch_template_id: "{{ lt.launch_template.launch_template_id }}"
              version: $Latest
          overrides:
            - instance_type: c6i.large
              weighted_capacity: "1"
            - instance_type: c5.large
              weighted_capacity: "1"
            - instance_type: c6a.large
              weighted_capacity: "1"
          instances_distribution:
            on_demand_allocation_strategy: prioritized
            on_demand_base_capacity: 0
            on_demand_percentage_above_base_capacity: "{{ 100 - spot_percent }}"
            spot_allocation_strategy: capacity-optimized
        tags:
          - key: Name
            value: "{{ cluster_name }}-{{ node_group }}"
            propagate_at_launch: yes
          - key: NodeGroup
            value: "{{ node_group }}"
            propagate_at_launch: yes
          - key: Cluster
            value: "{{ cluster_name }}"
            propagate_at_launch: yes
      register: asg

    - name: 等待 ASG 达到终态
      amazon.aws.ec2_instance_info:
        filters:
          "tag:NodeGroup": "{{ node_group }}"
          "instance-state-name": "running"
      register: instances
      until: instances.instances | length == asg.desired_capacity
      retries: 30
      delay: 20

    - name: 刷新动态库存
      meta: refresh_inventory

    - name: 对新节点做一致性校验
      hosts: tag_NodeGroup_{{ node_group }}
      gather_facts: no
      tasks:
        - name: 检查 kubelet 是否已注册
          command: kubectl get node {{ inventory_hostname }}
          delegate_to: localhost
          changed_when: false

跑完后,集群会出现 10 个节点,其中 8 台带 node.kubernetes.io/lifecycle=spot 标签和 spotInstance=true:NoSchedule 污点,2 台为普通 On-Demand。后续缩容、扩容、实例被回收,都由 ASG 自动补齐,Ansible 只需定期巡检漂移即可。

拓展思考

  1. 国内多云落地差异
    阿里云抢占式实例不支持 mixed_instances_policy,需要把 spot_strategy=SpotWithPriceLimit 写进 run_instances,同时用 ess 伸缩组 的 multiAZPolicy=COMPOSABLE 实现同等效果;华为云叫“竞价实例”,API 参数是 market_type=spot。
  2. 成本可观测
    建议把 spot_percent 做成 Ansible Survey 变量,结合 云监控账单 API 每月出报表,超预算自动调低 desired_capacity。
  3. 优雅下线
    Spot 实例释放前 5 分钟,云监控会推送 ecs:SpotInstanceInterruption 事件,可触发函数计算,函数里调用 Ansible Tower API 做 cordon + drain,比单纯靠 ASG 生命周期钩子更稳。
  4. GitOps 闭环
    把整条 Playbook 放进 ArgoCD ApplicationSet,节点组代码与业务 Helm Chart 同库,Pull Request 合并后自动跑 Ansible Job,实现“基础设施与业务应用同版本”。