跳转至

技巧

# 如果值不存在,则忽略改值
id: "{{ item.state | default(omit) }}"

# 删除目录下的所有文件
- find:
    paths: /opt/logs
    patterns: "*.log"
  register: find_results

- file:
    path: "{{ item['path'] }}"
    state: absent
  with_items: "{{ find_results['files'] }}"

# 返回 JSON 数据
# 通过配置环境变量
ANSIBLE_CALLBACK_WHITELIST=json ANSIBLE_STDOUT_CALLBACK=json ansible-playbook ...
# 全局配置 ansible.cfg
[defaults]
callback_whitelist=json
stdout_callback=json

# 向 template 模块传递变量
var1: "{{ lookup('template', 'lookup-test.j2', template_vars=dict(variable1='var1')) | trim }}"
var2: "{{ lookup('template', 'lookup-test.j2', template_vars=dict(variable1='var1', variable2='var2')) | trim }}"

# connection 和 delegate_to 的区别
# The main difference between connection and delegate_to is that connection can be used at a play or task level, 
# whereas delegate_to operates at a task level only.
# 通过命令行
ansible-playbook playbook.yml --connection=local

# 在 playbook 配置
- hosts: 127.0.0.1
  connection: local

# 只在一台主机上执行 
run_once: true

# if else 使用
debug: 
  msg: "{{ 'me' if st.stat.exists else 'you' }}"

# in 条件的使用
when: 'item.id | string not in sh_vlan_id'

# 多行模式
shell: |
  This text
  has multiple
  lines
作者: aisuhua