1. 在/etc/ansible/hosts默认文件中定义变量
    [test]
    192.168.163.130
    #[test:vars]
    #key=ansible
    或者
    192.168.163.130 key=ansible
    [test]
    192.168.163.130
  2. 编写var.yaml文件
  • hosts: test
    gather_facts: False
    tasks:
    - name: display Host Variable from hostfile
    debug: msg=“The {{ inventory_hostname }} Vaule is {{ key }}”

ansible-playbook var.yaml #检查yaml文件语法
ansible变量引用
ansible变量引用
3. 在/etc/ansible下新建目录host_vars
写入变量文件名要以主机ip或者绑定的host命名
cat host_vars/192.168.163.130
key: 192.168.163.130
ansible-playbook var.yaml
ansible变量引用
4. 针对主机组设置变量
在/etc/ansible下新建group_vars
变量文件以主机组命名
cat group_vars/test && rm -rf host_vars
key: abcdefg
ansible变量引用
5. 手动传入变量,可传入多个变量
ansible-playbook var.yaml -e “key=JSON”

6.支持文件传入变量
变量文件支持YAML和JSON两种格式
cat vars.yaml
key: KEY-YAML
cat var.json
{“key”: “KEY_JSON”}
ansible-playbook var.yaml -e “@var.json”
7. 在playbook文件内使用vars

  • hosts: test
    gather_facts: False
    vars:
    key: Ansible-KEY
    tasks:
    - name: display Host Variable from hostfile
    debug: msg=“The {{ inventory_hostname }} Vaule is {{ key }}”
  1. 在playbook文件使用vars_files
  • hosts: test
    gather_facts: False
    vars_files:
    - vars.yaml 或者group_vars/test
    tasks:
    - name: display Host Variable from hostfile
    debug: msg=“The {{ inventory_hostname }} Vaule is {{ key }}”
  1. 使用register内的变量
    cat var.yaml
  • hosts: test
    gather_facts: False
    tasks:
    - name: register variable
    shell: hostname
    register: aaaaa  #输出结果为python字典
    - name: display Host Variable from hostfile
    debug: msg=“The {{ inventory_hostname }} Vaule is {{ aaaaa }}” #{aaaaa[‘stdout’]}具体输出某个字段的值
    ansible变量引用
  1. vars_prompt传入参数
    cat var.yaml
  • hosts: test
    gather_facts: False
    vars_prompt:
    - name: “aaa”
    prompt: “please input aaa value”
    default: ‘123’
    private: no
    - name: “bbb”
    prompt: “please input bbb value”
    default: ‘456’
    private: yes
    tasks:
    - name: display aaa value
    debug: msg=“aaa value is {{ aaa }}”
    - name: display bbb value
    debug: msg=“bbb value is {{ bbb }}”
    ansible变量引用
    ansible变量引用

相关文章:

  • 2022-12-23
  • 2021-11-13
  • 2021-05-25
  • 2022-02-21
  • 2022-12-23
  • 2021-05-16
  • 2021-11-28
猜你喜欢
  • 2022-02-24
  • 2021-05-18
  • 2021-09-19
  • 2021-12-30
  • 2021-11-24
  • 2021-12-11
  • 2021-12-19
相关资源
相似解决方案