Kubernetes ConfigMap打印"\n"而不是换行符

26

我正在尝试将一个配置映射部署到一个集群中

- name: Make/Update all configmaps on the cluster
 kubernetes:
 api_endpoint: blah
 url_username: blah
 url_password: blah
 inline_data:
 apiVersion: v1
 kind: ConfigMap
 metadata: 
 name: blah
namespace: blah
 data: my-data.txt: "{{ data }}"
 state: present
data: |
 some = foo
 foo = some
(using spinnaker to attach it to pods)

当我进入舱室并打开 my-data.txt 文件时,它会显示:

some = foo\n foo = some\n

我希望它的显示与文本完全一样,并打印换行符而不是 /n

奇怪的是,如果我在文本中某处放置单引号' ',它会将文本原样打印,但包括单引号:

data: |
 some = foo
 foo = some
' '

打印出完全相同。

我尝试过研究,但我找不到任何东西,而且我已经被卡住了一段时间。


1
请修复所提供代码片段中的缩进。 - Halis
6个回答

16
这似乎与创建来自文件的configMap时的kubernetes/kubernetes issue 36222类似。
在您的情况下,这发生在创建了一个data块时。
最近的kubernetes/kubernetes issue 63503引用了所有已打印的问题。
一个评论提到

我使用Tab键添加了一个新行到configMap中。在改为使用空格而不是Tab后,我能够按预期看到configMap...

202年8月:issue 36222现在包括:

If you just want the raw output as it was read in when created --from-file, you can use jq to get the raw string (without escaped newlines etc)

If you created a configmap from a file like this:

kubectl create configmap myconfigmap --from-file mydata.txt

Get the data:

kubectl get cm myconfigmap -o json | jq '.data."mydata.txt""' -r
此外:

If the formatting of cm goes wierd a simple hack to get it back to normal is :

kubectl get cm configmap_name -o yaml > cm.yaml

Now copy the contents of cm.yaml file and past it on yamllint.com. Yamllint.com is powerful tool to check the linting of yaml files.
This will provide you with the configmap as expected with correct formatting.

Paste the output in another yaml file (for e.g - cm_ready.yaml)

 kubectl apply -f cm_ready.yaml

更新于2020年11月,同样的问题包括:
我能够通过以下方式修复这个问题: - 不要使用制表符,转换为空格 - 要删除换行符前的空格,请使用以下命令: `sed -i -E 's/[[:space:]]+$//g' File.ext` 它似乎还会将CRLF转换为LF。
更新 2023年11月, 超罗 补充说:

Finally, I found that the absence of a value defined in values.yaml will cause the \n issue.

data: {{ .Values.application.data}}

application.data is not defined in my yaml


1
yamllint.com 这个网站很神奇,直接使用即可 :D - Tara Prasad Gurung

13

使用 Kubernetes 1.20.2,该问题可以通过以下方法解决:

  • 使用以下命令去除末尾的空格: sed -i -E 's/[[:space:]]+$//g' file.txt
  • 使用以下命令将制表符替换为空格: sed -i 's/\t/ /g' file.txt (警告:需要手动管理空格数量!)
  • 删除文件末尾的空行

3
移除行末空格就足够了,尽管我已经在使用空格。对于我的情况来说,结尾的空行并不重要。 - Andrew
2
如果您正在使用VSCode,只需打开命令面板(在Mac上使用Cmd+Shift+P),然后运行“格式化文档”命令。它将清理YAML文件中的所有空格等内容,然后您就不应该再看到字符转义了。 - Rakib

3
根据Github问题所述,您需要删除每行末尾的所有空格,并确保没有任何特殊字符。
如果您正在编写程序,使用单行字符串比多行字符串更好。例如,在go中使用"" + "\n"而不是反引号。
正确的结果应该使用管道符|。最初的回答。
data: |
 some = foo
 foo = some

1
删除 data: 部分末尾的空行解决了我的问题(我使用的是yaml)。

0
在我的情况下,问题是我使用了CRLF行尾。切换到LF行尾并使用kubectl重新创建configmap会导致正确格式化的configmap资源。

0
在我的情况下,删除这两个字符解决了问题:
其他字符(如ℹ️✓⚠️✘)没有引起问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接