Ansible: hosts文件拆分為inventory和定義inventory全局變量


前言

隨着管理機器的增多,我們在使用Ansible的時候時常會遇到hosts文件過於冗長的問題,極其不便於管理,而將hosts文件拆分為inventory就可解決該問題;另外,hosts中的每個主機條目需要指定用戶名和私鑰或密碼,十分繁瑣,而hosts文件支持全局變量,可將該公用信息進行全局指定或分組指定,本文就這兩點展開,希望對遇到同樣問題的小伙伴有所幫助。

配置文件

首先需要修改/etc/ansible/ansible.cfg配置文件

[defaults]
#此處為目錄或hosts文件,不可更改
inventory = /etc/ansible/inventory
#inventory = /etc/ansible/host

創建inventory目錄

創建/etc/ansible/inventory目錄
在該目錄下創建拆分后的hosts文件

拆分hosts文件

建議先按照項目創建目錄,在項目目錄下創建環境的hosts文件,例如下圖

定義inventory全局變量

cat >/etc/ansible/inventory/all-vars <<"EOF"
[all:vars]
ansible_connection=ssh
ansible_ssh_user=root
ansible_ssh_private_key_file=/root/.ssh/id_rsa

清除原有每個inventory的變量

sed -ig 's/ansible_ssh_user=root ansible_ssh_private_key_file=\/root\/.ssh\/id_rsa//g' ./*

此處貼上/etc/ansible/inventory/Aproject/online的hosts文件內容

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM