ansible使用4-Playbook Roles and Include Statements

task include

---
# possibly saved as tasks/foo.yml
- name: placeholder foo
  command: /bin/foo

- name: placeholder bar
  command: /bin/bar

tasks:
  - include: tasks/foo.yml

变量传递

tasks:
  - include: wordpress.yml wp_user=timmy
  - include: wordpress.yml wp_user=alice
  - include: wordpress.yml wp_user=bob

# 1.4版本以上,可以传递列表与字典
tasks:
 - { include: wordpress.yml, wp_user: timmy, ssh_keys: [ 'keys/one.txt', 'keys/two.txt' ] }

tasks:
 - { include: wordpress.yml, wp_user: timmy, ssh_keys: [ 'keys/one.txt', 'keys/two.txt' ] }

# include文件使用{{ }}引用变量
{{ wp_user }}

# 其他方式
tasks:
  - include: wordpress.yml
    vars:
        wp_user: timmy
        some_list_variable:
          - alpha
          - beta
          - gamma

handlers include

---
# this might be in a file like handlers/handlers.yml
- name: restart apache
  service: name=apache state=restarted

handlers:
  - include: handlers/handlers.yml

import文件

- name: this is a play at the top level of a file
  hosts: all
  remote_user: root

  tasks:

  - name: say hi
    tags: foo
    shell: echo "hi..."

- include: load_balancers.yml
- include: webservers.yml
- include: dbservers.yml

角色

playbooks目录结构

site.yml
webservers.yml
fooservers.yml
roles/
   common/
     files/
     templates/
     tasks/
     handlers/
     vars/
     defaults/
     meta/
   webservers/
     files/
     templates/
     tasks/
     handlers/
     vars/
     defaults/
     meta/

playbook中定义

---
- hosts: webservers
  roles:
     - common
     - webservers

使用变量

---
- hosts: webservers
  roles:
    - common
    - { role: foo_app_instance, dir: '/opt/a',  port: 5000 }
    - { role: foo_app_instance, dir: '/opt/b',  port: 5001 }

使用表达式

---
- hosts: webservers
  roles:
    - { role: some_role, when: "ansible_os_family == 'RedHat'" }

assign tags

---
- hosts: webservers
  roles:
    - { role: foo, tags: ["bar", "baz"] }
---
- hosts: webservers

  pre_tasks:
    - shell: echo 'hello'

  roles:
    - { role: some_role }

  tasks:
    - shell: echo 'still busy'

  post_tasks:
    - shell: echo 'goodbye'

role默认变量

在defaults/main.yml中添加

role依赖

role依赖存储在meta/main.yml文件

---
dependencies:
  - { role: common, some_parameter: 3 }
  - { role: apache, port: 80 }
  - { role: postgres, dbname: blarg, other_parameter: 12 }

# 全路径
---
dependencies:
   - { role: '/path/to/common/roles/foo', x: 1 }

# 使用版本控制
---
dependencies:
  - { role: 'git+http://git.example.com/repos/role-foo,v1.1,foo' }
  - { role: '/path/to/tar/file.tgz,,friendly-name' }

allow_duplicates: yes

---
dependencies:
- { role: wheel, n: 1 }
- { role: wheel, n: 2 }
- { role: wheel, n: 3 }
- { role: wheel, n: 4 }

# meta/main.yml内容
---
allow_duplicates: yes
dependencies:
- { role: tire }
- { role: brake }

# result
tire(n=1)
brake(n=1)
wheel(n=1)
tire(n=2)
brake(n=2)
wheel(n=2)
...
car

你可能感兴趣的:(statement)