记录各种模块的使用方法
打印主机信息
gather_facts
# 收集目标主机的系统信息 可通过 {{ ansible_facts['key'] }} 引用
# 默认开启
# 关闭(可提升执行效率)
gather_facts: false
# 选择性关闭(如果 tags 包含state、reboot则关闭,否则启用)
gather_facts:"{{ 'no' if 'state' in ansible_run_tags or 'reboot' in ansible_run_tags else 'yes' }}"debug
---
- name: Check if rsync is installed and get its version
hosts: all
gather_facts: yes
tasks:
- name: Display Others
debug:
var: ansible_facts['distribution'],ansible_facts['distribution_version'] # 系统版本
## 结果
# TASK [Display Others]
# ************************************************************************************************
# ok: [172.21.27.39] => {
# "ansible_facts['distribution'],ansible_facts['distribution_version']": "('Anolis', '7.9')"
# }
# 或者
msg: "{{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}"
## 结果
# TASK [Display Others]
# ************************************************************************************************
# ok: [172.21.27.39] => {
# "msg": "Anolis 7.9"
# }
# 忽略 msg 中的换行符(编码时友好)
msg: >
OS: {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }},
Kernel: {{ ansible_facts['kernel'] }}
## 结果
# TASK [Display Others] **************************************************************************
# ok: [172.21.27.39] => {
# "msg": "OS: Anolis 7.9, Kernel: 4.19.91-27.4.an7.x86_64\n"
# }
变量
自定变量的使用方法和 ansible 系统变量一样
---
- name: Check if rsync is installed and get its version
hosts: all
gather_facts: yes
tasks:
- name: Display Others
vars:
Old_OS_Version: "7.7" # 定义
# 还可以 Old_OS_Version: {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}
debug:
msg: >
OS_Version: {{ Old_OS_Version }} >> {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}
# 结果
# TASK [Display Others] *********************************************************************************************
# ok: [172.21.27.39] => {
# "msg": "OS_Version: 7.7 >> Anolis 7.9\n"
# }
# 变量文件分割 和 变量的列表形式
# test_vars.yaml
http_port: 80 # 字典形式
db_config: # 列表形式,方便调用
host: "db.example.com"
user: "admin"
# foo.yaml
---
- name: Dispaly
hosts: all
gather_facts: no
vars_files:
- ./test_vars.yaml # 加载外部变量文件
tasks:
- name: Display Others
debug:
msg: "Port: {{ http_port }}, DB host: {{ db_config.host }}"
# 结果
# TASK [Display Others] ***********************************************************************************
# ok: [172.21.27.39] => {
# "msg": "Port: 80, DB host: db.example.com"
# }