Ansible - 定义变量

HOUHUILIN / 2024-01-13 / 原文

 

Ansible 支持十几种定义变量的方式

  • Inventory 变量
  • Host Facts 变量
  • Register 变量
  • Playbook 变量
  • Playbook 提示变量
  • 变量文件
  • 命令行变量

 

 

Inventory 变量

1、定义变量(在主机清单配置文件中进行定义)

[root@control ansible]# cat ~/ansible/hosts
[test]
node1 myvar1="hello world" myvar2="content"
[proxy]
node2
[webserver]
node[3:4]
[webserver:vars]
yourname="jacob"

2、使用变量(以下是以playbook的场景演示变量的使用)

[root@control ansible]# cat ~/ansible/inventory_var.yml
---
- hosts: test
  tasks:
    - name: create a file with var.
      shell: echo {{ myvar1 }} >/tmp/{{myvar2}}
- hosts: webserver
  tasks:
    - name: create a user with var.
      user:
        name: "{{ yourname }}"

第11行 以双花括号开始的时候,需要用双引号引起来,第6行 如果不是以双花括号开头则不需要加引号。

 

 

 

Host Facts 变量

Host Facts 变量(可以直接调用ansible收集的系统信息)

[root@control ansible]# cat ~/ansible/facts_var.yml
---
- hosts: test
  tasks:
    - name: Use facts info.
      copy:
        content: "{{ansible_hostname}}:{{ansible_bios_version}}"
        dest: /tmp/facts.txt

上述playbook可以将目标主机名及其bios版本号输出到目标主机/tmp/facts.txt文件中