轮询一次和轮询三次

# This will run debug three times since the list is flattened
- debug:
    msg: "{{ item }}"
  vars:
    nested_list:
      - - one
        - two
        - three
  with_items: "{{ nested_list }}"

# This will run debug once with the three items
- debug:
    msg: "{{ item }}"
  vars:
    nested_list:
      - - one
        - two
        - three
  with_items:
    - "{{ nested_list }}"

变量生成

- name: 动态生成主机名
  hosts: new-db
  become: yes
  remote_user: ansible
  vars:
    cloud: ali
    project: test
    role: db
    hostname: "{{ ( cloud + '_' + project + '_' + role + '_' + ansible_default_ipv4.address ) | replace('.','-') }}"
  tasks:
    - name: Show debug info
      debug: var=hostname
      
# 动态修改主机名称
- name: init web template
  hosts: new-web
  become: yes
  remote_user: ansible
  vars:
    cloud: ali
    project: test
    role: web
    hostname: "{{ ( cloud + '_' + project + '_' + role + '_' + ansible_default_ipv4.address ) | replace('.','-') }}"
  tasks:
    - name : update hostname from inventory_hostname
      hostname: {{ hostname }}
        name: 
      when: cloud is defined and project is defined and role is defined
      tags: hostname

抓取返回值

# when通过register返回的状态控制
tasks:
  - command: /bin/false
    register: result
    ignore_errors: True

  - command: /bin/something
    when: result is failed

  # In older versions of ansible use ``success``, now both are valid but succeeded uses the correct tense.
  - command: /bin/something_else
    when: result is succeeded

  - command: /bin/still/something_else
    when: result is skipped

playbooks注意事项

# any_errors_fatal任意异常退出
- name: nginx
  hosts: localhost
  remote_user: root
  any_errors_fatal: true
  roles:
    - nginx

# with_items的参数使用"",防止bug
with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

# 测试功能
ansible-playbook foo.yml --check

# debug
ansible-playbook playbook_mysql.yml -vvv