Ansible支持十几种定义变量的方式,其中常用的有如下:
- Inventory变量
- Host Facts变量
- Register变量
- Playbook变量
- Playbook提示变量
- 变量文件
- 命令行变量
1)Inventory(在主机清单配置文件中定义变量)
[root@db04 ansible]# cat hosts [test] db01 myvar1="hello the world" myvar2="content" db02
这里写一个yml文件
[root@db04 ansible]# cat inventory_var.yml --- - hosts: db01 tasks: - name: create a file with var. shell: echo {{myvar1}}>/tmp/{{myvar2}}
从yml文件中可以看出,myvar1在主机清单文件中被赋值为"hello the world", myvar2变量被赋值为"content"
然后再执行这个yml文件:ansible-playbook inventory_var.yml
2) Host Facts变量(可以直接调用ansible收集系统信息)
[root@db04 ansible]# cat facts_var.yml --- - hosts: db01 tasks: - name: Use facts info. copy: content: "{{ansible_hostname}}:{{ansible_bios_version}}" dest: /tmp/facts.txt [root@db04 ansible]#
3)register语句可以将某个命令的执行结果保存在变量中
[root@db04 ansible]# cat register.yml --- - hosts: db01 tasks: - name: save shell result to a variable. shell: hostname register: myvar - name: print the varialbe's value through debug. debug: msg: "{{myvar}}"
4)Playbook变量(使用vars关键词可以在playbook内定义变量)
[root@db04 ansible]# cat playbook_var.yml --- - hosts: db01 vars: iname: heal ipss: '123' tasks: - name: Use variables create user. user: name: "{{iname}}" password: "{{ipss|password_hash('sha512')}}" [root@db04 ansible]#
5)剧本提示变量,这个变量类似于shell中的read命令
[root@db04 ansible]# cat prompt_var.yml --- - hosts: db01 vars_prompt: - name: iname prompt: "请输入用户名" private: no - name: ipasswd prompt: "请输入密码" private: yes tasks: - name: create users user: name: "{{iname}}" password: "{{ipasswd|password_hash('sha512')}}"
6)单独定义变量文件(variables.yml),在playbook中用vars_files调用该文件
[root@db04 ansible]# cat variables.yml --- iname: cloud ipass: '123' [root@db04 ansible]# cat playbook_var.yml --- - hosts: db01 vars: iname: heal ipss: '123' tasks: - name: Use variables create user. user: name: "{{iname}}" password: "{{ipss|password_hash('sha512')}}"
7) 执行ansible-playbook命令时使用-e参数定义变量
[root@db04 ansible]# cat command_var.yml --- - hosts: db01 tasks: - name: create a user user: name: "{{iname}}" password: "{{ipass|password_hash('sha512')}}" [root@db04 ansible]# [root@db04 ansible]# ansible-playbook command_var.yml -e iname=tiechui -e ipass='123'
标签:变量,定义,ansible,root,yml,db04,name From: https://www.cnblogs.com/zmc60/p/17410587.html