学习ansible(一)

1、介绍

1 ansible基于Python开发的自动化运维工具
2 ansible基于ssh协议实现远程管理的工具,没有客户端
3 ansible软件可以实现多种批量管理操作

2、环境

主机 IP
ansible 服务端 192.168.4.11
ansible 客户端 192.168.4.12

3、安装

1、服务端:
yum install ansible 

2、客户端:
yum install libselinux-python 

 4、ansible命令参数

-m                 #模块名称,默认command  
-a                 #模块参数
-k                 #指定密码,用户密码,ansible.cfg可以配置
-u                 #指定用户,默认root,ansible.cfg可以配置
-C                 #检查并测试,不执行。
--syntax-check     #检查语法    
-f                 #并发进程数,默认:5
-s                 #sudo模式运行
-U                 #sudo用户,默认: root
-K                 #sudo密码
-B                 #异步模式,多少秒失败,后不执行
-P                 #轮询间隔,若使用-B,默认轮询间隔15秒
-c                 #连接类型,默认:smart(智能)
-i                 #指定hosts文件路径,默认/etc/ansible/hosts
-l                 #指定pattern,对已经匹配的主机中再过滤一次
--list-hosts       #输出匹配主机,但不执行任何操作
-M                 #模块路径,默认:/usr/share/ansible/plugins/modules
-o                 #压缩输出,重要的会输出
--private-key      #私钥路径
-T                 #连接超时时间,默认:10秒
-t                 #日志输出路径,日志文件名会以主机名命名
-v                 #详细模式(-vvv:更多,-vvvv:debug模式)

5、ansible 配置文件

# /etc/ansible/ansible.cfg                                                      #主配置文件(日志、模块、插件等)

常用配置:
#inventory = /etc/ansible/hosts                 #主机列表配置文件
#library = /usr/share/my_modules/               #库文件存放目录
#remote_tmp = ~/.ansible/tmp                    #远程主机临时执行目录
#local_tmp = ~/.ansible/tmp                     #本机临时执行目录
#forks = 5                                      #默认并发数
#sudo_user = root                               #默认sudo用户
#ask_sudo_pass = True                           #每次执行是否询问sudo的ssh密码
#ask_pass = True                                #每次执行是否询问ssh密码
#remote_port = 22                               #远程主机端口
host_key_checking = False                       #检查主机指纹(取消注释,不检查) 
log_path = /var/log/ansible.log                 #日志路径
#remote_user = root                             #SSH连接时的用户名
#private_key_file = /path/to/file               #SSH连接时的私钥文件
roles_path = /etc/ansible/roles:/path/roles     #roles路径,多个路径用冒号分隔
#gathering = implicit                           #控制收集Facts变量的策略

ssh配置
#ssh_args = -C -o ControlMaster=auto            #控制Ansible的ssh连接
#pipelining = False                             #多个task之间共享SSH连接,开启能够提升执行速度
#control_path =                                 #socket的路径

权限提升配置
#become=True                                    #是否进行权限提升
#become_method=sudo                             #权限提升的方式,默认:sudo
#become_user=root                               #权限提升的用户,默认:root
#become_ask_pass=False                          #权限提升的密码,默认:False,(不输入密码)

# /etc/ansible/hosts                                                                #主机清单

[nginx]                                         #组名
192.168.4.11                                    #IP地址或域名

#[tomcat-pass]                                  #密码认证方式
#192.168.4.12 ansible_ssh_user=root ansibel_ssh_port=22 ansible_ssh_pass=123456

# /etc/ansible/roles/                                                                #存放角色的目录(空目录)

6、Ansible管理认证方式

密码方式

1、ping在线主机
#ansible  all -m ping 
#ansible  all -m ping -u root -k            #指定用户和密码    

2、配置文件指定用户和密码
#cat  /etc/ansible/hosts
[tomcat-pass]                               #密码认证方式
192.168.4.12  ansible_ssh_user=root  ansibel_ssh_port=22  ansible_ssh_pass=123456

3、测试
#ansible  all -m ping 

密钥方式

1、创建SSH密钥对
ssh-keygen -f /root/.ssh/id_rsa -P "" -q        #免交互创建密钥对,-f:密钥文件的路径,-P或-N:密钥文件的提示信息,一般为空,-q:不输出结果信息
id_rsa                                          #生成的私钥
id_rsa.pub                                      #生成的公钥

2、非交互分发公钥
sshpass -p123456 ssh-copy-id -f -i ~/.ssh/id_rsa.pub "-o StrictHostKeyChecking=no" 192.168.4.12
sshpass -p远程主机密码,ssh-copy-id  -f:强制模式,-i:指定公钥文件,-p:端口,-o:跳过连接确认(ssh参数)

3、批量分发公钥
#
!/bin/bash #生成秘钥对 [ -e ~/.ssh/id_rsa ] && mv ~/.ssh/id_rsa* /tmp [ -e ~/.ssh/id_rsa ] || ssh-keygen -f ~/.ssh/id_rsa -P "" -q #分发秘钥 Ssh_Pass=123456 Key_Path=~/.ssh/id_rsa.pub ip=192.168.4. for id in 11 12 13 do sshpass -p$SSH_Pass ssh-copy-id -i $Key_Path "-o StrictHostKeyChecking=no" $ip$id done 4、配置文件 cat /etc/ansible/hosts [nginx] #组名 192.168.4.11 #IP地址或域名 5、测试 #ansible all -m ping

7、Ansible执行命令过程

1 加载配置文件 默认/etc/ansible/ansible.cfg
2 加载对应的模块文件,如command
3 通过ansible将模块或命令生成对应的临时py文件,并将文件传到远程主机上,~/.ansible/tmp/ansible-tmp-数字/XXX.PY文件
4 给文件+x执行
5 执行并返回结果
6 删除临时py文件,sleep 0退出

8、Ansible命令工具

ansible                  #主程序,命令执行工具
ansible-doc              #查看模块功能工具
ansible-galaxy           #上传/下载第三方模块指令
ansible-playbook         #定制自动化任务,编排工具
ansible-pull             #远程执行命令的工具
ansible-vault            #对playbook文件进行加密/解密
ansible-console          #基于Console界面与用户交互的执行工具

9、Ansible模块

模块查看和帮助

ansible-doc 
-l                       #列出所有的模块
-s                       #显示指定模块信息
ansible-doc 模块名        #直接查看完整信息
-j                       #以json的方式返回数据

command模块(执行命令模块,默认模块)

模块参数
chdir:切换目录
creates:当文件或目录存在时,不执行命令
removes:当文件或目录存在时,执行命令
warn:警告

实例
ansible nginx -m command -a "pwd"
ansible nginx -a "ls"
ansible nginx -a "chdir=/tmp pwd"                     #切换目录,并执行命令
ansible nginx -a "creates=/tmp pwd"                   #当文件存在时,pwd不执行
ansible nginx -a "removes=/tmp pwd"                   #当文件存在时,pwd执行
ansible nginx -a "chmod 000 /etc/hosts warn=False"    #忽略警告
注意:不支持 (>,<,|,&,;,变量等)

shell模块(万能模块,支持特殊字符)

模块参数
和command一样

实例
shell模块可以满足command模块所有功能,并支持特殊字符
ansible nginx -m shell -a "ls;pwd"
ansible nginx -m shell -a "ps -ef | grep sshd | grep -v grep"
ansible nginx -m shell -a "sh a.sh"
ansible nginx -m shell -a "python a.py"

script模块(本地脚本,远程执行)

实例
ansible nginx -m script -a "pwd.sh"
ansible nginx -m script -a "creates=/tmp/pwd.sh /tmp/pwd.sh"    #当文件存在时,不执行脚本

copy模块

模块参数
src:源
dest:目标
owner:属主
group:属组
mode:权限
content:定义文件的内容
backup:备份
force:强制覆盖文件,默认为yes

实例
ansible nginx -m copy -a "src=/data/test.txt dest=/tmp/ owner=tom group=tom mode=0755"  #复制文件并修改权限
ansible nginx -m copy -a "content='I Live You' dest=/tmp/test.txt backup=yes"           #备份并修改文件内容
ansible nginx -m copy -a  "src=/etc/hosts dest=/tmp/a/b/c/d/"                           #创建多级目录  

file模块

模块参数
path:文件路径,别名dest、name
state:directory(目录)、touch(文件)、link(软连接)、absent(删除)、hard(硬链接)
src:源文件
recurse:递归
force:强制创建软连接,默认为no(更新软连接)

实例
ansible nginx -m file -a "path=/tmp/test state=directory"                               #创建目录
ansible nginx -m file -a "path=/tmp/test owner=tom group=tom mode=644 state=touch"      #创建文件并修改权限
ansible nginx -m file -a "src=/usr/local/nginx/ dest=/tmp/nginx state=link"             #创建软连接
ansible nginx -m file -a "path=/tmp/nginx state=absent"                                 #删除软连接
ansible nginx -m file -a "path=/tmp/test state=directory mode=644 recurse=yes"          #递归设置权限

yum模块

模块参数
name:软件包名称,可以指定版本号,可以本地RPM包,可以URL文件
state:状态,installed(安装)、absent(卸载)
enablerepo:启用某个源
disablerepo:禁用某个源
disable_gpg_check:关闭gpg_check 
config_file:yum的配置文件 

实例
ansible nginx -m yum -a "name=telnet state=installed"   
ansible nginx -m yum -a "list=telnet"                      #查看软件包是否安装
ansible nginx -m yum -a "name=nginx,telnet"
ansible nginx -m yum -a "name=nginx state=absent"          #最好不要用yum卸载,用rpm -e卸载

systemd服务模块

模块参数
name:服务的名称
state:服务状态(started、stopped、restarted、reloaded)
enabled:服务是否开机自启

实例
ansible nginx -m systemd -a "name=crond enabled=no state=stopped "
ansible nginx -m systemd -a "name=crond enabled=yes state=started"

cron模块

模块参数
name:名称(添加不能相同,不加为None)
minute:分钟
hour:小时
day:天
month:月
weekday:周
job:任务
disabled:禁用(前面加#)
user:用户
state:状态(present、absent)
backup:备份
env:环境变量(name=job定义变量的值)

实例
ansible nginx -m cron -a "name='时间同步' minute=0 hour=0 job='ntpdate ntp1.aliyun.com'"
ansible nginx -m cron -a "name='时间同步' minute=*/1 backup=yes job='ntpdate ntp1.aliyun.com'"              
ansible nginx -m cron -a "env=yes name='TEST' backup=yes job='echo test'"
ansible nginx -m cron -a "name='重启时执行任务' special_time=reboot job='echo test'"
ansible nginx -m cron -a "name='重启时执行任务' disabled=true job='echo test'"         
ansible nginx -m cron -a "name='每小时执行一次' special_time=hourly job='echo test'"
ansible nginx -m cron -a "name='每小时执行一次' backup=yes state=absent"     
ansible nginx -m cron -a "name=None state=absent" 

mount模块

模块参数
fstype:挂载文件的类型
path:挂载点(别名name)
opts:挂载参数选项
src:要挂载的设备
state:状态(present:不挂载,仅写到fstab;mounted:挂载并写到fstab;unmounted:卸载,不清除fstab;absent:卸载,清除fstab)

实例
ansible nginx -m mount -a "src=192.168.4.11:/data path=/data fstype=nfs opts=defaults state=present"
ansible nginx -m mount -a "src=192.168.4.11:/data path=/data fstype=nfs opts=defaults state=mounted"
ansible nginx -m mount -a "src=192.168.4.11:/data path=/data fstype=nfs opts=defaults state=unmounted"
ansible nginx -m mount -a "src=192.168.4.11:/data path=/data fstype=nfs opts=defaults state=absent"

user模块

模块参数
name:用户名
group:属组
groups:附加组
home:家目录
create_home:是否创建家目录
remove:删除用户及家目录
shell:用户的shell
system:系统用户
uid:用户的id
password:密码
state:状态(present为默认、absent)
force:强制删除用户及家目录

实例
ansible nginx -m user -a "name=test"
ansible nginx -m user -a "name=test state=absent"           
ansible nginx -m user -a "name=test state=absent remove=yes"
ansible nginx -m user -a "name=test group=root"
ansible nginx -m user -a "name=test groups=python append=yes"
ansible nginx -m user -a 'name=test password="123456"
ansible nginx -m user -a "name=test expires=1546185600"
ansible nginx -m user -a "name=test uid=8888 shell=/sbin/nologin create_home=no"

10、playbook

简介

playbook==剧本,由多个play组成,一个play包含多个task任务,采用YAML语言编写的
paly:主机的角色,task:具体执行的任务。使用不同的模块完成一件事
- playbook      剧本                    YAML文件     
- play          找谁                    主机web01
- task          做什么                  yum、copy、service

yaml语法简介

规则一:缩进(两个空格,不能用tab键)
规则二:冒号(冒号后面要有空格,以冒号结尾或表示文件路径不需要空格。)
规则三:短横线(表示列表,后面要有空格)
#号注释,k/v值可同一行,也可换行,同行用:,换行用 -

1、- 用法(列表) 水果信息: - 苹果 - 香蕉 - 西瓜
2、:用法(前者的值) 姓名: 张三 性别: 男 人员信息: - 运维人员: sa - 开发人员: dev - 存储人员: dba
3、用法(空格): 软件安装步骤: - 服务端安装步骤: 第一个里程碑: 检查软件是否安装 第二个里程碑: 编写配置文件内容 - 客户端安装步骤:

playbook参数

-C:                 检查脚本语法,不执行
--syntax-check:     检查语法
-e:                 引入外部变量
--list-hosts:       列出运行任务的主机
--limit hosts:      只主机列表中的主机执行
-f:                 并发数,默认5
-k:                 用户密码
--ask-vault-pass:   加密playbook文件时提示输入密码
-D:即--diff:        更新文件时,显示不同的内容,结合-C会有较好的效果
--flush-cache:      清除远程主机缓存
--force-handlers:   强制运行handlers的任务,即使在任务失败的情况下
-i :                指定主机清单文件
--list-tags:        列出所有可用的tags
--list-tasks:       列出所有即将被执行的任务。
--skip-tags:        跳过指定的tags任务。
--start-at-task:    从第几条任务开始执行。
--step:             逐步执行任务,运行前确认每个任务
-t:                  指定执行该tags的任务

setup 模块(收集某主机信息)

# ansible nginx -m setup
常用变量
ansible_all_ipv4_addresses          #所有的ipv4地址
ansible_date_time                   #系统时间
ansible_default_ipv4                #默认的ipv4地址(ip、网段、网卡)
ansible_device_links                #系统的磁盘信息
ansible_distribution                #系统名称
ansible_distribution_major_version  #系统的主版本
ansible_distribution_version        #系统的全部版本
ansible_dns                         #系统的dns 默认udp 端口53
ansible_domain                      #系统的域 ldap
ipv4                                #ipv4地址
ansible_env                         #系统的环境
ansible_fqdn                        #系统的完整主机名
ansible_hostname                    #系统的简写主机名
ansible_kernel                      #系统的内核版本
ansible_machine                     #系统的架构
ansible_memtotal_mb                 #系统的内存
ansible_memory_mb                   #系统的内存使用情况
ansible_mounts                      #系统的挂载信息
ansible_processor                   #系统的cpu
ansible_processor_cores             #每颗cpu的核数
ansible_processor_count             #cpu的颗数
ansible_processor_vcpus             #cpu的个数=cpu的颗数*每颗cpu的核数
ansible_python                      #系统python信息
ansible_python_version              #系统python的版本
ansible_system                      #系统名字

palybook核心元素

hosts:               远程主机列表
tasks:               任务集
variables:           内置或自定义变量
templates:           模板,可替换模板文件中的变量并实现一些简单逻辑的文件
handlers 和notity :  必须结合使用,由特定的条件触发操作,由notity通知handlers执行
tags:                标签,指定某条件任务执行,用于选择运行playbook中的部分代码
hosts元素
hosts:远程主机列表
cat /root/ansible/hosts.yml
- hosts: web
  remote_user: root         #远程的用户

hosts主机列表形式:   
test.com            #主机名
192.168.4.12        #IP
web                 #组名
web:db              #两个组的并集
web:!db             #两个组的差集
web:&db             #两个组的交集
tasks元素
tasks:任务集
cat /root/ansible/tasks.yml
- hosts: web
  remote_user: root
  tasks:
    - name: create_new_file
      file: name=/test/test.txt state=touch
    - name: create_new_user
      user: name=tom state=present system=yes shell=/sbin/nologin

## name:描述信息,file和user:模块名,后面模块的具体操作
handlers和notify元素
notify元素:作为handlers的触发器(当tasks中触发到notify时,会优先执行handlers中的代码)
handlers元素:和tasks同级的列表,等待任务触发notify后执行  
cat /root/ansible/nginx.yml
- hosts: web
  remote_user: root
  tasks:
    - name: install_nginx
      yum: name=nginx
    - name: nginx_config
      copy: src="/etc/nginx/nginx.conf" dest="/etc/nginx/" backup=yes
      notify:
        - restart_nginx
        - check_service
    - name: start_nginx
      service: name=nginx state=started enabled=yes
  handlers:
    - name: restart_nginx
      service: name=nginx state=restarted
    - name: check_service
      shell: killall -0 nginx > /tmp/nginx.log

## killall
-0 nginx 检查nginx的进程有没有启动,返回0启动,非0没有启动
tags元素
tags元素:在某个任务打标签,方便单独执行或被其他调用
cat  /root/ansible/nginx.yml
- hosts: web
  remote_user: root
  tasks:
    - name: install nginx
      yum: name=nginx
      tags: install_nginx
    - name: copy nginx config file
      copy: src="/etc/nginx/nginx.conf" dest="/etc/nginx/" backup=yes
      notify:
        - restart nginx
        - check service
    - name: start nginx
      service: name=nginx state=started enabled=yes
      tags: start_nginx
  handlers:
    - name: restart nginx
      service: name=nginx state=restarted
    - name: check service
      shell: killall -0 nginx > /tmp/nginx.log

单独执行startnginx任务 ansible
-playbook -t startnginx /root/ansible/nginx.yml 指定两个标签执行 ansible-playbook -t install_nginx,startnginx /root/ansible/nginx.yml
vars元素
vars元素:定义变量
ansible nginx -m setup                               #查看变量
ansible nginx -m setup | grep ansible_fqdn           #通过变量过滤主机名
ansible nginx -m setup -a "filter=ansible_fqdn"      #通过变量过滤主机名

1、在/etc/ansible/hosts中定义变量(http_port)
[test]
192.168.4.12         http_port=8080
在playbook中使用变量
- hosts: web
  remote_user: root
  tasks:
    - name: set hostname
      hostname: name=test{{ http_port }}.python.com

2、通过命令行定义的变量,优先级最高(使用{{}}定义变量)
- hosts: web
  remote_user: root
  tasks:
    - name: install nginx
      yum: name={{ app1 }}
    - name: install vsftpd
      yum: name={{ app2 }}
    - name: copy nginx config file
      copy: src="/etc/nginx/nginx.conf" dest="/etc/nginx/" backup=yes
    - name: start nginx
      service: name={{ app1 }} state=started enabled=yes 
ansible-playbook -e 'app1=nginx app2=vsftpd' /root/ansible/nginx.yml     #-e 定义变量
 
3、用vars元素定义变量列表
- hosts: web
  remote_user: root
  vars:
    - app1: nginx
  tasks:
    - name: install nginx
      yum: name={{ app1 }}
    - name: copy nginx config file
      copy: src="/etc/nginx/nginx.conf" dest="/etc/nginx/" backup=yes
    - name: start nginx
      service: name={{ app1 }} state=started enabled=yes

4、将变量存放到一个文件中,在playbook里面调用
cat /root/ansible/vars.yml      
var1: nginx
var2: nsftpd
 
cat /root/ansible/yum.yml 
- hosts: web
  remote_user: root
  vars_files:
    - vars.yml
  tasks:
    - name: install nginx
      yum: name={{ var1 }}
    - name: install vsftpd
      yum: name={{ var2 }}
templates元素
模板文件,能够实现不同的主机,修改不同的配置文件
模板文件的编程语言是jinja2语言,支持的类型:
- 字符串: 使用单引号或者双引号
- 数字: 整数,浮点数
- 列表: [item1,item2,..]
- 元组: (item1,item2,..)
- 字典: {key1:value1,key2:value2,..}
- 布尔值: true/false
- 算数运算符: +,-,*,/,//,%,**
- 比较运算符: ==,!=,>,>=,<,<=
- 逻辑运算符: and,or,not
- 流表达式: for if when
1、#cat
/root/ansible/templates/nginx.conf.j2 worker_processes {{ ansible_processor_vcpus**2 }}; #远程主机的cpu的个数
2、#cat
/root/ansible/nginx.yml - hosts: web remote_user: root tasks: - name: install nginx yum: name=nginx - name: copy templates file template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf notify: restart nginx - name: start nginx service: name=nginx state=started enabled=yes handlers: - name: restart nginx service: name=nginx state=restarted
3、#ansible
-playbook /root/ansible/nginx.yml 4、#cat /root/ansible/templates/nginx.conf.j2 listen {{ http_port }} default_server; listen [::]:{{ http_port }} default_server; # ansible-playbook /root/ansible/nginx.yml
跳过错误继续执行
为了解决tasks中某段代码执行出现问题,是否继续执行,默认出错就停止
- hosts: web
  remote_user: root 
  tasks: run this command and ignore the resullt
    - name: shell start nginx
      shell: /usr/bin/somecommand || /bin/true
或者
- hosts: web
  remote_user: root
  tasks:
    - name: run this command and ignore the resullt
      shell: /usr/bin/somecommand
      ignore_errors: True
when语句
when语句:条件的测试,需要根据变量、facts或任务执行的结果,做相应的条件测试。
# 定义两个配置文件
cp /etc/nginx/nginx.conf /root/ansible/templates/nginx6.conf.j2
cp /etc/nginx/nginx.conf /root/ansible/templates/nginx7.conf.j2

cat
/root/ansible/nginxtemp.yml - hosts: web remote_user: root tasks: - name: install nginx yum: name=nginx - name: copy templates file for centos7 template: src=nginx7.conf.j2 dest=/etc/nginx/nginx.conf when: ansible_distribution_major_version == '7' notify: restart nginx - name: copy templates file for centos6 template: src=nginx6.conf.j2 dest=/etc/nginx/nginx.conf when: ansible_distribution_major_version == '6' notify: restart nginx - name: start nginx service: name=nginx state=started enabled=yes handlers: - name: restart nginx service: name=nginx state=restarted
with_items语句
with_items:循环,当执行重复性任务的时,使用迭代机制来实现
固定变量:"item",来引用
在tasks中用with_items定义循环的元素列表(支持的格式:字符串、字典)

创建多个文件及安装多个包
cat /root/ansible/items.yml - hosts: web remote_user: root tasks: - name: create file file: name=/root/ansible/{{ item }} state=touch with_items: - file1 - file2 - file3 - name: install packages yum: name={{ item }} with_items: - htop - sl - hping3
 迭代嵌套子变量
创建多个用户和组,将用户加入到不同的组
# cat /root/ansible/guser.yml
- hosts: web
  remote_user: root
  tasks:
    - name: add groups
      group: name={{ item }} state=present
      with_items:
        - g1
        - g2
        - g3
    - name: add user for goups
      user: name={{ item.name }} group={{ item.group }} state=present
      with_items:
        - { name: 'user1', group: 'g1'}
        - { name: 'user2', group: 'g2'}
        - { name: 'user3', group: 'g3'}
for语句
1、定义变量
# cat /root/ansible/testfor.yml
- hosts: web
  remote_user: root
  vars:
    ports:
      - 81
      - 82
      - 83
  tasks:
    - name: create for config
      template: src=/root/ansible/testfor.conf.j2 dest=/root/ansible/testfor.conf
      
2、模板文件编写
# cat /root/ansible/testfor.conf.j2
{% for p in ports %}
server {
  listen {{ p }}
}
{% enfor %}

3、执行
# ansible-playbook /root/ansible/testfor.yml

4、查看结果
server {
  listen: 81
}
server {
  listen: 82
}
server {
  listen: 83
}
 
1、定义变量
- hosts: web
  remote_user: root
  vars:
    weblist:
      - web:
        port: 81
        name: python.test.com
        rootdir: /nginx/python
      - web2:
        port: 82
        name: php.test.com
        rootdir: /nginx/php
  tasks:
    - name: create for config
      template: src=/root/ansible/testfor.conf.j2 dest=/root/ansible/testfor.conf
 
2、模板文件
cat /root/ansible/testfor.conf.j2
{% for w in weblist %}
server {
  listen {{ w.port }}
  servername {{ w.name }}
  documentroot {{ w.rootdir }}
}
{% endfor %}
if语句
1、定义变量
# cat /root/ansible/testfor.yml
- hosts: web
  remote_user: root
  vars:
    weblist:
      - web:
        port: 81
        rootdir: /nginx/python
      - web2:
        port: 82
        name: php.test.com
        rootdir: /nginx/php
  tasks:
    - name: create for config
      template: src=/root/ansible/testfor.conf.j2 dest=/root/ansible/testfor.conf
 
2、模板文件
cat /root/ansible/testfor.conf.j2
{% for w in weblist %}
server {
  listen {{ w.port }}
{% if w.name is defined %}
  servername {{ w.name }}
{% endif %}
  documentroot {{ w.rootdir }}
}
{% endfor %}
 
3、执行
# ansible-playbook  /root/ansible/testfor.yml
 
4、查看结果
server {
  listen 81
  documentroot /nginx/python
}
server {
  listen 82
  servername php.test.com
  documentroot /nginx/php
}

11、实例

 创建用户

- hosts: web
  remote_user: root
  tasks:
  - name: create_user
    user: name=test uid=2000 state=present

创建用户 和 复制文件

- hosts: web
  remote_user: root
  tasks:
  - name: create_user
    user: name=test uid=2000 state=present 
  - name: copy_file
    copy: src=/etc/hosts dest=/tmp/fs

创建一个用户(变量)

方法一:
- hosts: web
  tasks:
  - name: create_user
    user: name={{user}}
# ansible-playbook -e user=test useradd.yml

方法二:
- hosts: web vars: - user: test tasks: - name: create_user user: name={{user}}
方法三:
- hosts: web tasks: - name: yum yum: name=bc - name: sum shell: echo 11+22|bc register: user #注册成变量,返回结果为后面使用 - name: create_user user: name=test{{user.stdout}}

tags(标签,只执行带标签的代码)

- hosts: web
  tasks:
  - name: install
    yum: name=redis
  - name: copy_file
    copy: dest=/etc/redis.conf src=/etc/redis.conf
    tags: copy
  - name: start
    service: name=redis state=started
# ansible-playbook -t copy tags.yml     #仅运行标签所在的一项

handlers(改变时触发,执行某一项)

- hosts: web
  tasks:
  - name: install
    yum: name=redis
  - name: copyfile
    copy: dest=/etc/redis.conf src=/etc/redis.conf
    tags: copy
    notify: restart                     #改变时触发
  - name: start
    service: name=redis state=started
  handlers:                        #触发项
  - name: restart
    service: name=redis state=restarted

template  模块(基于jinja2)

cat /etc/redis.conf
bind {{ ansible_default_ipv4.address }}

- hosts: web
  tasks:
  - name: install
    yum: name=redis
  - name: copy_file
    template: dest=/etc/redis.conf src=/etc/redis.conf      #直接替换(绝对路径)
    tags: copy
    notify: restart
  - name: start
    service: name=redis state=started
  handlers:
  - name: restart
    service: name=redis state=restarted

- hosts: web
  tasks:
  - name: install
    yum: name=redis
  - name: copy_file
    template: dest=/etc/redis.conf src=redis.conf.j2        #直接替换(相对路径)
    tags: copy
    notify: restart
  - name: start
    service: name=redis state=started
  handlers:
  - name: restart
    service: name=redis state=restarted

when (类似python 中的 if)

- hosts: web
  tasks:
  - name: copy_file
    copy: content="centos7" dest=/tmp/a.txt
    when: ansible_distribution_major_version=="7"           #利用收集的信息
  - name: copy_file
    copy: content="centos6" dest=/tmp/a.txt
    when: ansible_distribution_major_version=="6"

with_items (类似python中的 while)

- hosts: web
  tasks:
  - name: crate_user
    user: name={{item.name}}  group={{item.group}}
    with_items:
    - {"name":test01,"group":test}
    - {"name":test02,"group":test}
    - {"name":test03,"group":test}

roles  (角色)

1、创建roles任务文件
#cat ./roles/nginx/ ├── files -- 静态文件 │ └── c.txt ├── handlers -- 触发的任务 │ └── main.yml ├── tasks -- 任务(必须的) │ ├── copyfile.yml │ ├── install.yml │ ├── main.yml │ └── start.yml ├── templates -- 动态文件,需要传递参数 │ └── nginx.conf └── vars -- 变量 └── main.yml 查找顺序: - 主文件看到roles,就回去roles目录下面找对应的目录 - 先去tasks目录里面找main.yml文件,如果遇到import_task则加载任务 - 如果遇到了template,则去templates目录里面找文件 - 如果遇到了copy,则去files目录里面找文件 - 如果遇到了变量,则去vars目录里面找main.yml文件 - 如果遇到了notify,则去handlers目录里面找main.yml文件
2、创建主机roles文件
#cat nginx.yml
- hosts: web roles: nginx
3、执行
# ansible
-playbook nginx.yml

创建文件2种方法

- hosts: webservers
  tasks:
    - name: Create New File
      file: path=/tmp/123.txt state=touch owner=root group=root mode=600
    - name: Create New File2
      file:
        path: /tmp/456.txt
        state: touch
        owner: root
        group: root
        mode: 0666      

部署nfs服务

1、编写nfs-server文件
- hosts: nfs_servers
  tasks:
    - name: Installed NFS Server
      yum:
        name: nfs-utils
        state: present
    - name: Configure NFS Server
      copy:
        src: ./file/exports.j2 
        dest: /etc/exports
        owner: root
        group: root
        mode: 0644
        backup: yes
    - name: Create NFS Group www
      group:
        name: www
        gid: 666
    - name: Create NFS User www
      user:
        name: www
        group: www
        uid: 666
        create_home: no
        shell: /sbin/nologin
    - name: Create NFS Share Directory
      file:
        path: /ansible_data
        state: directory
        owner: www
        group: www
        mode: 0755
        recurse: yes
    - name: Systemd NFS Server 
      systemd:
        name: nfs
        state: restarted
        enabled: yes

2、编写nfs-clinet的yml 
- hosts: webservers
  tasks:
    - name: Mount NFS Server share directory
      mount:
        src: 192.168.4.12:/ansible_data
        path: /mnt
        fstype: nfs
        opts: defaults
        state: mounted

部署nginx服务

- hosts: webservers
  tasks:
    - name: Installed Nginx Server
      yum:
        name: nginx
        state: present
    - name: Configure Nginx Server
      copy:
        src: ./file/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: 0644
        backup: yes
      notify: Restart Nginx Server      
    - name: Systmd nginx Server
      systemd:
        name: nginx
        state: started
        enabled: yes
  handlers:
    - name: Restart Nginx Server
      systemd:
        name: nginx
        state: restarted

部署rsync

- hosts: 192.168.4.12
  tasks:
    - name: install rsync
      yum: name=rsync state=installed
    - name: rsync conf file
      copy: src=/etc/ansible/conf/rsync_conf/rsyncd.conf dest=/etc/
    - name: create rsync user
      user: name=rsync state=present createhome=no shell=/sbin/nologin
    - name: create auth file
      copy: src=/etc/ansible/conf/rsync_conf/rsync.password dest=/etc/ mode=600
    - name: create backup dir
      file: dest=/backup state=directory owner=rsync group=rsync
    - name: boot rsync server
      shell: rsync --daemon --config=/etc/rsyncd.conf
- hosts: 192.168.4.11
  tasks:
    - name: create auth file
      copy: src=/etc/ansible/conf/rsync_conf/rsync_client.password dest=/etc/rsync.password mode=600
    - name: test
      shell: rsync -az --password-file=/etc/rsync.password  /tmp/a.txt test@192.168.4.12::backup/    

ansible

原文地址:https://www.cnblogs.com/wuhg/p/12734695.html