ansible的介绍和使用3(ansible中变量的介绍和使用)

1.变量的基础介绍和应用

在ansible中使用变量,能让我们的工作变得更加灵活,在ansible中,变量的使用方式有很多种,我们慢慢聊。 

先说说怎样定义变量,变量名应该由字母、数字、下划线组成,变量名需要以字母开头,ansible内置的关键字不能作为变量名。

1.playbook中变量的定义和引用方法

如果我们想要在某个play中定义变量,可以借助vars关键字,示例语法1如下

---
- hosts: test70
  vars:
    testvar1: testfile
  remote_user: root
  tasks:
  - name: task1
    file:
      path: /testdir/{{ testvar1 }}
      state: touch

上例中,先使用vars关键字,表示在当前play中进行变量的相关设置。

vars关键字的下一级定义了一个变量,变量名为testvar1,变量值为testfile

当我们需要使用testvar1的变量值时,则需要引用这个变量,如你所见,使用"{{变量名}}"可以引用对应的变量。

多变量定义语法格式

格式1

vars:
  testvar1: testfile
  testvar2: testfile2

格式2(块序列语法)

vars:
  - testvar1: testfile
  - testvar2: testfile2

格式3

---
- hosts: test70
  remote_user: root
  vars:
    nginx:
      conf80: /etc/nginx/conf.d/80.conf
      conf8080: /etc/nginx/conf.d/8080.conf
  tasks:
  - name: task1
    file:
      path: "{{nginx.conf80}}"
      state: touch
  - name: task2
    file:
      path: "{{nginx.conf8080}}"
      state: touch

上述格式3,用类似"属性"的方式定义变量,上述格式3定义了两个变量,两个变量的值对应两个nginx配置文件路径

格式3定义变量,引用语法如下

1.

"{{nginx.conf80}}"

2.

"{{nginx['conf8080']}}"

这里需要注意一点就是,当我们引用变量的的时候,如果变量被引用时,处于冒号之后(:),我们引用变量时必须使用双引号引起被引用的变量,否则会报语法错误。如下所示:

path: "{{nginx.conf80}}"

2.文件中变量的定义和引用

除了能够在playbook中直接定义变量,我们还可以在某个文件中定义变量,然后再在playbook中引入对应的文件,引入文件后,playbook即可使用文件中定义的变量,当想要让别人阅读你的playbook,却不想让别人看到某些值,可以使用这种办法,因为别人在阅读playbook时,只能看到引入的变量名,但是看不到变量对应的值,这种将变量分离到某个文件中的做法叫做"变量文件分离""变量文件分离"除了能够隐藏某些值,还能够让你将不同类的信息放在不同的文件中,并且让这些信息与剧本主体分开

首先,我们来定义一个专门用来存放nginx相关变量的文件(文件名为nginx_vars.yml),在文件中定义变量时,不要使用vars关键字,直接定义变量即可,定义变量的语法与在playbook中定义变量的几种语法相同

语法一示例:
  testvar1: testfile
  testvar2: testfile2
语法二示例:
  - testvar1: testfile
  - testvar2: testfile2
语法三示例:
nginx:
  conf80: /etc/nginx/conf.d/80.conf
  conf8080: /etc/nginx/conf.d/8080.conf
# cat nginx_vars.yml
nginx:
  conf80: /etc/nginx/conf.d/80.conf
  conf8080: /etc/nginx/conf.d/8080.conf

在playbook引用变量文件中的变量语法格式如下,在playbook中引入包含变量的文件时,需要使用"vars_files"关键字,被引入的文件需要以"- "开头,以YAML中块序列的语法引入,

---
- hosts: testB
  remote_user: root
  vars_files:
  - /testdir/ansible/nginx_vars.yml
  tasks:
  - name: task1
    file:
      path={{nginx.conf80}}
      state=touch
  - name: task2
    file:
      path={{nginx['conf8080']}}
      state=touch

上例中"vars_files"关键字只引入了一个变量文件,也可以引入多个变量文件每个被引入的文件都需要以"- "开头,示例如下

  vars_files:
  - /testdir/ansible/nginx_vars.yml
  - /testdir/ansible/other_vars.yml

"vars"关键字和"vars_files"关键字可以同时使用,如下

  vars:
  - conf90: /etc/nginx/conf.d/90.conf
  vars_files:
  - /testdir/ansible/nginx_vars.yml
原文地址:https://www.cnblogs.com/qingbaizhinian/p/14097459.html