Ansible:将变量设置为文件内容 [英] Ansible: Set variable to file content

查看:29
本文介绍了Ansible:将变量设置为文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有 ansible-playbook 的 ec2 模块我想为文件的内容设置一个变量.这是我目前的做法.

I'm using the ec2 module with ansible-playbook I want to set a variable to the contents of a file. Here's how I'm currently doing it.

  1. 带有文件名的变量
  2. shell 任务 cat 文件
  3. 使用 cat 的结果传递给 ec2 模块.
  1. Var with the filename
  2. shell task to cat the file
  3. use the result of the cat to pass to the ec2 module.

我的剧本的示例内容.

vars:
  amazon_linux_ami: "ami-fb8e9292"
  user_data_file: "base-ami-userdata.sh"
tasks:
- name: user_data_contents
  shell: cat {{ user_data_file }}
  register: user_data_action
- name: launch ec2-instance
  local_action:
...
  user_data: "{{ user_data_action.stdout }}"

我认为有一种更简单的方法可以做到这一点,但我在搜索 Ansible 文档时找不到它.

I assume there's a much easier way to do this, but I couldn't find it while searching Ansible docs.

推荐答案

您可以使用 lookups在 Ansible 中以获取文件的内容,例如

You can use lookups in Ansible in order to get the contents of a file, e.g.

user_data: "{{ lookup('file', user_data_file) }}"

警告:此查找适用于本地文件,而不适用于远程文件.

Caveat: This lookup will work with local files, not remote files.

这是一个文档中的完整示例:

- hosts: all
  vars:
     contents: "{{ lookup('file', '/etc/foo.txt') }}"
  tasks:
     - debug: msg="the value of foo.txt is {{ contents }}"

这篇关于Ansible:将变量设置为文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆