Skip to main content
 首页 » 编程设计

python之使用 Ansible 从命令行渲染模板

2024年10月24日11unruledboy

我有一个 Jenkins shell 脚本,它有类似这样的东西来从模板创建 Nginx 配置。

nginx.conf.j2 :

server { 
  listen 80; 
  server_name {{ server_name }}; 
  ... 

将所有环境变量传递给模板的渲染过程:

env server_name=$SERVER_NAME \ 
  python - <<'EOF' > "nginx.conf" 
import os, jinja2 
template = jinja2.Template(open(os.environ["nginx.conf.j2"]).read()) 
print template.render(**os.environ) 
EOF 

如何使用 Ansible 做同样的事情?我猜它可能是这样的:

ansible <host-pattern> -m template -a "src=nginx.conf.j2 dest=nginx.conf" 

但是如何跳过<host-pattern>在本地做?如何将环境变量传递给模板?

请您参考如下方法:

如果您需要强制 Ansible 在本地运行,您可以创建一个 inventory像这样包含本地主机的文件:

[local] 
localhost ansible_host=127.0.0.1 ansible_connection=local 

假设您将其保存到一个名为 local 的文件中,您将像这样使用它:

ansible all -i local -m template -a "src=nginx.conf.j2 dest=nginx.conf" 

或者,您也可以使用稍微笨拙的方式直接在 CLI 上以列表形式提供 list :

ansible all -i "localhost," -m template -a "src=nginx.conf.j2 dest=nginx.conf" --connection=local 

特别注意尾随的 ,,因为这使得 Ansible 将其视为列表而不是字符串,并且它期望库存是列表。

但是,听起来您正在尝试使用 Ansible 来替代问题中包含的 Python 片段。如果您尝试上述操作(如评论中所述),您还会看到 Ansible 仅支持剧本中的模板,而不支持临时命令中的模板。

相反,我建议您退后一步,按预期更多地使用 Ansible,并使用 Jenkins 触发具有指定 list (包括您的 Nginx 盒)的 Ansible 剧本,然后配置 Nginx。

一个非常基本的示例剧本可能看起来像这样:

- hosts: nginx-servers 
  tasks: 
    - name: Template nginx.conf 
      template: 
        src: nginx.conf.j2 
        dest: /etc/nginx/nginx.conf 

主机中的 nginx-servers 对应于如下定义的库存组 block :

[nginx-servers] 
nginx1.example.com 
nginx2.example.com 

有了这个,您可能会想开始查看 roles这将大大提高重用您编写的大量 Ansible 代码的能力。