Ansible - 定义变量

发布时间 2024-01-13 14:21:12作者: HOUHUILIN

 

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行 如果不是以双花括号开头则不需要加引号。