【Ansible】Ansible的脚本-----playbook剧本(补充)

目录

playbook剧本实战演练实战演练

1.tags 模块

2.Templates 模块


playbook剧本实战演练实战演练

1.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都会执行。

2.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.80.101 server_ip=192.168.80.101 http_port=8080 host_name=www.xy102.com
192.168.80.102 server_ip=192.168.80.102 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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值