facts
facts变量是在运行剧本时,ansible收集的机器信息。
查看所有内置变量
ansible web -m setup
使用
use_facts.yml
- hosts: web
tasks:
- name: get ip by facts
debug:
msg: 通过 facts 变量 获取IP {{ ansible_default_ipv4.address }}
常用fact变量
ansible_hostname #主机名
ansible_memtotal_mb #内存大小(总计)单位mb
ansible_processor_vcpus #cpu数量
ansible_default_ipv4.address #默认的网卡ip eth8
ansible_distribution #系统发行版本名字 Centos ubuntu Debian
示例
使用fact变量向服务器分发motd文件
使用template模块分发
模板文件
motd.j2
#主机名: {{ ansible_hostname }}
#内存MB: {{ ansible_memtotal_mb }}
#CPU数量: {{ ansible_processor_vcpus }}
#IP: {{ ansible_default_ipv4.address }}
06_motd.yaml
- hosts: web web_proxy
tasks:
- name: gen motd
template:
src: ./motd.j2
dest: /etc/motd
backup: yes
templae模块
用法与copy基本一致,但是他可以解析模板文件中的变量,并赋值,可以用来推送配置文件等。
register
register
关键字用于捕获任务(task)的输出,并将其存储为一个变量。可以在后续的任务中使用或引用这个变量。register
通常用于调试、记录任务输出或根据前一个任务的结果来决定后续任务的执行。
- name: Execute a command and capture the output
command: /usr/bin/some-command
register: command_output
- name: Debug the command output
debug:
msg: "The command output is: {{ command_output.stdout }}"
这个例子中,首先执行了一个命令,并使用register
关键字将命令的输出存储到名为command_output
的变量中。然后在下一个任务中使用debug
模块来打印这个变量的内容。
command_output
变量是一个包含任务执行结果的字典,其中stdout
键包含了命令的标准输出。stdout_lines
则是一个包含标准输出每一行的列表。还有其他一些可能的键,如stderr
(标准错误输出)、rc
(返回码)等,具体取决于您执行的任务类型。
请注意,register
捕获的是整个任务的结果,而不仅仅是命令的输出。对于不同的模块,结果可能包含不同的信息。例如,对于shell
或command
模块,结果通常包含stdout
、stderr
和rc
等;而对于file
模块,结果可能包含文件的状态信息等。
使用register
时,要确保变量名在Ansible playbook中是唯一的,以避免命名冲突。此外,注册的变量在当前playbook的所有后续任务中都是可用的,直到playbook执行结束。
示例,根据时间创建文件
10_reg.yaml
- hosts: web
tasks:
- name: get time
command: date +%F_%w
register: timestamp
- name: output time
debug:
msg: "{{ timestamp.stdout }}"
- name: touch timestamp fiel
file:
state: touch
path: /tmp/{{ timestamp.stdout }}
运行结果