linux--ansible(playbook5 变量1)

本文介绍了Ansible Playbook中变量的定义方法,包括两种定义方式,以及如何定义多个变量。还讨论了变量文件分离的实践,详细解释了如何将变量写入文件并在playbook中引用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vars

定义方法

第一种定义方法

---
- hosts: testB
  vars:                 定义变量
    var1: file          变量值
  remote_user: root
  tasks:
  - name: touch file
    file: path=/testdir/{{var1}} state=touch

在这里插入图片描述
第二种定义方法

---
- hosts: testB
  vars:
    - var1: file
  remote_user: root
  tasks:
  - name: touch file
    file: path=/testdir/{{var1}} state=touch

定义多个变量

第一种

---
- hosts: testB
  vars:
    - var1: file
    - var2: file2
  remote_user: root
  tasks:
  - name: touch file
    file: path=/testdir/{{var1}} state=touch
  - name: touch file2
    file: path=/testdir/{{var2}} state=directory

第二种

---
- hosts: testB
  vars:
    var1: file
    var2: file2
  remote_user: root
  tasks:
  - name: touch file
    file: path=/testdir/{{var1}} state=touch
  - name: touch file2
    file: path=/testdir/{{var2}} state=directory

在这里插入图片描述
第三种:属性定义

  • 引用变量属于开头位置要用引号引起来
---
- hosts: testB
  remote_user: root
  vars:
    httpd:
      conf80: /etc/httpd/conf.d/80.conf
      conf8000: /etc/httpd/conf.d/8000.conf

  tasks:
   - name: task1
     file: path={{httpd.conf80}} state=touch
   - name: task2
     file:
       path: "{{httpd.conf8000}}"
       state: touch
---
- hosts: testB
  remote_user: root
  vars:
    httpd:
      conf80: /etc/httpd/conf.d/80.conf
      conf8000: /etc/httpd/conf.d/8000.conf

  tasks:
   - name: task1
     file: path={{httpd.conf80}} state=touch
   - name: task2
     file:
       path: "{{httpd['conf8000']}}"                      区别
       state: touch

在这里插入图片描述

变量文件分离

写入文件

vim httpd_vars.yml
httpd:
  conf80: /etc/httpd/conf.d/80.conf
  conf8000: /etc/httpd/conf.d/8000.conf

playbook:

---
- hosts: testB
  remote_user: root
  vars_files:
  - httpd_vars.yml
  tasks:
  - name: task1
    file: path={{httpd.conf80}}
          state=touch
  - name: task2
    file:
      path: "{{httpd['conf8000']}}"
      state: touch

在这里插入图片描述

---
- hosts: testB
  remote_user: root
  vars:
  - conf80: /etc/httpd/conf.d/80.conf
  vars_files:
  - httpd_vars.yml

  tasks:
  - name: task1
    file: path={{conf80}}
          state=touch
  - name: task2
    file:
      path: "{{httpd['conf8000']}}"
      state: touch
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值