目录
一、Ansible概念
1.1特点
二、工作机制(日常模块)
2.1 核心程序
三、Ansible 环境安装部署
//管理端安装 ansible
yum install -y epel-release //先安装 epel 源
yum install -y ansible
//ansible 目录结构
/etc/ansible/
├── ansible.cfg #ansible的配置文件,一般无需修改
├── hosts #ansible的主机清单,用于存储需要管理的远程主机的相关信息
└── roles/ #公共角色目录
//配置主机清单
cd /etc/ansible
vim hosts
[webservers] #配置组名
192.168.10.17 #组里包含的被管理的主机IP地址或主机名(主机名需要先修改/etc/hosts文件)
[dbservers]
192.168.10.18
//配置密钥对验证
ssh-keygen -t rsa #一路回车,使用免密登录
sshpass -p 'abc1234' ssh-copy-id root@192.168.10.17
sshpass -p 'abc1234' ssh-copy-id root@192.168.10.18
四、ansible 命令行模块
ansible-doc -l #列出所有已安装的模块,按q退出
4.1command 模块
ansible-doc -s command #-s 列出指定模块的描述信息和操作动作
ansible 192.168.10.14 -m command -a 'date' #指定 ip 执行 date
ansible webservers -m command -a 'date' #指定组执行 date
ansible webservers -m command -a 'date' #指定组执行 date
ansible dbservers -m command -a 'date'
ansible all -m command -a 'date' #all 代表所有 hosts 主机
ansible all -a 'ls /' #如省略 -m 模块,则默认运行 command 模块
//常用的参数:
chdir:在远程主机上运行命令前提前进入目录
creates:判断指定文件是否存在,如果存在,不执行后面的操作
removes:判断指定文件是否存在,如果存在,执行后面的操作
ansible all -m command -a "chdir=/home ls ./"
4.2shell 模块
ansible-doc -s shell
ansible dbservers -m shell -a 'echo 123456 | passwd --stdin test'
ansible dbservers -m shell -a 'echo $(ifconfig ens33 | awk "NR==2 {print $2}") | cut -d " " -f2'
ansible dbservers -m shell -a 'echo $(ifconfig ens33 | awk "NR==2 {print \$2}")'
4.3cron 模块
ansible-doc -s cron #按 q 退出
//常用的参数:
minute/hour/day/month/weekday:分/时/日/月/周
job:任务计划要执行的命令
name:任务计划的名称
ansible webservers -m cron -a 'minute="*/1" job="/bin/echo helloworld" name="test crontab"'
ansible webservers -a 'crontab -l'
ansible webservers -m cron -a 'name="test crontab" state=absent' #移除计划任务,假如该计划任务没有取名字,name=None即可
4.4user 模块
ansible-doc -s user
//常用的参数:
name:用户名,必选参数
state=present|absent:创建账号或者删除账号,present表示创建,absent表示删除
system=yes|no:是否为系统账号
uid:用户uid
group:用户基本组
shell:默认使用的shell
move_home=yse|no:如果设置的家目录已经存在,是否将已经存在的家目录进行移动
password:用户的密码,建议使用加密后的字符串
comment:用户的注释信息
remove=yes|no:当state=absent时,是否删除用户的家目录
ansible dbservers -m user -a 'name="test01"' #创建用户test01
ansible dbservers -m command -a 'tail /etc/passwd'
ansible dbservers -m user -a 'name="test01" state=absent' #删除用户test01
4.5group 模块
ansible-doc -s group
ansible dbservers -m group -a 'name=mysql gid=306 system=yes' #创建mysql组
ansible dbservers -a 'tail /etc/group'
ansible dbservers -m user -a 'name=test01 uid=306 system=yes group=mysql' #将test01用户添加到mysql组中
ansible dbservers -a 'tail /etc/passwd'
ansible dbservers -a 'id test01'
4.6copy模块
用于复制指定主机文件到远程主机的
ansible-doc -s copy
常用的参数:
ansible dbservers -m copy -a 'src=/etc/fstab dest=/opt/fstab.bak owner=root mode=640'
ansible dbservers -a 'ls -l /opt'
ansible dbservers -a 'cat /opt/fstab.bak'
ansible dbservers -m copy -a 'content="helloworld" dest=/opt/hello.txt' #将helloworld写入/opt/hello.txt文件中
ansible dbservers -a 'cat /opt/hello.txt'
4.7file模块
ansible-doc -s file
ansible dbservers -m file -a 'owner=test01 group=mysql mode=644 path=/opt/fstab.bak' #修改文件的属主属组权限等
ansible dbservers -m file -a 'path=/opt/fstab.link src=/opt/fstab.bak state=link' #设置/opt/fstab.link为/opt/fstab.bak的链接文件
ansible dbservers -m file -a "path=/opt/abc.txt state=touch" #创建一个文件
ansible dbservers -m file -a "path=/opt/abc.txt state=absent" #删除一个文件
4.8hostname模块
ansible dbservers -m hostname -a "name=mysql01"
4.9ping 模块
ansible all -m ping
4.11yum 模块
ansible-doc -s yum
ansible webservers -m yum -a 'name=httpd' #安装服务
ansible webservers -m yum -a 'name=httpd state=absent' #卸载服务
4.12service/systemd 模块
ansible-doc -s service
常用的参数:
ansible webservers -a 'systemctl status httpd' #查看web服务器httpd运行状态
ansible webservers -m service -a 'enabled=true name=httpd state=started' #启动httpd服务
4.13script 模块
ansible-doc -s script
vim test.sh
#!/bin/bash
echo "hello ansible from script" > /opt/script.txt
chmod +x test.sh
ansible webservers -m script -a 'test.sh'
ansible webservers -a 'cat /opt/script.txt'
五、inventory 主机清单
vim /etc/ansible/hosts
[webservers]
192.168.10.14:2222 #冒号后定义远程连接端口,默认是 ssh 的 22 端口
192.168.10.1[2:5]
[dbservers]
db-[a:f].example.org #支持匹配 a~f
(1)主机变量
[webservers]
192.168.10.14 ansible_port=22 ansible_user=root ansible_password=abc1234
(2)组变量
[webservers:vars] #表示为 webservers 组内所有主机定义变量
ansible_user=root
ansible_password=abc1234
[all:vars] #表示为所有组内的所有主机定义变量
ansible_port=22
(3)组嵌套
[nginx]
192.168.10.20
192.168.10.21
192.168.10.22
[apache]
192.168.10.3[0:3]
[webs:children] #表示为 webs 主机组中包含了 nginx 组和 apache 组内的所有主机
nginx
apache
市场运行常用的自动化工具
puppet
saltstack
chef
fabric
六、Ansible 的脚本 --- playbook 剧本
playbooks 本身由以下各部分组成
6.1示例
6.1.1test1.yaml
vim test1.yaml
--- #yaml文件以---开头,以表明这是一个yaml文件,可省略
- name: first play #定义一个play的名称,可省略
gather_facts: false #设置不进行facts信息收集,这可以加快执行速度,可省略
hosts: webservers #指定要执行任务的被管理主机组,如多个主机组用冒号分隔
remote_user: root #指定被管理主机上执行任务的用户
tasks: #定义任务列表,任务列表中的各任务按次序逐个在hosts中指定的主机上执行
- name: test connection #自定义任务名称
ping: #使用 module: [options] 格式来定义一个任务
- name: disable selinux
command: '/sbin/setenforce 0' #command模块和shell模块无需使用key=value格式
ignore_errors: True #如执行命令的返回值不为0,就会报错,tasks停止,可使用ignore_errors忽略失败的任务
- name: disable firewalld
service: name=firewalld state=stopped #使用 module: options 格式来定义任务,option使用key=value格式
- name: install httpd
yum: name=httpd state=latest
- name: install configuration file for httpd
copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf #这里需要一个事先准备好的/opt/httpd.conf文件
notify: "restart httpd" #如以上操作后为changed的状态时,会通过notify指定的名称触发对应名称的handlers操作
- name: start httpd service
service: enabled=true name=httpd state=started
handlers: #handlers中定义的就是任务,此处handlers中的任务使用的是service模块
- name: restart httpd #notify和handlers中任务的名称必须一致
service: name=httpd state=restarted
##Ansible在执行完某个任务之后并不会立即去执行对应的handler,而是在当前play中所有普通任务都执行完后再去执行handler,这样的好处是可以多次触发notify,但最后只执行一次对应的handler,从而避免多次重启。
//运行playbook
ansible-playbook test1.yaml
//补充参数:
-k(–ask-pass):用来交互输入ssh密码
-K(-ask-become-pass):用来交互输入sudo密码
-u:指定用户
ansible-playbook test1.yaml --syntax-check #检查yaml文件的语法是否正确
ansible-playbook test1.yaml --list-task #检查tasks任务
ansible-playbook test1.yaml --list-hosts #检查生效的主机
ansible-playbook test1.yaml --start-at-task='install httpd' #指定从某个task开始运行
//定义、引用变量
- name: second play
hosts: dbservers
remote_user: root
vars: #定义变量
- groupname: mysql #格式为 key: value
- username: nginx
tasks:
- name: create group
group: name={{groupname}} system=yes gid=306 #使用 {{key}} 引用变量的值
- name: create user
user: name={{username}} uid=306 group={{groupname}}
- name: copy file
copy: content="{{ansible_default_ipv4}}" dest=/opt/vars.txt #在setup模块中可以获取facts变量信息
ansible-playbook test1.yaml -e "username=nginx" #在命令行里定义变量
//指定远程主机sudo切换用户
---
- hosts: dbservers
remote_user: zhangsan
become: yes #2.6版本以后的参数,之前是sudo,意思为切换用户运行
become_user: root #指定sudo用户为root
执行playbook时:ansible-playbook test1.yml -K <密码>
6.1.2test2.yaml
//when条件判断
在Ansible中,提供的唯一一个通用的条件判断是when指令,当when指令的值为true时,则该任务执行,否则不执行该任务。
//when一个比较常见的应用场景是实现跳过某个主机不执行任务或者只有满足条件的主机执行任务
vim test2.yaml
---
- hosts: all
remote_user: root
tasks:
- name: shutdown host
command: /sbin/shutdown -r now
when: ansible_default_ipv4.address == "192.168.10.14" #when指令中的变量名不需要手动加上 {{}}
或
when: inventory_hostname == "<主机名>"
ansible-playbook test2.yaml
6.1.3test3.yaml
//迭代
Ansible提供了很多种循环结构,一般都命名为with_items,作用等同于 loop 循环。
vim test3.yaml
---
- name: play1
hosts: dbservers
gather_facts: false
tasks:
- name: create directories
file:
path: "{{item}}"
state: directory
with_items: #等同于 loop:
- /tmp/test1
- /tmp/test2
- name: add users
user: name={{item.name}} state=present groups={{item.groups}}
with_items:
- name: test1
groups: wheel
- name: test2
groups: root
或
with_items:
- {name:'test1', groups:'wheel'}
- {name:'test2', groups:'root'}
ansible-playbook test3.yaml
6.2Templates 模块
1.先准备一个以 .j2 为后缀的 template 模板文件,设置引用的变量
cp /etc/httpd/conf/httpd.conf /opt/httpd.conf.j2
vim /opt/httpd.conf.j2
Listen {{http_port}} #42行,修改
ServerName {{server_name}} #95行,修改
DocumentRoot "{{root_dir}}" #119行,修改
2.修改主机清单文件,使用主机变量定义一个变量名相同,而值不同的变量
vim /etc/ansible/hosts
[webservers]
192.168.10.14 http_port=192.168.10.14:80 server_name=www.accp.com:80 root_dir=/etc/httpd/htdocs
[dbservers]
192.168.10.15 http_port=192.168.0.15:80 server_name=www.benet.com:80 root_dir=/etc/httpd/htdocs
3.编写 playbook
vim apache.yaml
---
- hosts: all
remote_user: root
vars:
- package: httpd
- service: httpd
tasks:
- name: install httpd package
yum: name={{package}} state=latest
- name: install configure file
template: src=/opt/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf #使用template模板
notify:
- restart httpd
- name: create root dir
file: path=/etc/httpd/htdocs state=directory
- name: start httpd server
service: name={{service}} enabled=true state=started
handlers:
- name: restart httpd
service: name={{service}} state=restarted
ansible-playbook apache.yaml
6.3tags 模块
vim webhosts.yaml
---
- hosts: webservers
remote_user: root
tasks:
- name: Copy hosts file
copy: src=/etc/hosts dest=/opt/hosts
tags:
- only #可自定义
- name: touch file
file: path=/opt/testhost state=touch
tags:
- always #表示始终要运行的代码
ansible-playbook webhosts.yaml --tags="only"
vim dbhosts.yaml
---
- hosts: dbservers
remote_user: root
tasks:
- name: Copy hosts file
copy: src=/etc/hosts dest=/opt/hosts
tags:
- only
- name: touch file
file: path=/opt/testhost state=touch
ansible-playbook dbhosts.yaml --tags="only"
//分别去两台被管理主机上去查看文件创建情况
6.4Roles 模块
roles 的目录结构:
cd /etc/ansible/
tree roles/
roles/
├── web/
│ ├── files/
│ ├── templates/
│ ├── tasks/
│ ├── handlers/
│ ├── vars/
│ ├── defaults/
│ └── meta/
└── db/
├── files/
├── templates/
├── tasks/
├── handlers/
├── vars/
├── defaults/
└── meta/
roles 内各目录含义解释
在一个 playbook 中使用 roles 的步骤:
示例
mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,defaults,meta} -p
mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta} -p
mkdir /etc/ansible/roles/php/{files,templates,tasks,handlers,vars,defaults,meta} -p
touch /etc/ansible/roles/httpd/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/php/{defaults,vars,tasks,meta,handlers}/main.yml
------编写httpd模块------
写一个简单的tasks/main.yml
vim /etc/ansible/roles/httpd/tasks/main.yml
- name: install apache
yum: name={{pkg}} state=latest
- name: start apache
service: enabled=true name={{svc}} state=started
//定义变量:可以定义在全局变量中,也可以定义在roles角色变量中,一般定义在角色变量中
vim /etc/ansible/roles/httpd/vars/main.yml
pkg: httpd
svc: httpd
-------编写mysql模块-------
vim /etc/ansible/roles/mysql/tasks/main.yml
- name: install mysql
yum: name={{pkg}} state=latest
- name: start mysql
service: enabled=true name={{svc}} state=started
vim /etc/ansible/roles/mysql/vars/main.yml
pkg:
- mariadb
- mariadb-server
svc: mariadb
-------编写php模块-----
vim /etc/ansible/roles/php/tasks/main.yml
- name: install php
yum: name={{pkg}} state=latest
- name: start php-fpm
service: enabled=true name={{svc}} state=started
vim /etc/ansible/roles/php/vars/main.yml
pkg:
- php
- php-fpm
svc: php-fpm
-----编写roles示例-----
vim /etc/ansible/site.yml
---
- hosts: webservers
remote_user: root
roles:
- httpd
- mysql
- php
cd /etc/ansible
ansible-playbook site.yml