--- title: Ansible tags: ansible --- [toc] # Demo url: https://gitlab.com/homway/ansibledemo # Chef vs Puppet vs Ansible vs Saltstack | | Chef | Puppet | Ansible | Saltstack | | -------- | -------- | -------- | -------- | -------- | | Language | DSL(Ruby) | DSL(Ruby) | YAML(Python) | YAML(Python) | | Architecture | Client/Server | Client/Server | Client only | Client/Server | | server | Chef Server: linux | Puppet Master: linux | Ansible server: linux | Salt Master: linux | | client | linux | linux | linux(ssh) <br> windows: winrm | linux | | pricing | 120 | 100 | 100 | 150 | ## Google Trend https://trends.google.com.tw/trends/explore?q=%2Fm%2F05zxlz3,%2Fg%2F1hh_rd6rx,%2Fm%2F0k0vzjb,%2Fm%2F0hn8c6s,%2Fg%2F11g6bg27fp # 示意圖 ![](https://i.imgur.com/MmB7KNu.png) # 安裝(Ubuntu) ```shell sudo apt update sudo apt install software-properties-common sudo add-apt-repository --yes --update ppa:ansible/ansible sudo apt install ansible ``` # 指令 ansible pattern [-m module_name] [-a args] ```shell --version 版本號 -h 指令說明 -i 指定invertory檔案 -m module 模組 -a module 參數 -v 詳細過程 –vv -vvv 更詳細 ``` # 元素 * config: 設定檔 * Invertory:主機清單, ex: [dev|qc] webserver, dbserver, app server * Playbook:預先定義好的任務腳本, ex: install, rebot * Module: 內建的功能模組, ex: command, shell, ping # 設定檔: ansible.cfg ## 設定檔順序 * ANSIBLE_CONFIG (environment variable if set) * ansible.cfg (in the current directory) <--useful * ~/.ansible.cfg (in the home directory) * /etc/ansible/ansible.cfg config doc: https://docs.ansible.com/ansible/latest/reference_appendices/config.html ```shell= # 主機清單, 可用 -i 參數替換 inventory = hosts # 是否檢查know_hosts host_key_checking = false # forks = 5 # remote_user=ansible # remote_port=22 # sudo_user=root # timeout=10 ``` # 主機清單: hosts ```shell= [all] vm01 vm02 vm03 [demo] vm01 [web] vm01 vm02 [db] vm03 [all:vars] ansible_connection=ssh ansible_port=22 ansible_ssh_user=ansible vm01 ansible_host=192.168.1.11 vm02 ansible_host=192.168.1.12 vm03 ansible_host=192.168.1.13 ``` # Module module doc: https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html * command: 預設模組, 執行指令 * shell: 執行包含 pipeline 指令 * script: 執行script檔 * service: ansible vm01 -m service -a 'name=httpd state=restarted' * user: ansible vm01 -m user -a 'name=user1 home=/home/user1' # Galaxy galaxy url: https://galaxy.ansible.com/ # Playbook: hello.yaml ```yaml= - name: hello world hosts: all tasks: - name: echo 'hello world' command: echo 'hello world' register: msg - name: print msg debug: msg: "{{ msg }}" # - name: ping # command: ping 168.95.1.1 -c 4 ``` # 測試 ```shell= ansible-playbook hello.yaml ansible -i hosts all -m ping ansible all -m ping ansible web -m ping ansible db -m ping ansible vm02,vm03 -m ping ``` # TODO * ???