對 ansible 基礎徹底不瞭解能夠看個人上一篇文章。git
Playbook 是用YAML 格式寫成。對YAML不瞭解的能夠參見這篇簡短的介紹 。github
大部分指令不把輸出粘在這裏,也是但願讀者本身邊讀,邊操做。
爲便於拷貝操做,命令行提示符$
都將省略。web
ansible-playbook playbook.yml
--- - hosts: all tasks: - name: Install Apache. command: yum install --quiet -y httpd httpd-devel - name: Copy configuration files. command: > cp httpd.conf /etc/httpd/conf/httpd.conf - command: > cp httpd-vhosts.conf /etc/httpd/conf/httpd-vhosts.conf - name: Start Apache and configure it to run at boot. command: service httpd start - command: chkconfig httpd on
命令:command 指令後緊跟的大於號(>)告訴YAML「自動將下一組縮進行引爲一個長字符串,每行之間用空格分隔」。在某些狀況下,它有助於提升任務的可讀性。使用有效的YAML語法有多種描述配置的方法。
上面的playbook 與腳本無異,有助於把你原有的shell腳本的技能進行平滑過渡。shell
下面展現更有 ansible 味道的寫法。apache
--- - hosts: all become: yes tasks: - name: Install Apache. yum: name={{ item }} state=present with_items: - httpd - httpd-devel - name: Copy configuration files. copy: src: "{{ item.src }}" dest: "{{ item.dest }}" owner: root group: root mode: 0644 with_items: - src: "httpd.conf" dest: "/etc/httpd/conf/httpd.conf" - src: "httpd-vhosts.conf" dest: "/etc/httpd/conf/httpd-vhosts.conf" - name: Make sure Apache is started now and at boot. service: name=httpd state=started enabled=yes
這裏become: yes
至關於 --sudo
的做用。state=present
至關沒有就安裝。可選的 state 還有 latest
- 保持最新,absent
- 有就卸載,started
- 啓動等。segmentfault
運行ansible-playbook時加--check
參數用於覈查服務器的狀態,不作修改操做(dry-run)。瀏覽器
能夠經過 --limit
參數指定範圍,如:服務器
ansible-playbook playbook.yml --limit webservers
下面的指令將顯示出做用於哪些主機:併發
ansible-playbook playbook.yml --list-hosts
指定專門用戶:ssh
ansible-playbook playbook.yml --remote-user=johndoe
或以另外一個用戶身份執行(同時在命令行詢問密碼):
ansible-playbook playbook.yml --become --become-user=janedoe \ --ask-become-pass
這裏有一些完整的例子,能夠在DevOps實踐中加以運用。
--- hosts: all vars_files; - var.yml pre_tasks: - name: Update apt cache if needed. apt: update_cache=yes cache_valid_time=3600 handlers: - name: restart solr service: name=solr state=restarted tasks: - name: Install Java. apt: name=openjdk-8-jdk state=present - name: Download Solr. get_url: url: "https://archive.apache.org/dist/lucene/solr/{{ solr_version }}/solr-{{ solr_version }}.tgz" dest: "{{ download_dir }}/solr-{{ solr_version }}.tgz" checksum: "{{ solr_checksum }}" - name: Expand Solr. unarchive: src: "{{ download_dir }}/solr-{{ solr_version }}.tgz" dest: "{{ download_dir }}" copy: no creates: "{{ download_dir }}/solr-{{ solr_version }}/README.txt" - name: Run Solr installation script. shell: > {{ download_dir }}/solr-{{ solr_version }}/bin/install_solr_service.sh {{ download_dir }}/solr-{{ solr_version }}.tgz -i /opt -d /var/solr -u solr -s solr -p 8983 creates={{ solr_dir }}/bin/solr - name: Ensure solr is started and enabled on boot. service: name=solr state=started enabled=yes
執行:
ansible-playbook solr.yml --limit-hosts solr
順利的話, 過一會就能夠經過瀏覽器訪問8983端口的solr管理界面了。
若有什麼問題,能夠參考這裏的 源代碼。
If everything is under control, you are going too slow...
指南就到這裏,實踐纔是關鍵。祝您好運。