Ansible - [08] 模块应用

 

firewalld 模块

使用firewalld模块可以配置防火墙策略

[root@control ~]# cat ~/ansible/firewall.yml
---
- hosts: agent
  tasks:
    - name: install firewalld.
      yum:
        name: firewalld
        state: present
    - name: run firewalld.
      service:
        name: firewalld
        state: started
        enabled: yes
    - name: set firewalld rule
      firewalld:
        port: 80/tcp
        permanent: yes
        state: enabled

以上可进行:安装防火墙、启动防火墙、允许80端口的访问

其他案例

- firewalld:
    port: 8081/tcp
    permanent: yes
    state: disabled
    
- firewalld:
    port: 161-162/udp
    permanent: yes
    state: enabled
    
- firewalld:
    zone: dmz
    service: http
    permanent: yes
    state: enabled
    
- name: Redirect port 443 to 8443 with Rich Rule
  firewalld:
    rich_rule: rule forward-port port=443 protocol=tcp to-port=8443
    zone: public
    permanent: yes
    immediate: yes
    state: enabled
    

immediate 可以让规则立刻生效

查看防火墙永久规则:firewalld-cmd --list-ports --permanent

 

 

template 模块

  • copy模块可以将一个文件拷贝给远程主机
  • 但是如果希望每个拷贝的文件内容都不一样呢?
  • 如何给所有web主机拷贝index.html内容是各自的IP地址?
  • Ansible可以利用Jinja2模板引擎读取变量
    • 之前在playbook中调用变量,也是Jinja2(谐音:金加兔)的功能
    • Jinja2模块的表达式包含在分隔符"{{  }}"内
[root@control ansible]# mkdir ~/ansible/template
[root@control ansible]# cat ~/ansible/template/index.html
Welcome to {{ ansible_hostname }} on {{ ansible_eth0.ipv4.address }}.
# 模板文件中调用变量不需要双引号
[root@control ansible]# cat ~/ansible/template.yml
---
- hosts: webserver
  tasks:
    - name: use template copy index.html to webserver.
      template:
        src: ~/ansible/template/index.html
        dest: /var/www/html/index.html

# 在被控制节点查看文件
[root@node3 ansible]# cat /var/www/html/index.html
Welcome to node3 on 192.168.4.3.

定义变量

[root@control ansible]# cat ~/ansible/template/soure.j2
{{ welcome }} {{ iname }}...
[root@control ansible]#
[root@control ansible]# cat ~/ansible/template2.yml
---
- hosts: webserver
  vars:
    welcome: 'hello'
    iname: 'jack'
  tasks:
    - name: use template copy a file to remote hosts
      template:
        src: ~/ansible/template/source.j2
        dest: /tmp/
[root@control ansible]# 

 

posted @ 2024-01-15 15:30  HOUHUILIN  阅读(32)  评论(0编辑  收藏  举报