【Ansible 文档】提示、推荐、注意事项

1. 查看 详细 信息

如果你想要查看成功模块和不成功的详细输出,使用 --verbose 标识

2. 检查 playbook 的语法

使用 ansible-playbook 的 --syntax-check 标识。通过parser来运行playbook,确保Include files、roles等没有语法错误。

3. 在运行playbook之前,查看playbook影响的哪些主机

ansible-playbook playbook.yml --list-hosts

4. 运行playbook的方式

ansible-playbook playbook.yml -f 10

5. 特权上升的方式更改为 become

 

6. 指定主机顺序执行playbook

inventory:
  The default. The order is ‘as provided’ by the inventory
reverse_inventory:
  As the name implies, this reverses the order ‘as provided’ by the inventory
sorted:
  Hosts are alphabetically sorted by name
reverse_sorted:
  Hosts are sorted by name in reverse alphabetical order
shuffle:
  Hosts are randomly ordered each run

7. 任务可以使用历史遗留格式: action: module options 来声明,但是推荐使用 module: options 格式

8. 大多数模块使用 “key=value” 来指定参数,例如服务模块。但是 “command and shell ” 模块使用的是参数列表,不使用“key=value”格式。

tasks:
  - name: enable selinux
    command: /sbin/setenforce 1

command和shell模块关心返回值,因此如果你有的命令退出码不为0,你可能希望这么做:
tasks:
  - name: run this command and ignore the result
    shell: /usr/bin/somecommand || /bin/true
tasks:
  - name: run this command and ignore the result
    shell: /usr/bin/somecommand
    ignore_errors: True

9. 如果一行太长了,在下一行使用一个空格缩进表示命令的继续

tasks:
  - name: Copy ansible inventory file to client
    copy: src=/etc/ansible/hosts dest=/etc/ansible/hosts
            owner=root group=root mode=0644

10. playbook 可能有四个包含任务的部分

pre_tasks, tasks, post_tasks, roles

11. handlers 需要注意的

handler执行的时机:

  • handlers notified within pre_taskstasks, and post_tasks sections are automatically flushed in the end of section where they were notified;
  • handlers notified within roles section are automatically flushed in the end of tasks section, but before any tasks handlers.  表明 roles 会跟tasks section合并

  此外,通过meta,可以提前执行handler:

tasks:
   - shell: some tasks go here
   - meta: flush_handlers
   - shell: some other tasks

可以指定监听的主题

handlers:
    - name: restart memcached
      service: name=memcached state=restarted
      listen: "restart web services"
    - name: restart apache
      service: name=apache state=restarted
      listen: "restart web services"

tasks:
    - name: restart everything
      command: echo "this task will restart the web services"
      notify: "restart web services"

 

posted @ 2017-10-20 16:29  彭玉松  阅读(657)  评论(0编辑  收藏  举报