对 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...
指南就到这里,实践才是关键。祝您好运。