ansible变量引用

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文件语法

3. 在/etc/ansible下新建目录host_vars
    写入变量文件名要以主机ip或者绑定的host命名
    cat host_vars/192.168.163.130
    key: 192.168.163.130
    ansible-playbook var.yaml

4. 针对主机组设置变量
    在/etc/ansible下新建group_vars
    变量文件以主机组命名
    cat group_vars/test  && rm -rf host_vars
    key: abcdefg

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 }}"

8. 在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 }}"
9. 使用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']}具体输出某个字段的值

10. 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 }}"

 

posted @ 2019-12-03 23:05  MlxgzZ  阅读(459)  评论(0编辑  收藏  举报