Ansible 之 Templates模板替换

一、Templates作用

常被用作传输文件,同时支持预定义变量替换,并且可由Jinja2渲染格式

二、Templates场景

将nginx.j2分发至远程主机的/app/nginx.conf,且替换配置文件中变量为对应的值。

三、编排目录

[root@Ansible ansible]# tree roles/template/
roles/template/
├── tasks
│   ├── main.yml
│   └── template.yml
├── templates
│   └── nginx.j2
└── vars
    └── main.yml

四、任务总调度文件

---
- hosts: test
  remote_user: cedar
  become: yes
  roles:
    - role: template

五、角色下所有文件的代码

main.yml

[root@Ansible template]# cat tasks/main.yml 
---
- include: template.yml

template.yml

[root@Ansible template]# cat tasks/template.yml 
---
- name: "模板更换"
  template: src=nginx.j2 dest=/app/nginx.conf

nginx.j2

[root@Ansible template]# cat templates/nginx.j2 
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;

    server {
        listen       {{LISTEN_PORT}} default_server;
        server_name  {{SERVER_NAME}};
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
}

main.yml

[root@Ansible template]# cat vars/main.yml 
---
LISTEN_PORT: "80"
SERVER_NAME: "www.kang.com"

六、运行结果

[root@Ansible ansible]# ansible-playbook roles_file/template.yml 

PLAY [test] *****************************************************************************************************************************************************

TASK [Gathering Facts] ******************************************************************************************************************************************
ok: [10.3.153.8]

TASK [template : 模板更换] ******************************************************************************************************************************************
changed: [10.3.153.8]

PLAY RECAP ******************************************************************************************************************************************************
10.3.153.8                 : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Ansible 之 Templates模板替换

猜你喜欢

转载自blog.51cto.com/12965094/2606244