对于重复使用而且复杂的参数值,可以定义变量引用,便于管理和修改,也可以创建文件存放变量,引用变量文件即可
示例如下
[[email protected] ansible]# tree .
.├── ansible.cfg├── backup│ └── backup.sh├── hosts├── roles├── vars ============>存放变量的目录│ └── httpd.yml =========>存放变量的文件└── work ===========================>工作目录├── apache_config_1.yml ├── apache_config.yml├── apache_create.yml├── apache_remove.yml变量写法要主要格式和缩进[[email protected] ansible]# cat vars/httpd.yml #apache varsapache:conf: /etc/httpd/conf/httpd.confvhost: /etc/httpd/vhost引用方法:"{{apache.conf}}"如下方式创建apache的虚拟主机:
需要注意的是对同一文件多次blockin时,marker很重要,否则会覆盖上次插入的内容
[[email protected] ansible]# cat work/apache_config.yml
-
hosts: jack6-2
remote_user: rootvars_files:- /etc/ansible/vars/httpd.ymltasks:
- name: insert lineblockinfile:path: "{{apache.conf}}"block: "Listen 8888\nInclude vhost/*.conf"insertafter: EOFmarker: "#{mark} 8888"
- name: cat shell: grep ^Include {{apache.conf}}
- name: DocumentRootfile:path: "{{apache.droot}}"state: directory
-
name: insert block
blockinfile:path: "{{apache.vconf}}"block: "<VirtualHost *:8888>\n\tDocumentRoot /data/www/html\n\tServerName myvhost.com\n\t<Directory /data/www/html>\n\t\tAllowOverride None\n\t\tRequire all granted\n\t\tSatisfy Any\n\t\tOrder allow,deny\n\t\tAllow from all\n\t</Directory>\n</VirtualHost>" insertbefore: BOFbackup: yesnotify: reload_httpd - meta: flush_handlers
- name: insert contentblockinfile:path: "{{apache.vhtml}}"block: "Hello my bro! Welcome to My Website."insertbefore: BOFcreate: yesmarker: "#{mark} WHAT FCK"backup: yes
handlers:
- name: reload_httpdservice:name: httpdstate: reloaded
###########################################################################
当我们需要使用testvar1的变量值时,则需要引用这个变量,如你所见,使用"{{变量名}}"可以引用对应的变量。也可以定义多个变量,示例如下。
Shell
vars:testvar1: testfiletestvar2: testfile2123vars:testvar1: testfiletestvar2: testfile2除了使用上述语法,使用YAML的块序列语法也可以定义变量,示例如下
Shell
vars:- testvar1: testfile
- testvar2: testfile2123vars:
- testvar1: testfile
- testvar2: testfile2
在定义变量时,还能够以类似"属性"的方式定义变量,示例如下
- hosts: test70remote_user: rootvars:nginx:conf80: /etc/nginx/conf.d/80.confconf8080: /etc/nginx/conf.d/8080.conftasks:
- name: task1file:path: "{{nginx.conf80}}"state: touch
- name: task2file:path: "{{nginx.conf8080}}"state: touch
- hosts: test70remote_user: rootvars:nginx:conf80: /etc/nginx/conf.d/80.confconf8080: /etc/nginx/conf.d/8080.conftasks:
- name: task1file:path: "{{nginx.conf80}}"state: touch
- name: task2file:path: "{{nginx.conf8080}}"state: touch如上例所示,我定义了两个变量,两个变量的值对应两个nginx配置文件路径
当我们需要引用这两个变量时,有两种语法可用
语法一
Shell
"{{nginx.conf80}}"1"{{nginx.conf80}}"语法二Shell
"{{nginx['conf8080']}}"1"{{nginx['conf8080']}}"而在上述后面的示例中引用变量时,变量被引用时如下,处于"开头的位置"
Shell
path: "{{nginx.conf80}}"1path: "{{nginx.conf80}}"这种情况下,我们引用变量时必须使用双引号引起被引用的变量,否则会报语法错误"vars"关键字和"vars_files"关键字可以同时使用,如下
Shell
vars:- conf90: /etc/nginx/conf.d/90.confvars_files:
-
/testdir/ansible/nginx_vars.yml
vars:
- conf90: /etc/nginx/conf.d/90.confvars_files:
- /testdir/ansible/nginx_vars.yml
精彩评论