ansible-playbook role 编写示例
下面是一个安装httpd软件的过程。
tasks / templates / vars 是必须的目录:
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:
[ roles]# cat httpd/tasks/main.yml - include: group.yml - include: user.yml - include: httpd.yml - include: conf.yml - include: service.yml - include: selinux.yml
各个剧本:
[ roles]# cat httpd/tasks/group.yml - name: 创建用户组 vars_file: - /etc/ansible/roles/httpd/vars/main.yml group: name={{ groupname }} [ roles]# cat httpd/tasks/user.yml - name: 创建用户 vars_file: - /etc/ansible/roles/httpd/vars/main.yml user: name={{ username }} system=yes group={{ groupname }} [ roles]# cat httpd/tasks/httpd.yml - name: yum 安装httpd yum: name=httpd [ 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 [ roles]# cat httpd/tasks/service.yml - name: 启动服务 service: name=httpd state=started [ roles]# cat httpd/tasks/selinux.yml - name: 关闭selinux shell: "sed -i ‘s/SELINUX=enforcing/SELINUX=disabled/g‘ /etc/sysconfig/selinux"
[ roles]# cat httpd/templates/httpd.conf.j2 ... {% if ansible_distribution_major_version == "7" %} Listen 77 {% else %} Listen 8080 {% endif %} ...
[ roles]# cat httpd/vars/main.yml username: app groupname: app
在roles同级别目录中定义如下调用角色的剧本,httpd是目录名字:
[ ansible]# pwd /etc/ansible [ 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