Ansible的脚本-----playbook剧本【下】

目录

[实战演练六:tags 模块](#实战演练六:tags 模块)

[实战演练七:Templates 模块](#实战演练七:Templates 模块)


实战演练六:tags 模块

可以在一个playbook中为某个或某些任务定义"标签",在执行此playbook时通过ansible-playbook命令使用--tags选项能实现仅运行指定的tasks。
playbook还提供了一个特殊的tags为always。作用就是当使用always作为tags的task时,无论执行哪一个tags时,定义有always的tags都会执行。

复制代码
vim play5.yaml
- name: five play
  remote_user: root
  hosts: dbservers
  gather_facts: true
  tasks:
  - name: copy file
    copy: src=/etc/hosts dest=/opt/
    tags:
    - test

  - name: touch file
    file: path=/opt/myhosts state=touch
    tags:
    - only


ansible-playbook play5.yaml --tags="test"   #指定标签,只运行该标签下的任务



被控制节点查看opt目录下是否有hosts文件

复制代码
vim play5.yaml
- name: five play
  remote_user: root
  hosts: dbservers
  gather_facts: true
  tasks:
  - name: copy file
    copy: src=/etc/hosts dest=/opt/
    tags:
    - test

  - name: touch file
    file: path=/opt/myhosts state=touch
    tags:
    - only
    - always

ansible-playbook play5.yaml --tags="test"     #当使用always作为tags的task时,无论执行哪一个tags时,定义有always的tags都会执行。

被控制节点查看

实战演练七:Templates 模块

Jinja是基于Python的模板引擎。Template类是Jinja的一个重要组件,可以看作是一个编译过的模板文件,用来产生目标文本,传递Python的变量给模板去替换模板中的标记。

复制代码
cp /opt/httpd.conf ./httpd.conf.j2   先准备一个以 .j2 为后缀的 template 模板文件,设置引用的变量

vim httpd.conf.j2 
Listen {{server_ip}}:{{http_port}}   #42行
ServerName {{host_name}}:{{http_port}}   #95行
      
vim /etc/ansible/hosts
[webservers]
192.168.9.113 server_ip=192.168.9.113 http_port=8080 host_name=www.xy102.com
192.168.9.111 server_ip=192.168.9.111 http_port=8081 host_name=www.xy103.com
复制代码
vim play1.yaml
- name: first play
  gather_facts: false
  hosts: webservers
  remote_user: root
  tasks:
  - name: disable firewalld
    service: name=firewalld state=stopped enabled=no
  - name: disable selinux
    command: 'setenforce 0'
    ignore_errors: true
  - name: mount cdrom
    mount: src=/dev/sr0 path=/mnt fstype=iso9660 state=mounted
  - name: install httpd
    yum: name=httpd state=latest
  - name: copy config template file
    template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
    notify: "reload httpd"
  - name: start httpd
    service: name=httpd state=started enabled=yes
  handlers:
  - name: reload httpd
    service: name=httpd state=reloaded

ansible-playbook play1.yaml


两个被控制节点查看42、95行是否修改成功

相关推荐
爱网络爱Linux2 天前
RHCSA+RHCE 10.0全新升级!红帽Ansible自动化运维
运维·自动化·ansible·rhce认证·rhel1o·linux10·rhce10
码上上班7 天前
Ansible课程
ansible
至乐活着10 天前
Ansible自动化运维实战:从零部署高可用Nginx+静态网站集群
ansible·自动化运维·devops·playbook·配置管理
John Song12 天前
ansible-playbook常用的检查命令
windows·ansible
明航咨询_贾老师15 天前
RHCA Ansible高级自动化(DO374)认证信息整理
运维·自动化·ansible·rhca·红帽认证
有毒的教程19 天前
Ansible批量操作自动化完整教程:批量部署服务、配置同步、软件更新实战
运维·自动化·ansible
Hy行者勇哥24 天前
用Cursor智能编写Ansible/Terraform脚本,打通CI/CD链路
ci/cd·ansible·terraform
芷栀夏1 个月前
飞牛NAS怎么部署Immich?家庭照片自动备份与远程访问教程
服务器·nginx·ansible
悠然南风1 个月前
Ansible常见模块总结及LDAP Role 编写与调试
ansible
祺风挽楠2 个月前
ansible编辑
网络·ansible