ansible playbook 详解

ansible playbook 能将ansible的任务执行分解成各个部分,使远程配置更加强大和灵活。

核心组件

  • Tasks:任务,由模板定义的操作列表

  • Variables:变量

  • Templates:模板,即使用模板语法的文件

  • Handlers:处理器 ,当某条件满足时,触发执行的操作

  • Roles:角色

yaml中的字段

  • hosts :指定主机组,(,分隔多个)

  • remote_user :使用的用户

  • gather_facts :是否收集主机的信息

  • vars :自定义的变量

  • tasks :任务组

    • name :任务名

    • module :执行的模块

    • notify :任务状态变触发的handlers

    • with_items :循环处理

    • when :条件判断

  • handlers :处理器

--- 

- hosts: testhost
  user: root
  gather_facts: false
  tags: 
    - always      # 指定tags,可是使用 ansible-playbook -t always 执行标记了的task
  vars:
    name: "test"
    service: "nginx"
    exist: "True"

  tasks:
    - name: change mode for files
      file: path=/tmp/{{ item }} mode=600
      # {{ var }} 可以是/etc/ansible/hosts中的,gather中的,vars中的
      template: src=. dest=. # 指定模板
      with_items:
        - 1.txt
        - 2.txt
        - 3.txt

    - name: installed nginx
      yum: name="{{ service }}" 
      when: ansible_ens33.ipv4.address == "172.7.15.114"   # ansible <host> -m setup 可以查看到所有的gather信息

      when: exist | match("True")                          # 支持 () , and, or, 自定义条件   
    - name: create file
      file: path=/tmp/123 state=touch
      notify: test handler

   handlers:
     - name: test handler
       shell: echo "123" > /tmp/11.txt
---
- hosts: 192.168.127.129
  remote_user: root
  tasks:
    - name: test_playbook
      shell: touch /tmp/test.txt
    - name: task2
      shell: touch /tmp/tasks2.txt
# 循环实例
---
- hosts: testhost
  user: root
  tasks:
    - name: change mode for files
      file: path=/tmp/{{ item }} state=touch mode=600
      with_items:
        - 1.txt
        - 2.txt
        - 3.txt
# ansible-playbook test.yml --syntax-check # 验证yaml文件语法格式

playbook: test.yml
# 条件实例
---
- hosts: testhost
  user: root
  gather_facts: True
  tasks:
    - name: use when
      shell: touch /tmp/when.txt
      when: ansible_ens33.ipv4.address == "172.7.15.114"
      # ansible aming-02 -m setup 可以查看到所有的facter信息
# handlers 实例
---
- name: handlers test
  hosts: 192.168.127.129
  user: root
  tasks:
    - name: copy file
      copy: src=/etc/passwd dest=/tmp/aaa.txt
      notify: test handlers

  handlers:
    - name: test handlers
      shell: echo "111111" >> /tmp/aaa.txt

最后更新于

这有帮助吗?