使用Ansible 收集服务器元数据信息到CMDB数据库

发布时间 2023-05-30 20:09:59作者: wang-hongwei

安装必要组件:

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 }}_metadata.json
      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 }}"
        state: import
        target: /tmp/cmdb.sql
      delegate_to: localhost
      run_once: true

运行Ansible playbook:

ansible-playbook collect_facts.yml