【Vagrant+VirtualBox创建自动化虚拟环境】Ansible测试Playbook

文章目录

Vagrant

Vagrant是一个基于Ruby的工具,用于创建和部署虚拟化开发环境。它使用Oracle的开源VirtualBox虚拟化系统,使用 Chef创建自动化虚拟环境

Documentation | Vagrant | HashiCorp Developer官方手册

HashiCorp Cloud Platform-Vagrant查询镜像网站

安装vagrant

Install | Vagrant | HashiCorp Developer

安装 VirtualBox

Oracle VirtualBox

启动报错Error relaunching VirtualBox VM process: 5

  • 避坑!注意卸载完美平台再启动恢复(不玩cs无视之)

如何使用

ruby 复制代码
如何在 Vagrant 中使用这个盒子
第 1 步
选项 1:创建 Vagrantfile 并启动 box (Windows用cmd)

vagrant init bento/ubuntu-20.04 --box-version 202407.23.0

选项 2:打开 Vagrantfile 并将内容替换为以下内容
#-----------------------s-----------------------------
hosts = {
  "host1" => "192.168.0.221",
  "host2" => "192.168.0.222",
  "host3" => "192.168.0.223"
}

Vagrant.configure("2") do |config|
  hosts.each do |name, ip|
    config.vm.define name do |machine|
      machine.vm.box = "bento/ubuntu-20.04"
	  machine.vm.box_version = "202407.23.0"
      machine.vm.hostname = "%s" % name
      machine.vm.network :public_network,bridge: "en1", ip: ip
      machine.vm.provider "virtualbox" do |v|
          v.name = name
          v.customize ["modifyvm", :id, "--memory", 1024]
          v.customize ["modifyvm", :id, "--cpus", 2]
      end
    end
  end
end

#-----------------------e-----------------------------
步骤 2
启动您的虚拟机

vagrant up #启动
vagrant halt #关闭
vagrant destroy #销毁
vagrant ssh #使用MobaXterm登录可用vagrant创建的私钥登录(.vagrant\machines\host1\virtualbox\private_key),账户名vagrant,密码空
  • 网络

    • network

      • 公共网络(与本机同网段)machine.vm.network :public_network
      • 私有网络(NAT)machine.vm.network :public_network
    • bridge 如果主机上有多个网络接口可用,Vagrant 将 要求您选择虚拟机应桥接到的接口。默认的 可以通过向网络定义添加子句来指定接口。:bridge

    ruby 复制代码
       #Vagrant 将 要求您选择虚拟机应桥接到的接口。默认的 可以通过向网络定义添加子句来指定接口
       config.vm.network "public_network", bridge: "en1: Wi-Fi (AirPort)"
       #对于某些提供程序,可以指定要桥接的适配器列表 对:
       config.vm.network "public_network", bridge: [
         "en1: Wi-Fi (AirPort)",
         "en6: Broadcom NetXtreme Gigabit Ethernet Controller",
       ]
       ```
  • Hyper-V配置(服务器性能配置cpu、memory内存等) Configuration- Hyper-V Provider | Vagrant | HashiCorp Developer

Ansible

ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。Ansible架构相对比较简单,仅需通过SSH连接客户机执行任务即可

安装Ansible

安装 Ansible --- Ansible 社区文档

安装完整的 Ansible 软件包:pipx

shell 复制代码
#安装pipx
sudo apt update
sudo apt install python3-pip -y
python3 -m pip install --user pipx
python3 -m pipx ensurepath # 把 ~/.local/bin 写进 PATH
export PATH="$HOME/.local/bin:$PATH"
pipx --version
#安装完整的 Ansible 软件包
#apt install python3.8-venv
pipx install --include-deps ansible

Playbook测试

Ansible Playbook 提供可重复、可重用、简单的配置管理和多机部署系统,非常适合部署复杂的应用程序。如果您需要多次使用 Ansible 执行任务,请编写 playbook 并将其置于源代码控制之下。然后,您可以使用 playbook 推送新配置或确认远程系统的配置。

前期准备

shell 复制代码
  #先生成公私钥对
  ssh-keygen -t rsa
  ls /root/.ssh/  #有目录id_rsa  id_rsa.pub
  #讲vagrant创建的文件夹`.vagrant`传到主机(我这里是Ubuntu24),修改权限
  chmod 600 .vagrant/machines/host1/virtualbox/private_key
  chmod 600 .vagrant/machines/host2/virtualbox/private_key
  chmod 600 .vagrant/machines/host3/virtualbox/private_key
  #先连接一遍测试	
  ssh -i .vagrant/machines/host1/virtualbox/private_key [email protected]
  ssh -i .vagrant/machines/host2/virtualbox/private_key [email protected]
  ssh -i .vagrant/machines/host3/virtualbox/private_key [email protected]
  #连接报错Failed to connect to the host via ssh: @@@WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! 
  #使用 ssh-keygen 命令清除旧的公钥
  ssh-keygen -R 192.168.0.221
  ssh-keygen -R 192.168.0.222
  ssh-keygen -R 192.168.0.223

如使用私钥还需要密码,在~/.ssh/ config添加以下内容

如果仍报错 no mutual signature supported,需强制使用 RSA 算法:

shell 复制代码
sudo cat >> ~/.ssh/config << EOF
Host *
    PubkeyAcceptedKeyTypes=+ssh-rsa
    HostKeyAlgorithms=+ssh-rsa
EOF
创建hosts文件
shell 复制代码
host1 ansible_host=192.168.0.221
host2 ansible_host=192.168.0.222
host3 ansible_host=192.168.0.223

[all:vars]
ansible_ssh_private_key_file=.vagrant/machines/{{ inventory_hostname }}/virtualbox/private_key
创建setup.yml文件

当前目录下有以下文件/文件夹,再执行setup.yml

hosts、setup.yml、.vagrant/

ansible-playbook -i hosts setup.yml

ruby 复制代码
---
# 目标主机组:all 表示所有主机
- hosts: all
  # 启用权限提升(默认使用 sudo)
  become: true
  # 切换到 root 用户执行任务
  become_user: root
  # 使用 vagrant 用户进行 SSH 连接
  remote_user: vagrant
  # 禁用事实收集(目标机无 Python 时需关闭)
  gather_facts: false
  tasks:
    # 1. 等待 SSH 服务就绪(在控制机本地执行)
    - name: Wait for ssh to be up
      become: false  # 此任务不需要提权
      wait_for:
        port: 22     # 检测端口 22
        delay: 5     # 每次检测间隔 5 秒
        connect_timeout: 5  # 连接超时时间
        timeout: 360  # 总等待时间(秒)
        host: "{{ ansible_host }}"  # 目标主机 IP
      delegate_to: localhost  # 在控制机执行

    # 2. 安装 Python(使用 raw 模块绕过 Ansible 的 Python 依赖)
    - name: Installs python
      raw: |
        # 替换为国内镜像源并更新
        #sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list
        #sed -i 's/esm.ubuntu.com//g' /etc/apt/sources.list
        apt-get update -y && apt-get install -y python  # 安装 Python
      args:
        executable: /bin/bash  # 指定解释器

    # 3. 创建目标目录(用于存放 SSH 密钥)
    - name: Creates destination directory
      file:
        path: /root/.ssh/  # 目录路径
        state: directory   # 确保目录存在
        mode: 0700         # 目录权限
        owner: root        # 属主

    # 4. 推送 RSA 公钥(优先尝试)
    - name: Pushes user's rsa key to root's vagrant box
      copy:
        src: ~/.ssh/id_rsa.pub          # 本地公钥路径
        dest: /root/.ssh/authorized_keys  # 目标路径
        owner: root
        mode: 0600       # 安全权限
      register: rsa       # 注册结果变量
      ignore_errors: yes  # 允许失败(若无 RSA 密钥)

    # 5. 推送 DSA 公钥(仅当 RSA 失败时尝试)
    - name: Pushes user's dsa key to root's vagrant box
      copy:
        src: ~/.ssh/id_dsa.pub
        dest: /root/.ssh/authorized_keys
        owner: root
        mode: 0600
      when: rsa is failed  # 条件触发
      register: dsa
      ignore_errors: yes

    # 6. 推送 ED25519 公钥(前两者均失败时尝试)
    - name: Pushes user's ed25519 key to root's vagrant box
      copy:
        src: ~/.ssh/id_ed25519.pub
        dest: /root/.ssh/authorized_keys
        owner: root
        mode: 0600
      when: dsa is failed  # 前两个任务均失败时执行

    # 7. 检查 DNS 解析是否正常
    - name: Checks if resolver is working properly
      command: host -t A baidu.com  # 测试解析(原 ansible.cc 已过时)
      register: ns
      ignore_errors: yes

    # 8. 若 DNS 解析失败,配置备用 DNS(Google Public DNS)
    - name: Pushes new resolver configuration if resolver fails
      lineinfile:
        path: /etc/resolv.conf
        regexp: "^nameserver "
        line: "nameserver 114.114.114.114"  # 替换为 Google DNS
        state: present
      when: ns is failed

    # 9. 验证 DNS 配置是否生效
    - name: Checks if resolver is working properly with new nameserver
      command: host -t A baidu.com
      when: ns is failed

    # 10. 完成提示(调试用)
    - name: Final greeting
      debug:
        msg: "All tasks completed! Your Vagrant VMs are ready."
相关推荐
兔兔爱学习兔兔爱学习1 小时前
Linux部署ragflow,从安装docker开始~
linux·docker
好的明天qaz2 小时前
Ansible安装配置
ansible
安达发4 小时前
安达发|高效智能塑料切割数控系统 - 全自动化软件解决方案
大数据·运维·人工智能·自动化·aps排产软件·智能优化排产软件
lsnm6 小时前
【LINUX操作系统】线程操作
linux·jvm·c++·ubuntu·centos·gnu
FREEDOM_X7 小时前
Ubuntu 20.04 安装 ROS 2 Foxy Fitzroy
linux·ubuntu·机器人
华纳云IDC服务商7 小时前
如何利用Rust提升Linux服务器效率(详细操作指南)
linux·服务器·rust
桦07 小时前
【Linux】g++安装教程
linux·运维·服务器
杜子腾dd8 小时前
7.Excel:单元格格式
大数据·自动化·excel
Once_day8 小时前
Linux之netlink(2)libnl使用介绍(1)
linux·netlink·libnl3