当前位置: 首页 > news >正文

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

文章目录

    • Vagrant
      • 安装vagrant
      • 安装 VirtualBox
      • 如何使用
    • Ansible
      • 安装Ansible
      • Playbook测试
        • 创建`hosts`文件
        • 创建`setup.yml`文件

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无视之)

如何使用

如何在 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" % namemachine.vm.network :public_network,bridge: "en1", ip: ipmachine.vm.provider "virtualbox" do |v|v.name = namev.customize ["modifyvm", :id, "--memory", 1024]endendend
end#-----------------------e-----------------------------
步骤 2
启动您的虚拟机vagrant up #启动
vagrant halt #关闭
vagrant destroy #销毁
vagrant ssh 
  • 网络

    • network

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

       #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

#安装pipx#aptsudo apt install pipx # apt 默认目录 /usr/bin/pipx#pythonpython3 -m pip install --user pipxpython3 -m pipx ensurepath
#安装完整的 Ansible 软件包
pipx install --include-deps ansible

Playbook测试

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

前期准备

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

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

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

sudo cat >> ~/.ssh/config << EOF
Host *PubkeyAcceptedKeyTypes=+ssh-rsaHostKeyAlgorithms=+ssh-rsa
EOF
创建hosts文件
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

---
# 目标主机组: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 upbecome: false  # 此任务不需要提权wait_for:port: 22     # 检测端口 22delay: 5     # 每次检测间隔 5 秒connect_timeout: 5  # 连接超时时间timeout: 360  # 总等待时间(秒)host: "{{ ansible_host }}"  # 目标主机 IPdelegate_to: localhost  # 在控制机执行# 2. 安装 Python(使用 raw 模块绕过 Ansible 的 Python 依赖)- name: Installs pythonraw: |# 替换为国内镜像源并更新#sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list#sed -i 's/esm.ubuntu.com//g' /etc/apt/sources.listapt-get update -y && apt-get install -y python  # 安装 Pythonargs:executable: /bin/bash  # 指定解释器# 3. 创建目标目录(用于存放 SSH 密钥)- name: Creates destination directoryfile:path: /root/.ssh/  # 目录路径state: directory   # 确保目录存在mode: 0700         # 目录权限owner: root        # 属主# 4. 推送 RSA 公钥(优先尝试)- name: Pushes user's rsa key to root's vagrant boxcopy:src: ~/.ssh/id_rsa.pub          # 本地公钥路径dest: /root/.ssh/authorized_keys  # 目标路径owner: rootmode: 0600       # 安全权限register: rsa       # 注册结果变量ignore_errors: yes  # 允许失败(若无 RSA 密钥)# 5. 推送 DSA 公钥(仅当 RSA 失败时尝试)- name: Pushes user's dsa key to root's vagrant boxcopy:src: ~/.ssh/id_dsa.pubdest: /root/.ssh/authorized_keysowner: rootmode: 0600when: rsa is failed  # 条件触发register: dsaignore_errors: yes# 6. 推送 ED25519 公钥(前两者均失败时尝试)- name: Pushes user's ed25519 key to root's vagrant boxcopy:src: ~/.ssh/id_ed25519.pubdest: /root/.ssh/authorized_keysowner: rootmode: 0600when: dsa is failed  # 前两个任务均失败时执行# 7. 检查 DNS 解析是否正常- name: Checks if resolver is working properlycommand: host -t A baidu.com  # 测试解析(原 ansible.cc 已过时)register: nsignore_errors: yes# 8. 若 DNS 解析失败,配置备用 DNS(Google Public DNS)- name: Pushes new resolver configuration if resolver failslineinfile:path: /etc/resolv.confregexp: "^nameserver "line: "nameserver 114.114.114.114"  # 替换为 Google DNSstate: presentwhen: ns is failed# 9. 验证 DNS 配置是否生效- name: Checks if resolver is working properly with new nameservercommand: host -t A baidu.comwhen: ns is failed# 10. 完成提示(调试用)- name: Final greetingdebug:msg: "All tasks completed! Your Vagrant VMs are ready."

相关文章:

  • git fetch和git pull的区别
  • ​【空间数据分析】缓冲区分析--泰森多边形(Voronoi Diagram)-arcgis操作
  • Vue使用Sortablejs拖拽排序 视图显示与数据不一致、拖拽结束后回跳问题
  • excel如何做相关系数分析
  • 【网络原理】TCP异常处理(二):连接异常
  • 脑机接口:重塑人类未来的神经增强革命
  • HarmonyOS NEXT 诗词元服务项目开发上架全流程实战(二、元服务与应用APP签名打包步骤详解)
  • 什么是 MCP?AI 应用的“USB-C”标准接口详解
  • CentOS环境下搭建seata(二进制、MySQL)
  • [计算机网络]物理层
  • Nginx核心功能与LNMP部署
  • 主流微前端框架比较
  • pytest-前后置及fixture运用
  • Mybatis-plus代码生成器的创建使用与详细解释
  • Nginx部署与源码编译构建LAMP
  • SVMSPro平台获取Websocket视频流规则
  • ComfyUI 学习笔记,案例1:2_pass_txt2img
  • CMD与PowerShell:Windows命令行工具的对比与使用指南
  • 4月29号
  • w233大学生就业需求分析系统设计与实现
  • 广东省副省长刘红兵跨省调任湖南省委常委、宣传部长
  • 打造全域消费场景,上海大世界百个演艺娱乐新物种待孵化
  • 开门红背后的韧性密码:上海八大企业的“反脆弱”与“真功夫”
  • 黄晓丹:用“诗心”找到生存的意义
  • 北美票房|《罪人》遭媒体唱衰,好莱坞业内人士集体反击
  • 银川市长信箱被指乱回复:问诗词大会、答工程欠款,官方称工作失误