You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Ansible编辑LXC容器内的/etc/netplan/50-cloud-init.yaml文件

解决方案

首先前提:你需要提前安装Ansible的community.general扩展集合,执行命令:
ansible-galaxy collection install community.general

你之前用到的container_config模块是用于修改LXD层面的容器配置(比如资源限制、硬件挂载等宿主机侧配置),无法修改容器内部的文件,你可以选择以下两种方案完成需求:

方案1:直接在现有创建容器的Playbook后追加任务(最适配现有流程)

你可以直接在原有创建容器的任务后,新增两个任务,分别完成配置写入和配置生效操作,完整追加的Playbook内容如下:

# 接原有创建容器的任务之后
- name: 写入自定义Netplan配置到LXD容器
  become: True
  community.general.lxd_file:
    container: "{{ lxc_CT_NAME }}"
    path: /etc/netplan/50-cloud-init.yaml
    mode: "0644"
    force: yes
    content: |
      network:
        version: 2
        renderer: networkd
        ethernets:
          eth0:
            addresses:
              - 192.168.100.119/24
            gateway4: 192.168.100.11
            mtu: 1400
            nameservers:
                addresses:
                - 208.**.222.***
                - 208.**.***.220
  when: container_created.changed

- name: 应用Netplan配置使静态IP生效
  become: True
  community.general.lxd_exec:
    container: "{{ lxc_CT_NAME }}"
    command: netplan apply
  when: container_created.changed

方案2:将LXD容器纳入Ansible托管(适合需要频繁操作容器内部的场景)

你可以将LXD容器添加到Ansible的Inventory清单中,使用LXD连接协议直接操作容器,和操作普通物理机/虚拟机逻辑完全一致:

  1. 编辑Inventory文件添加容器配置:
[lxd_containers]
{{ lxc_CT_NAME }} ansible_connection=lxd ansible_user=root
  1. 编写单独的Playbook修改配置:
- name: 配置LXD容器静态IP
  hosts: lxd_containers
  tasks:
    - name: 修改Netplan配置文件
      copy:
        content: |
          network:
            version: 2
            renderer: networkd
            ethernets:
              eth0:
                addresses:
                  - 192.168.100.119/24
                gateway4: 192.168.100.11
                mtu: 1400
                nameservers:
                    addresses:
                    - 208.**.222.***
                    - 208.**.***.220
        dest: /etc/netplan/50-cloud-init.yaml
        mode: 0644
    - name: 应用网络配置
      command: netplan apply

内容的提问来源于stack exchange,提问作者Oleg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:36:04