9.ansible之定义变量

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'
复制代码

 

posted on   太白金星有点烦  阅读(112)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2022-05-17 5.处理MongoDB的Jumbo Chunk

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示