Ansible ansible playbook 中使用 template 如何让调用的变量被使用后生成的文件中 文本是顶格的

yinghai9989 · 2019年11月05日 · 最后由 yinghai9989 回复于 2019年11月06日 · 196 次阅读

问题如下:

### 定义 hosts 文件

node_hosts:
"127.0.0.1 localhost\n
172.171.8.10 controller10\n
172.171.8.11 compute11 swift11\n
172.171.8.12 compute12 swift12\n

# The following lines are desirable for IPv6 capable hosts\n
::1 localhost ip6-localhost ip6-loopback\n
ff02::1 ip6-allnodes\n
ff02::2 ip6-allrouters\n"

+++++++++++++++++++++++++++++++++++++++++++++++++++++++

在 playbook 的 roles 中如下语句

  • name: Create the hosts file for all machines
    template: src=hosts.j2 dest=/etc/hosts
    tags:
    • common2

希望得到的结果

root@compute11:~# cat /etc/hosts
127.0.0.1 localhost
172.171.8.10 controller10
172.171.8.11 compute11 swift11
172.171.8.12 compute12 swift12

#The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

就是 172 开头的多空一格,

请问如何出掉这一格

首先,论坛是支持 makedown 格式的,可以先看下排版说明

你的这个问题,应该是你node_hosts赋值的时候带上了这个空格,可以使用 jinja2 模板的特性解决。不需要在每行中加上换行符

---
- hosts: localhost
  vars:
    node_hosts: |
     127.0.0.1 localhost
     172.171.8.10 controller10
     172.171.8.11 compute11 swift11
     172.171.8.12 compute12 swift12

     # The following lines are desirable for IPv6 capable hosts
     # ::1 localhost ip6-localhost ip6-loopback
     # ff02::1 ip6-allnodes
     # ff02::2 ip6-allrouters
  tasks:
    - template: src=hosts.j2 dest=/tmp/hosts

谢谢大神的指点,已经实现需求

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册