在ansible中,可以通过变量传递参数,传参方式有命令行变量、filter、role、文件或剧本中定义变量等,变量名是以字母开头的字母、数字和下划线的组合。
变量调用优先级:
命令行-e > playbook定义 > hosts普通变量 > host分组变量
0x01 命令行指定变量
# 命令格式 ansible-playbook –e varname=value # playbook.yml - hosts: webservice remote_user: root tasks: – name: install_package yum: name={{ varname }} – name: start service service: name={{ varname }} state=started enabled=yes
0x02 在playbook中定义
# playbook.yml - hosts: webservice remote_user: root vars: - username: demo_user - groupname: demo_group tasks: - name: create_group group: name={{ groupname }} state=present - name: create_user user: name={{ username }} group{{ groupname }} home=/home/{{ username }}dir
0x03 在/etc/ansible/hosts中定义
hosts普通变量示例:
# /etc/ansible/hosts [webservice] 10.10.10.101 username=lzl hstname=httpd 10.10.10.102 username=lrx hstname=nginx # playbook.yml - hosts: webservice remote_user: root tasks: - name: set_hostname hostname: name={{ hstname }}-{{ username }}
公共/分组变量示例:
# /etc/ansible/hosts [webservice:vars] hstname=webservice # playbook.yml - hosts: myhosts remote_user: root tasks: - name: set_hostname hostname: name={{ hstname }}-{{ username }}
0x04 调用变量文件
# vars.yml username: liuzl groupname: root # playbook.yml - hosts: webservice remote_user: root vars_files: - vars.yml tasks: - name: create_log file: name=/root/{{ groupname }}-{{ username }}.log state=touch
0x05 调用setup变量
远程主机的所有变量都可直接调用,filter是用来匹配字符串,可以使用正则表达式,也可以使用grep过滤,-C选项查看前后三行。
ansible myhosts -m setup -a 'filter=ansible_nodename' ansible myhosts -m setup -a 'filter=ansible*mb'
0x06 在role中定义
在ansible中,template的功能是根据模块文件动态生成对应的配置文件,它是基于Jinja2语言的文本文件,必须存放于templates目录下,扩展名为.j2,目录结构如下:
./ ├── tpl_nginx.yml └── templates └── nginx.conf.j2
示例:
# nginx.conf.j2 Listen {{tcp_port}} ServerName {{server_name}} MaxClients {{access_num}} # /etc/ansible/hosts [webservice] 10.10.10.202 tcp_port=0.0.0.0:80 access_num=1000 server_name="www.olzl.net" # playbook.yml - hosts: webservice remote_user: root tasks: - name: install_nginx yum: name=nginx - name: templates_1 template: src=nginx_1.conf.j2 dest=/etc/nginx/nginx.conf when: ansible_distribution_major_version == "7" notify: restart nginx tags: conf - name: templates_2 template: src=nginx_2.conf.j2 dest=/etc/nginx/nginx.conf when: ansible_distribution_major_version == "8" notify: restart_nginx tags: conf - name: start_nginx service: name=nginx state=started handlers: - name: restart_nginx service: name=nginx state=restarted
原创文章禁止转载:技术学堂 » Ansible自动化运维之Playbook变量传参