使用Ansible收集服务器元数据信息到CMDB数据库
数据库建库
CREATE DATABASE `ansiblecmdb` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
安装必要组件:
# ansible-galaxy collection install community.mysql # 非必要,如果安装的ansible自带有则不需要安装
pip install ansible-cmdb
yum install -y mariadb MySQL-python
创建一个Ansible playbook文件,例如 collect_facts.yml,并添加以下内容:
- name: Collect server facts into CMDB
hosts: all
gather_facts: true
become: true
vars:
db_host: "192.168.0.100"
db_user: "root"
db_password: "password"
db_name: "ansiblecmdb"
tasks:
- name: Create output directory
file:
path: /tmp/out
state: directory
delegate_to: localhost
run_once: true
- name: Get server metadata
setup:
register: metadata
- name: Save metadata to file
copy:
content: "{{ hostvars[item]['metadata'] | to_nice_json }}"
dest: /tmp/out/{{ item }}
loop: "{{ groups.all }}"
delegate_to: localhost
run_once: true
- name: Execute ansible-cmdb command
shell: "ansible-cmdb -t sql /tmp/out > /tmp/cmdb.sql"
delegate_to: localhost
run_once: true
- name: Insert data into CMDB table
mysql_db:
login_host: "{{ db_host }}"
login_user: "{{ db_user }}"
login_password: "{{ db_password }}"
name: "{{ db_name }}"
encoding: utf8mb4
state: import
target: /tmp/cmdb.sql
delegate_to: localhost
run_once: true
运行Ansible playbook:
ansible-playbook collect_facts.yml
作者:wanghongwei
版权声明:本作品遵循<CC BY-NC-ND 4.0>版权协议,商业转载请联系作者获得授权,非商业转载请附上原文出处链接及本声明。