ansible template

不会跳舞的胖子發表於2024-08-23

Jinja2 文件:https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_templating.html

Ansible 的 template 模組用於將 Jinja2 模板檔案(.j2 檔案)渲染並生成目標檔案。它的主要功能是根據變數動態生成配置檔案或其他內容,並將其分發到目標主機。template 模組在管理配置檔案或生成動態內容時非常有用。

基本語法

- name: Render a template to a file
  ansible.builtin.template:
    src: template_file.j2
    dest: /path/to/destination/file
    owner: root
    group: root
    mode: '0644'

主要引數

  • src: 指定模板檔案的路徑。通常是相對於 rolesplaybook 目錄中的路徑。
  • dest: 指定渲染後的檔案儲存路徑。檔案會被複製到目標主機上的這個路徑。
  • owner: 設定生成檔案的所有者。
  • group: 設定生成檔案的所屬組。
  • mode: 設定檔案的許可權模式(例如 0644)。

典型用法

1. 簡單的模板渲染

- name: Render an nginx configuration file
  ansible.builtin.template:
    src: templates/nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    owner: root
    group: root
    mode: '0644'

這個任務會將 nginx.conf.j2 模板渲染並生成到目標主機的 /etc/nginx/nginx.conf,檔案的所有者和組為 root,許可權為 0644

2. 使用變數的模板渲染

假設在模板 nginx.conf.j2 中使用了一些變數,例如:

server {
    listen {{ nginx_port }};
    server_name {{ nginx_server_name }};

    location / {
        proxy_pass http://{{ proxy_backend }};
    }
}

在 playbook 中,可以定義這些變數,然後使用 template 模組來渲染模板:

- hosts: webservers
  vars:
    nginx_port: 80
    nginx_server_name: example.com
    proxy_backend: backend.example.com

  tasks:
    - name: Render nginx configuration with variables
      ansible.builtin.template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/nginx.conf

在目標主機上,nginx.conf 檔案將會被渲染為:

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend.example.com;
    }
}

3. 使用 validate 引數

validate 引數用於在模板被渲染並寫入目標檔案前進行驗證。常用於確保配置檔案在部署前是有效的。例如,在渲染 nginx 配置檔案時,可以使用 nginx -t 來驗證:

- name: Render and validate nginx configuration
  ansible.builtin.template:
    src: templates/nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    validate: '/usr/sbin/nginx -t -c %s'
  • %s: 會被替換為生成的檔案路徑。

如果驗證失敗,Ansible 會停止執行並報告錯誤,避免部署錯誤的配置檔案。

templatecopy 的區別

  • template 模組: 用於渲染 Jinja2 模板檔案,允許在檔案中使用變數、邏輯和控制結構。
  • copy 模組: 用於直接複製檔案,不進行任何模板渲染。

使用 template 模組的好處

  • 動態生成檔案: 根據上下文和變數動態生成配置檔案或其他內容。
  • 邏輯控制: 可以在模板中使用 Jinja2 語法,進行條件判斷、迴圈等複雜操作。
  • 配置管理: 更靈活地管理和部署不同環境下的配置檔案。

相關文章