典型命令
ansible 10.10.20.197 -m fetch -a "ser=/etc/fstab dest=/tmp/fstab"
# 10.10.20.197 //管理主机
# -m fetch //引用模块
# -a "ser=/etc/fstab dest=/tmp/fstab" //模块参数
基础概念
清单文件
用来配置管理的主机IP信息,所有需要管理的主机都需要配置在清单文件里面
# 默认清单文件: /etc/ansible/hosts
## 192.168.1.100
## 192.168.1.110
# If you have multiple hosts following a pattern you can specify
# them like this:
## www[001:006].example.com
# Ex 3: A collection of database servers in the 'dbservers' group
## [dbservers]
##
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57
# Here's another example of host ranges, this time there are no
# leading 0s:
## db-[99:101]-node.example.com
[test-host]
10.10.20.197 ansible_user=root ansible_ssh_pass=letsg0 ansible_port=22
10.10.20.198
模块
ansible封装的基本功能单元
# 查看所有模块
ansible-doc -l
# 查看某个模块详情
ansible-doc -s fetch
- 常用模块
command # 远程执行命令
shell # 远程执行命令,经过操作系统/bin/bash
script # 远程执行本地脚本
copy # 拷贝文件
file # 文件操作,创建、删除、修改
find # 查找文件
replace # 替换文件中的字符串
blockinfile # 操作文件中的一段文本
lineinfile # 操作某行中的一段文本
user # 管理用户
group # 管理组
yum_repository # 管理yum仓库
yun # 通过yum管理软件包
cron # 管理远程的定时任务
service # 管理远程主机服务
Playbooks
Playbooks是Ansible的配置,部署,编排语言
ansible-playbook test.yml # 执行playbook
ansible-playbook --syntax-check test.yml # 检查playbook中yaml语法
playbook示例
# playbook是由若干个play组成,每个play可以定义特殊的hosts,一个play包含若干个task
---
- hosts: webservers
vars:
http_port: 80
max_clients: 200
remote_user: root
tasks:
- name: ensure apache is at the latest version
yum: pkg=httpd state=latest
- name: write the apache config file
template: src=/srv/httpd.j2 dest=/etc/httpd.conf
notify:
- restart apache
- name: ensure apache is running
service: name=httpd state=started
handlers:
- name: restart apache
service: name=httpd state=restarted
tasks
任务
handlers
可调用任务,在task执行后可通过notify调用它
tags
通过打tag可以,在执行playbook的时候,可以选择执行或者不执行某些命令
ansible-playbook --tags=release /root/test.yml # 执行tags为release的task ansible-playbook --skip-tags=release /root/test.yml # 不执行tags为release的task
role和include
通过include来引用其他play或者task,来实现功能模块重用,并强烈推荐使用role这种目录组织方式来管理Ansible工程
最好通过查看经典示例来学习规范的目录组织结构
详情,待补充
变量
变量名由字母、数字以及下划线组成,始终以字母开头
- 在playbook中使用变量
# 使用vars关键字定义变量,{{ }}来引用变量
---
- hosts: test-host
vars:
testvar1: testfile
testvar2:
filepath: /testdir/demo.conf
remote_user: root
tasks:
- name: task1
file:
path: /testdir/{{testvar1}}
state: touch
- name: task2
file:
path: "{{testvar2.filepath}}"
state: touch
# 在文件中定义变量,vars_files来引用变量定义文件
# 变量定义文件 /root/ansible/vars1.yml
testvar1: testfile
testvar2:
filepath: /testdir/demo.conf
# 引用变量
---
- hosts: test-host
remote_user: root
vars_files:
- /root/ansible/vars1.yml
tasks:
- name: task1
file:
path: /testdir/{{testvar1}}
state: touch
- name: task2
file:
path: "{{testvar2.filepath}}"
state: touch
其他变量内容,待补充