Ansible中的角色使用:
目录
files | 存放copy或script等模块调用的函数 |
tasks | 定义各种task,要有main.yml ,其他文件include包含调用 |
handlers | 定义各种handlers,要有main.yml ,其他文件include包含调用 |
vars | 定义variables,要有main.yml ,其他文件include包含调用 |
templates | 存储由template模块调用的模板文本 |
meta | 定义当前角色的特殊设定及其依赖关系,要有main.yml 的文件 |
defaults | 要有main.yml 的文件,用于设定默认变量 |
tests | 用于测试角色 |
ansible—galaxy命令工具:
Ansible Galaxy 是一个免费共享和下载 Ansible 角色的网站,可以帮助我们更好的定义和学习roles;
ansible-galaxy命令默认与https://galaxy.ansible.com网站API通信,可以查找、下载各种社区开发的Ansible 角色。
vim ansible.cfg
- mkdir roles
-
- cd roles/
- ansible-galaxy init apache
- cd ..
- ansible-galaxy list
例子:下载httpd,配置虚拟主机并认证加密
- vim tasks/main.yml
-
- - name: yum
- yum:
- name: httpd
- state: present
-
- - name: service
- service:
- name: httpd
- state: started
- enabled: yes
-
- - name: create doc
- lineinfile:
- path: "{{item.doc}}/index.html"
- line: "{{item.index}}"
- create: yes
- loop: "{{webs}}"
-
- - name: create vhosts.conf
- template:
- src: vhosts.conf.j2
- dest: /etc/httpd/conf.d/vhost.conf
- notify: restart httpd
-
- - name: auth
- copy:
- src: .htpasswd
- dest: /etc/httpd/.htpasswd
- notify: restart httpd
- vim handlers/main.yml
- cat handlers/main.yml
-
- - name: restart httpd
- service:
- name: httpd
- state: restarted
- vim vars/main.yml
- cat vars/main.yml
-
- webs:
- - doc: /var/www/html
- index: "www.westos.org's page"
-
- - name: bbs.westos.org
- doc: /var/www/virtual/westos.org/bbs/html
- index: "bbs.westos.org's page"
-
- - name: login.westos.org
- doc: /var/www/virtual/westos.org/login/html
- index: "login.westos.org's page"
- vim templates/vhosts.conf.j2
- cat templates/vhosts.conf.j2
-
- {% for web in webs %}
- {% if web.name is defined %}
- <VirtualHost *:80>
- ServerName {{web.name}}
- {% endif %}
- {% if web.name is not defined %}
- <VirtualHost _default_:80>
- {% endif %}
- DocumentRoot {{web.doc}}
- </VirtualHost>
- {% endfor %}
- <Directory "/var/www/virtual/westos.org/login/html">
- AuthUserfile "/etc/httpd/.htpasswd"
- AuthName "Please input your name and password"
- AuthType basic
- Require user yyl
- </Directory>
- touch .htpasswd
- htpasswd -cm .htpasswd yyl
- cp /etc/httpd/.htpasswd files/
- vim httpd.yml
-
- - name: instell http
- hosts: all
- roles:
- - role: apache
ansible-playbook httpd.yml
pre_task
:任务执行前post_tasks
:任务执行后
例子:
- - name: instell http
- hosts: all
- pre_tasks:
- - name: test
- debug:
- msg: this is start !!
-
- roles:
- - role: apache
-
- post_tasks:
- - name: show post
- debug:
- msg: this is end !!
1、访问地址角色下载地址:galaxy.ansible.com roles
2、搜索nginx,往后翻一下找到roles
3、下载角色
ansible-galaxy collection install ivansible.nginx
要注意出于安全原因,下载的代码需要仔细研读每一行代码!!!