ansible-playbook role 编写示例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ansible-playbook role 编写示例相关的知识,希望对你有一定的参考价值。
下面是一个安装httpd软件的过程。
tasks / templates / vars 是必须的目录:
├── httpd
│ ├── tasks
│ │ ├── conf.yml
│ │ ├── group.yml
│ │ ├── httpd.yml
│ │ ├── main.yml
│ │ ├── selinux.yml
│ │ ├── service.yml
│ │ └── user.yml
│ ├── templates
│ │ └── httpd.conf.j2
│ └── vars
│ └── main.yml
在main.yml中包含各个单独的task:
[root@localhost roles]# cat httpd/tasks/main.yml
- include: group.yml
- include: user.yml
- include: httpd.yml
- include: conf.yml
- include: service.yml
- include: selinux.yml
各个剧本:
[root@localhost roles]# cat httpd/tasks/group.yml
- name: 创建用户组
vars_file:
- /etc/ansible/roles/httpd/vars/main.yml
group: name={{ groupname }}
[root@localhost roles]# cat httpd/tasks/user.yml
- name: 创建用户
vars_file:
- /etc/ansible/roles/httpd/vars/main.yml
user: name={{ username }} system=yes group={{ groupname }}
[root@localhost roles]# cat httpd/tasks/httpd.yml
- name: yum 安装httpd
yum: name=httpd
[root@localhost roles]# cat httpd/tasks/conf.yml
- name: 拷贝配置文件
# 配置文件通过渲染完成后拷贝到被控主机
template: src=/etc/ansible/roles/httpd/templates/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf backup=yes
[root@localhost roles]# cat httpd/tasks/service.yml
- name: 启动服务
service: name=httpd state=started
[root@localhost roles]# cat httpd/tasks/selinux.yml
- name: 关闭selinux
shell: "sed -i ‘s/SELINUX=enforcing/SELINUX=disabled/g‘ /etc/sysconfig/selinux"
[root@localhost roles]# cat httpd/templates/httpd.conf.j2
...
{% if ansible_distribution_major_version == "7" %}
Listen 77
{% else %}
Listen 8080
{% endif %}
...
[root@localhost roles]# cat httpd/vars/main.yml
username: app
groupname: app
在roles同级别目录中定义如下调用角色的剧本,httpd是目录名字:
[root@localhost ansible]# pwd
/etc/ansible
[root@localhost ansible]# cat install_apache.yml
- hosts: webs
remote_user: root
# 使用角色,角色名是roles下的目录名字
roles:
- role: httpd
测试剧本,执行角色剧本:
ansible-playbook -C install_apache.yml
ansible-playbook install_apache.yml
以上是关于ansible-playbook role 编写示例的主要内容,如果未能解决你的问题,请参考以下文章
ansible-playbook roles 安装zabbix-agent 监控 php
[ansible]牛刀小试,使用ansible-playbook role方式部署jdk环境