如何在开始使用ansible剧本时添加空格

时间:2019-07-06 06:08:48

标签: ansible

我写了一个可笑的剧本,在文件末尾添加了2个变量。有一个文件/home/ec2-user/etc_hosts/tasks/main.yml,其IP地址和主机名为https://github.com/shettypriy/ansible/blob/master/ansible

我正在尝试插入新的IP地址和相应的主机名。我写的剧本添加了主机名和IP地址,但没有缩进,如此处https://github.com/shettypriy/ansible/blob/master/no_indentation

添加新的IP地址和主机名后如何维护缩进

- name: updating etc_hosts/tasks/main.yml
  blockinfile:
     path: /home/ec2-user/etc_hosts/tasks/main.yml
     insertafter: "^with_items"
     marker: ""
     block: |
        "{{ new_server_ip }} {{ server_name }}"
     backup: yes

1 个答案:

答案 0 :(得分:0)

管道后的数字|告诉Jinja2下一个缩进开始的位置。问题中的代码缩进3个空格。让我们使用它。这意味着该块的第一列(在字母“ c”下方)从上一个缩进级别(在字母“ b”下方)向右开始3个空格。

block: |3
   This line starts at 1st column

让我们再向右移动4个空格以对齐新行 with_items:

block: |3
       - "{{ new_server_ip }} {{ server_name }}"

没有显式缩进|<number> block 的默认配置是去除所有空格。

示例1。

正则表达式不起作用,因为 with_items 不在第一列开始

insertafter: "^with_items"

正确的代码

   insertafter: "^\\s*with_items:(.*)$"
   block: |3
           - "ww4.xx4.yy4.zz4 hostname4"

给予

- name: add server name and ip address in /etc/hosts file
  lineinfile: dest=/etc/hosts line="{{ item }}"
  with_items:
# BEGIN ANSIBLE MANAGED BLOCK
     - "ww4.xx4.yy4.zz4 hostname4"
# END ANSIBLE MANAGED BLOCK
     - "ww1.xx1.yy1.zz1 hostname1"
     - "ww2.xx2.yy2.zz2 hostname2"
     - "ww3.xx3.yy3.zz3 hostname3"

示例2。

下面的代码

   insertafter: EOF
   block: |3
           - "ww4.xx4.yy4.zz4 hostname4"

给予

- name: add server name and ip address in /etc/hosts file
  lineinfile: dest=/etc/hosts line="{{ item }}"
  with_items:
     - "ww1.xx1.yy1.zz1 hostname1"
     - "ww2.xx2.yy2.zz2 hostname2"
     - "ww3.xx3.yy3.zz3 hostname3"
# BEGIN ANSIBLE MANAGED BLOCK
     - "ww4.xx4.yy4.zz4 hostname4"
# END ANSIBLE MANAGED BLOCK

注意。如果没有标记marker: "",模块就不是幂等的。

相关问题