当文件也包含换行时,如何将文件内容存储到ansible中

时间:2019-07-08 08:43:55

标签: ansible

我正在尝试使用以下任务将certificate.pem文件的内容存储到变量中:

 - name: Get the contents of the root certificate
   shell: cat {{ ca_certificate_file }}

 - name: Decode data and store as fact
   set_fact:
     root_certificate_content: "{{ ca_certificate_data.stdout }}"

变量root_certificate_content具有文件的全部内容,但是用空格代替它而不是换行。我有一种方法可以获取变量中的证书内容。

1 个答案:

答案 0 :(得分:0)

尝试lookup plugins

- set_fact:
    root_certificate_content: "{{ lookup('file', ca_certificate_file) }}"

例如“ the variable "root_certificate_content" should have the contents of the file as it is. If the file has a new line then it should come as the new line”。下面的游戏

- hosts: localhost
  tasks:
    - set_fact:
        root_certificate_content: "{{ lookup('file', 'cert1') }}"
    - debug:
        msg: "{{ root_certificate_content.split('\n') }}"

包含文件(每行3行,每行换行)

$ cat cert1 
line 1
line 2
line 3

提供变量 root_certificate_content 的内容(每行三行,换行符)

"msg": [
    "line 1", 
    "line 2", 
    "line 3"
]

if you just show the value of root_certificate_content without using .split('\n') in the debug msg

- debug:
    var: root_certificate_content

然后可以在字符串中看到换行符

"root_certificate_content": "line 1\nline 2\nline 3"