1. 各目录含义解释
roles: <--所有的角色必须放在roles目录下,这个目录可以自定义位置,默认的位置在/etc/ansible/roles
project: <---具体的角色项目名称,比如nginx、tomcat、php
files: <--用来存放由copy模块或script模块调用的文件。
templates: <--用来存放jinjia2模板,template模块会自动在此目录中寻找jinjia2模板文件。
tasks: <--此目录应当包含一个main.yml文件,用于定义此角色的任务列表,此文件可以使用include包含其它的位于此目录的task文件。
main.yml
handlers: <--此目录应当包含一个main.yml文件,用于定义此角色中触发条件时执行的动作。
main.yml
vars: <--此目录应当包含一个main.yml文件,用于定义此角色用到的变量。
main.yml
2. Ansible Roles示例
通过ansible roles安装配置nfs服务,此处的roles不使用默认的路径/etc/ansible/roles
1. 搭建结构
mkdir /mnt/myansible_roles
cd /mnt/myansible_roles
创建ansible.cfg
cat > ansible.cfg << EOF
[defaults]
inventory = hosts
sudo_user = root
transport = smart
remote_port = 22
remote_user = root
log_path = /mnt/myansible_roles/logs/ansible.log
deprecation_warnings = False
command_warnings = False
host_key_checking = False
interpreter_python = auto_legacy_silent
# gather_facts = no
EOF
创建hosts
cat > hosts << EOF
[nfsServer]
192.168.137.248
EOF
mkdir logs
mkdir -p roles/nfs-server/{tasks,vars,files,templates,handlers}
tree
.
├── ansible.cfg
├── hosts
├── logs
├── roles
│ └── nfs-server
│ ├── files
│ ├── handlers
│ ├── tasks
│ ├── templates
│ └── vars
└── site.yaml
2. 编写nfs-server
cd /mnt/myansible_roles/roles/nfs-server
# 创建tasks/main.yaml
cat > tasks/main.yaml << EOF
- name: install nfs-utils rpcbind
yum:
name:
- nfs-utils
- rpcbind
state: installed
- name: create data directory
file:
path: "{{ data_dir }}"
state: directory
owner: nfsnobody
group: nfsnobody
# ignore_errors: True
#- name: create config file
# copy: src="exports" dest="/etc/"
# notify:
# - restart nfs
#- name: create config file
# copy:
# src: exports
# dest: /etc/
# notify:
# - restart nfs
#- name: create config file
# template: src="exports.j2" dest="/etc/exports"
# notify:
# - restart nfs
- name: create config file
template:
src: exports.j2
dest: /etc/exports
notify:
- restart nfs
- name: start process
service:
name: "{{ item }}"
enabled: yes
state: started
with_items:
- rpcbind
- nfs
- name: check server
#shell: /usr/sbin/showmount -e localhost
shell: /usr/sbin/showmount -e "{{ansible_eth0.ipv4.address}}"
register: result
- name: display result
debug: msg={{ result.stdout_lines }}
EOF
# 创建vars/main.yaml
cat > vars/main.yaml << EOF
data_dir: /sharding_data
EOF
# 创建handlers/main.yaml
cat > handlers/main.yaml << EOF
- name: restart nfs
service:
name: nfs
state: restarted
enabled: yes
EOF
# 创建files/exports
cat > files/exports << EOF
/sharding_data/ 192.168.137.0/24(rw,sync)
EOF
# 创建templates/exports.j2
cat > templates/exports.j2 << EOF
{{ data_dir }} 192.168.137.0/24(rw,sync)
EOF
.
├── files
│ └── exports
├── handlers
│ └── main.yaml
├── tasks
│ └── main.yaml
├── templates
│ └── exports.j2
└── vars
└── main.yaml
3. 测试,执行
cd /mnt/myansible_roles/
cat > site.yaml << EOF
---
- hosts: all
roles:
- nfs-server
EOF
# 语法检查
ansible-playbook --syntax-check site.yaml
# 预执行
ansible-playbook -C site.yaml
# 如果都没问题就可以执行
ansible-playbook site.yaml
网友评论