无法将只读字符串添加到文件

问题描述 投票:0回答:1

我无法使用 lineinfile 将“readOnly: true”添加到文件中。

示例 1 - 当我使用此代码时:

- name: Insert vsphere mountPath
  lineinfile:
    path: /etc/kubernetes/manifests/kube-controller-manager.yaml
    insertbefore: "hostNetwork: true"
    line: "{{ item }}"
  with_items: 
    - "    - mountPath: /etc/kubernetes/vsphere.conf"
    - "      name: vsphere-config"
    - "      readOnly: true"

我在 kube-controller-manager.yaml 中得到这个(如您所见,只读:缺少 true):

    - mountPath: /etc/kubernetes/vsphere.conf
      name: vsphere-config
  hostNetwork: true

示例 2 - 当我使用此代码时:

- name: Insert vsphere mountPath
  lineinfile:
    path: /etc/kubernetes/manifests/kube-controller-manager.yaml
    insertbefore: "hostNetwork: true"
    line: "{{ item }}"
  with_items: 
    - "    - mountPath: /etc/kubernetes/vsphere.conf"
    - "      name: vsphere-config"
    - "      readOnly2: true"

我在 kube-controller-manager.yaml 中得到这个(当我使用字符串 ReadOnly2 而不是 ReadOnly 时它有效):

    - mountPath: /etc/kubernetes/vsphere.conf
      name: vsphere-config
      readOnly2: true
  hostNetwork: true

示例 3 - 当我使用此代码时:

- name: Insert vsphere mountPath
  lineinfile:
    path: /etc/kubernetes/manifests/kube-controller-manager.yaml
    insertbefore: "hostNetwork: true"
    line: "{{ item }}"
  with_items: 
    - "    - mountPath: /etc/kubernetes/vsphere.conf"
    - "      name: vsphere-config"
    - "      'readOnly': true"

我在 kube-controller-manager.yaml 中得到这个(但我需要只读而不是“只读”):

    - mountPath: /etc/kubernetes/vsphere.conf
      name: vsphere-config
      'readOnly': true
  hostNetwork: true

我应该怎么做才能在文件中包含以下行?

    - mountPath: /etc/kubernetes/vsphere.conf
      name: vsphere-config
      readOnly: true
  hostNetwork: true
ansible ansible-2.x
1个回答
0
投票

最初,我在使用

blockinfile
时丢失了前导空格。

那是因为

block: |2
保持前导空格在 Ansible 2.14.2 中不再起作用。

block: |2
    insert something

所以我不得不添加评论作为解决方法以保留前导空格:

block: |
  # comment
    insert something

除此之外,我在同一个文件中添加了多个块,所以我必须确保我添加的每个块都有不同的

marker

marker: "# Something"

那么我的最终代码是:

- name: Insert vsphere mountPath
  blockinfile:
    path: /etc/kubernetes/manifests/kube-controller-manager.yaml
    insertbefore: "hostNetwork: true"
    block: |
      # Adding parameters:
          - mountPath: /etc/kubernetes/vsphere.conf
            name: vsphere-config
            readOnly: true
    marker: "# ANSIBLE BLOCK FOR VSPHERE"
© www.soinside.com 2019 - 2024. All rights reserved.