Ansible中能否实现cat功能?读取defaults/main.yml并注册变量
Hey there! Let's tackle your Ansible questions one by one:
问题1:Ansible中是否可实现类似cat命令的文件读取功能?
Absolutely! Ansible has you covered here—there are a couple of reliable ways to replicate the cat command's file-reading behavior:
slurpmodule (highly recommended): This is Ansible's purpose-built module for reading file contents. It returns the file's content as a Base64-encoded string (easy to decode later), works consistently across all supported target systems, and avoids the shell injection risks that come with running raw system commands. It’s the idempotent, "Ansible-native" way to do this.command/shellmodules: You can directly runcat /path/to/your/filevia these modules if you need a quick-and-dirty approach. That said, this relies on the target system having thecatutility installed, and it’s not as clean or secure as usingslurpfor production playbooks.
问题2:我希望读取defaults/main.yml文件内容并将其注册到一个变量中,该如何操作?
The best practice here is to use the slurp module, paired with a filter to decode the Base64 content into plain text. Here’s a complete, ready-to-use playbook snippet:
- name: Read and store defaults/main.yml content hosts: your_target_hosts # Replace with your actual host group/targets tasks: - name: Slurp the contents of defaults/main.yml ansible.builtin.slurp: # Use role_path if this task is inside an Ansible role; else use full absolute path path: "{{ role_path }}/defaults/main.yml" register: raw_default_yml - name: Decode Base64 content into a usable variable ansible.builtin.set_fact: decoded_default_yml: "{{ raw_default_yml.content | b64decode }}" # Optional: Debug step to verify the content (remove in production!) - name: Print the decoded file content ansible.builtin.debug: var: decoded_default_yml
Key notes:
- If you’re not running this task inside an Ansible role, replace
{{ role_path }}/defaults/main.ymlwith the full absolute path to your file (e.g.,/opt/ansible/roles/my_custom_role/defaults/main.yml). - The
slurpmodule returns a dictionary with two keys:content(the Base64-encoded text) andsource(the file path). - The
b64decodefilter converts the encoded string into plain text, making the content usable in subsequent tasks (like templating or condition checks).
If you really want to use cat (not recommended for production), here’s how you’d do it:
- name: Read defaults/main.yml using cat (not ideal) hosts: your_target_hosts tasks: - name: Run cat command and capture output ansible.builtin.command: cat "{{ role_path }}/defaults/main.yml" register: default_yml_content # The plain text content will be in default_yml_content.stdout - name: Print the content ansible.builtin.debug: var: default_yml_content.stdout
But again, stick with slurp whenever possible—it’s the more secure, maintainable approach for Ansible playbooks.
内容的提问来源于stack exchange,提问作者pyramid13
相关产品推荐
相关产品推荐

