ansible基礎(chǔ)教程

ansible 是一個(gè)輕量級(jí)的IT自動(dòng)化工具,集合了眾多運(yùn)維工具(puppet、cfengine、chef、func、fabric)的優(yōu)點(diǎn),實(shí)現(xiàn)了批量系統(tǒng)配置、批量程序部署、批量運(yùn)行命令等功能。

特點(diǎn)

  • SSH by default
  • No agents: controlled hosts / devices need no agent sofware
  • No server: any linux machine can do Ansible activities via terminal commands
  • Modules in any languages: the modules can be developed in any languages
  • YAML, not code: using YAML language(標(biāo)記語言,類XML) to write playbook
  • Strong multi-tier solution:可實(shí)現(xiàn)多級(jí)指揮

ansible 配置文件

  • ansible.cfg

    • 定義各種通用變量
    • 查找ansible.cfg文件的順序
      • ANSIBLE_CONFIG環(huán)境變量所指定的文件
      • ./ansible.cfg
      • ~/.ansible.cfg
      • /etc/ansible/ansible.cfg
    • 配置舉例:
    inventory = /etc/ansible/hosts  #指定inventory文件位置
    

Inventory

Ansible只能管理指定的服務(wù)器,在inventory文件中進(jìn)行配置對(duì)應(yīng)的主機(jī)/分組的數(shù)據(jù),其格式如下:

--組名(對(duì)系統(tǒng)進(jìn)行分組)
[webservers]
--主機(jī)名
foo.example.com
                             
--指定系統(tǒng)的別名 + ssh的用戶
jumper ansible_ssh_host=192.168.1.50 ansible_ssh_user=appadmin
        
--01到50,一組相似的hostname
www[01:50].example.com

--給host設(shè)定變量,后續(xù)playbook中可以使用
host1 http_port=80 maxRequestsPerChild=808

--給group設(shè)定變量,應(yīng)用于組內(nèi)的所有host
[atlanta]
host1
host2

[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com    

--組內(nèi)組
[southeast:children]
atlanta
raleigh    

Ansible Ad-Hoc 命令

  • 臨時(shí)執(zhí)行的命令
ansible <pattern_goes_here[webservers, all, *]> -m <module_name> -a <arguments>
  • 不指定module的話,則默認(rèn)執(zhí)行command模塊
  • ansible-doc: 獲取模塊列表,以及模塊使用格式
    • ansible-doc [-l] [-s MODULE]
      • -l : 列出支持的核心模塊
      • -s MODULE : 查看模塊的用法

使用例子:ping主機(jī)

ansible -i hosts webservers -m ping --ask-pass -u user
ansible -i hosts all -m ping --ask-pass -u user

輸出:

[root@Centos7 ~]# ansible all -m ping
host1 | success >> {
    "changed": false,
    "ping": "pong"
}

host2 | UNREACHABLE! => {
    "changed": false,
    "msg": "Authentication failed.",
    "unreachable": true
}

參數(shù)解釋

  • -m, --module-name: module name to execute(default=command)
    • -m ping : 執(zhí)行ping module
  • -a, --args: module arguments
  • -i, --inventory-file: specify inventory host path(default=/etc/ansible/hosts) or comma separated host list.
  • -k, --ask-pass: ask for connection password
  • -u REMOTE_USER, --user=REMOTE_USER: connect as this user (default=None)
  • webservers 表示執(zhí)行該命令的分組,all 表示inventory中配置的所有主機(jī)
  • -l, --limit=SUBSET: further limit selected hosts to an additional pattern,限定組或host來執(zhí)行playbook
  • -c, --connect: connect type to use (default=smart)
  • --ask-vault-pass: ask for vault password(sudo 模式需要)
  • -b, --become: run operations with become (does not imply password prompting)(使用playbook制定的become_user進(jìn)行操作)
  • -t TAGS, --tags=TAGS: only run plays and tasks tagged with these values
  • -C, --check: don't make any changes; instead, try to predict some of the changes that may occur

Ansible Playbook

  • Ad-Hoc命令只能執(zhí)行一些臨時(shí)性的、簡單的命令
  • 實(shí)際企業(yè)應(yīng)用需要經(jīng)過多個(gè)步驟,且各個(gè)步驟之間存在依賴關(guān)系,Ad-Hoc命令無法滿足使用需求
  • 使用playbook來定義步驟以及依賴
  • playbook 由yaml編寫,讓遠(yuǎn)程主機(jī)按照事先編排的機(jī)制執(zhí)行task
---
- hosts: all    #執(zhí)行tasks的主機(jī),all表示所有
  become: yes   #使用特定用戶執(zhí)行tasks,該參數(shù)也可以配置在相應(yīng)task中。
  become_user: root
  remote_user: username #the user log into machine.
  
  tasks:
    # 每個(gè)task都相當(dāng)于在執(zhí)行對(duì)應(yīng)模塊的功能
    # 每個(gè)task感覺都是單次的連接,執(zhí)行完之后斷掉,之前的環(huán)境變量設(shè)置不會(huì)在后續(xù)的task中生效
    # 描述task
    - name: copy local file to remote machine
      # 執(zhí)行對(duì)應(yīng)模塊功能
      copy: 
        src: ~/test
        dest: ~/test
        owner: root 
        mode: 0600
      # 命令執(zhí)行的結(jié)果存到變量中,方便后續(xù)使用
      register: rsa
      # 設(shè)置環(huán)境變量
      environment:
        JAVA_HOME: /usr/java/jre1.8.0_51
      # task有失敗之后,相同host后續(xù)的task不會(huì)執(zhí)行,該參數(shù)可在失敗后繼續(xù)執(zhí)行。
      ignore_errors: yes
      # 給這部分task打上tags,可指定只執(zhí)行相應(yīng)tags的task  (命令中添加:-t deploy)
      tags: deploy
      # (call the tasks defined in handlers if module does some changes to the remote host)
      notify:
        - do something
            
    # defines a list of tasks
    handlers:
      - name: do something
        service: test

    - name: task 2
      debug: var={{ host_vars }} # 使用對(duì)應(yīng)host的host_vars變量

  • 例:在幾臺(tái)機(jī)子中執(zhí)行hostname命令,并獲取返回值

    • 文件目錄:
    test        # inventory文件,配置主機(jī)
    test.yml    # playbook
    
    • inventory 配置內(nèi)容
    [server]
    host1 ansible_ssh_host=1.1.1.1 ansible_ssh_user=appadmin
    host2 ansible_ssh_host=1.1.1.2 ansible_ssh_user=appadmin
    
    • test.yml 內(nèi)容
    ---
    - hosts: all
      tasks:
        - name: get hostname
          shell: hostname
          register: out
    
        - debug: var=out
    
    • 執(zhí)行playbook:$ ansible-playbook -i test test.yml,返回內(nèi)容:
PLAY [all] *********************************************************************

TASK [setup] *******************************************************************
ok: [host1]
ok: [host2]

TASK [get hostname] ************************************************************
changed: [host1]
changed: [host2]

TASK [debug] *******************************************************************
ok: [host1] => {
    "out": {
        "changed": true,
        "cmd": "hostname",
        "delta": "0:00:00.003584",
        "end": "2017-02-09 16:05:04.043118",
        "rc": 0,
        "start": "2017-02-09 16:05:04.039534",
        "stderr": "",
        "stdout": "host1.com",
        "stdout_lines": [
            "host1.com"
        ],
        "warnings": []
    }
}
ok: [host2] => {
    "out": {
        "changed": true,
        "cmd": "hostname",
        "delta": "0:00:00.003584",
        "end": "2017-02-09 16:05:04.043118",
        "rc": 0,
        "start": "2017-02-09 16:05:04.039534",
        "stderr": "",
        "stdout": "host2.com",
        "stdout_lines": [
            "host1.com"
        ],
        "warnings": []
    }
}

PLAY RECAP *********************************************************************
# 以下是對(duì)應(yīng)host的task執(zhí)行情況,ok表示執(zhí)行成功的task數(shù)量,charged表示對(duì)host產(chǎn)生修改的task數(shù)量。
host1                         : ok=3    changed=1    unreachable=0    failed=0
host2                         : ok=3    changed=1    unreachable=0    failed=0

role 使用

  • playbook 直接調(diào)用 task 問題
    • playbook 是需要處理的事情,task 是執(zhí)行細(xì)節(jié),playbook并不關(guān)心細(xì)節(jié)
    • playbook 直接調(diào)用task 使task無法復(fù)用
    • playbook會(huì)越來越長,難維護(hù)
  • 將一個(gè)或多個(gè)task抽象成一個(gè)role,隱藏細(xì)節(jié),供playbook調(diào)用
  • role易于復(fù)用,可以從一個(gè)已知的文件結(jié)構(gòu)中自動(dòng)加載vars, tasks, handler。
  • 部分文件結(jié)構(gòu):
test
test.yml
roles/
    install/
        files/
        templates/
        tasks/
            main.yml  #應(yīng)用 install 時(shí),優(yōu)先執(zhí)行main.yml
        handlers/
        vars/
    deploy/
        files/
        templates/
        tasks/
            main.yml
        handlers/
        vars/
  • playbook內(nèi)容
---
- hosts: webservers
  roles:
     - install
     - deploy

部分常用模塊

  • file: 包含了文件、文件夾、超級(jí)鏈接類的創(chuàng)立、拷貝、移動(dòng)、刪除操作。
  • copy: copy a file on the local box to remote locations. (可以使用 remote_src,使src在遠(yuǎn)程機(jī)子上,2.0 以后的版本適用)
  • fetch: copy files from remote locations to the local box.
  • template: Templates a file out to a remote server.
  • command: Executes a command on a remote node(It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", ";" and "&" will not work)If you want to execute a command securely and predictably, it may be better to use the command module instead.
  • lineinfile: Ensure a particular line is in a file, or replace an existing line using a back-referenced regular expression.
  • pause : Pause playbook execution
  • ping : Try to connect to host, verify a usable python and return pong on success. no sense in playbook.
  • shell : Execute commands in nodes.(runs the command through a shell (/bin/sh) on the remote node.)If you want to execute a command securely and predictably, it may be better to use the command module instead.
  • debug : Print statements during execution
  • setup : Gathers facts about remote hosts(默認(rèn)執(zhí)行),支持filter。
  • apt : Manages apt-packages
  • service: Controls services on remote hosts
  • fail: Fail with custom message
  • subversion: Deploys a subversion repository.
  • group: Add or remove groups
  • user: Manage user accounts
  • get_url: Downloads files from HTTP, HTTPS, or FTP to node
  • wait_for: Waits for a condition before continuing.(port is open , file is present, and so on.)
  • script: Runs a local script on a remote node after transferring it

實(shí)際場(chǎng)景應(yīng)用

參考:

an-intro-to-network-automation-3-ansible
an-ansible-tutorial
ansible-simple-tutorial

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • ansible 系統(tǒng)架構(gòu) ansible簡介ansible是新出現(xiàn)的自動(dòng)化運(yùn)維工具,ansible是一個(gè)配置管理和...
    運(yùn)維阿文閱讀 9,842評(píng)論 1 53
  • ansible介紹ansible常用模塊使用playbooktemplates,模板條件測(cè)試和循環(huán)迭代roles,...
    哈嘍別樣閱讀 1,492評(píng)論 0 3
  • 進(jìn)手帳坑已經(jīng)半年左右了,然而還是不怎么會(huì)拼貼。買來的膠帶不會(huì)用,最后被我用來改裝盒子 后來知道了bullet...
    木淺月閱讀 1,232評(píng)論 6 25
  • 首先申明,本人并不是時(shí)尚主編或者什么。我只代表普通的女性來表達(dá)一下關(guān)于女生眼中,什么樣的男生形象才可以稱的上好看。...
    多多西米閱讀 14,485評(píng)論 10 32
  • 人都會(huì)老掉,老成自己不想要的樣子。 年老并不可怕,只是時(shí)光堆積的結(jié)果罷了! 可怕的是人還沒有老,內(nèi)心已經(jīng)老了——變...
    sofia222閱讀 294評(píng)論 0 0

友情鏈接更多精彩內(nèi)容