码迷,mamicode.com
首页 > 其他好文 > 详细

ansible基础-模块-playbook-roles角色

时间:2019-10-26 15:00:51      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:hal   其他   type   ansible   nts   返回结果   role   srv   attr   

1、安装:

 wget https://mirrors.aliyun.com/centos/7/os/x86_64/Packages/yum-metadata-parser-1.1.4-10.el7.x86_64.rpm

 rpm -ivh *.rpm  --nodeps --force 这里我选择强制安装不考虑依赖 (线上注意处理掉依赖问题

 yum -y install epel-release

 yum -y install ansible

 ansible --version #测试如果显示版本 既安装成功

密钥小插曲:

????非交互式传公钥

 ssh-keygen -f /root/.ssh/id_rsa -N ""

 -f 指定私钥存放路径

 -N "" 新密码设置 “为空” 

[root@ansible .ssh]# sshpass -p123123 ssh-copy-id -i /root/.ssh/id_rsa.pub "root@192.168.31.102 -o StrictHostKeyChecking=no" 
Warning: Permanently added ‘192.168.31.102‘ (RSA) to the list of known hosts.
Now try logging into the machine, with "ssh ‘root@192.168.31.102 -o StrictHostKeyChecking=no‘", and check in:

  .ssh/authorized_keys

to make sure we haven‘t added extra keys that you weren‘t expecting.

 测试:

[root@ansible .ssh]# for ip in `seq 101 104`;do    
> ssh root@192.168.31.$ip "hostname"
> done
node1
node4
node2
node3

2、主机清单(inventory)

??Inventory主机清单

ansible的主要功能用于批量主机操作,为了便捷地使用其中的部分主机,可以在inventory file中将其分组命名

??默认的inventory file为/etc/ansible/hosts

??inventory file 可以有多个,且也可以通过Dynamic(动态) Inventory 来动态生成

 可以设置分组 /etc/ansible/hosts  

[testhost] #组1
192.168.1.4:222   #为了服务器安全问题 可能会修改端口号 配置文件中这么定义
192.168.1.6
192.168.1.8

[gamedb] #组2
192.168.1.5
192.168.1.11

[gameserver] #组3
192.168.1.[0:254] #整个网段

[logdb] #组4
db-[a:f].example.com #a-f 所有的主机

 例子:

[root@ansible .ssh]# ansible testhost -m ping
192.168.1.6 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.8 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.4 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

 ansible配置文件

 /etc/ansible/ansible.cfg  说一下默认配置

[defaults]

# some basic default values...

#inventory      = /etc/ansible/hosts  #主机清单
#library        = /usr/share/my_modules/  #库
#module_utils   = /usr/share/my_module_utils/  #模块路径
#remote_tmp     = ~/.ansible/tmp  #临时py命令文件存放在远程主机目录
#local_tmp      = ~/.ansible/tmp  #本地的临时命令执行目录
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml #插件配置文件
#forks          = 5   #同时执行5个命令
#poll_interval  = 15  #15秒拉一起数据
#sudo_user      = root  #链接到对象可以切换到root 用sudo命令
#ask_sudo_pass = True    #sudo口令
#ask_pass      = True    #是否支持用户口令
#transport      = smart    #传输 用的不多
#remote_port    = 22      #默认22
#module_lang    = C      #语言
#module_set_locale = False 
#host_key_checking = Fales  #检查对应服务器的host_key,建议取消注视
#log_pah = /var/log/ansible.log  #日志文件 建议取消注视

3、ansible系列命令

??ansible-doc :显示模块帮助

  ansible-doc[options][module...]

  -a    显示所有模块的文档  #很多 很慢

  -l,--list  列出可用模块  #很多 还行

  -s,--snippet 显示指定模块的playbook片段

例子

[root@ansible log]# ansible-doc -s ping #ansible -a 还有ansible -l 就不展示了 太长了
- name: Try to connect to host, verify a usable python and return `pong‘ on success
  ping:
      data:                  # Data to return for the `ping‘ return value. If this
                               parameter is set to
                               `crash‘, the module will
                               cause an exception.
[root@ansible log]# 

??ansible通过ssh实现配 置管理、应用部署、任务执行等功能,建议配置ansible端能基于密钥认证的方式联系各被管理节点

ansible <host-pattern> [-m module_name] [-a args]

  --version 版本信息

  m moule模块,默认为command

  -v 详细过程 -vv -vvv更详细

  --list-host 显示主机列表,可简写--list

  -k,--ask-pass 提示输入ssh链接密码 默认Kay验证

  -K,--ask-become-pass 提示输入sudo时口令

  -C,--check  检查并不执行

  -T,--timeout=TIMEOUT  执行命令的超时时间,默认10s

  -u, --user=REMOTE_USER  执行远程执行得用户

  -b,--become    代替旧版的sudo切换

例子:

[root@ansible log]# ansible all -u ygcn -bKk -m command -a "ls /root" 
SSH password:  #ygcn密码
SUDO password[defaults to SSH password]: # sudo密码
192.168.1.6 | SUCCESS | rc=0 >>
anaconda-ks.cfg
apache-tomcat-8.0.48.tar.gz
install.log
install.log.syslog
jdk-8u25-linux-x64.rpm

192.168.1.8 | SUCCESS | rc=0 >>
anaconda-ks.cfg
install.log
install.log.syslog

192.168.1.4 | SUCCESS | rc=0 >>
anaconda-ks.cfg
install.log
install.log.syslog
[root@ansible log]#
各位如果执行失败,权限问题。ygcn没有sudo的权限
命令:visudo 
## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL #取消本行注视

usermod -aG wheel ygcn #把用户加入组中

 ??小技巧:如果visudo或者vim 没有颜色  执行下面两条即可 

  echo export EDITOR=vim >> /etc/profile.d/env.sh

   . /etc/profile.d/env.sh 

4、ansible的Host-pattern(ansible主机模式)

1、ALL :表示所有Inventory中的所有主机

  例子:ansible all -m ping

[root@ansible ~]# cat /etc/ansible/hosts |tail -n 8
[webserver]
192.168.1.10
192.168.1.6
[dbserver]
192.168.1.8
192.168.1.6
[root@ansible ~]# ansible all -m ping 
192.168.1.8 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.10 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.6 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
} 

2、*   :通配符

  例子:ansible  "*" -m ping   #匹配所有

[root@ansible ~]# cat /etc/ansible/hosts |tail -n 8
[webserver]
192.168.1.10
192.168.1.6
[dbserver]
192.168.1.8
192.168.1.6
[root@ansible ~]# ansible "*" -m ping 
192.168.1.8 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.6 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.10 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

3、 或关系

  例子:ansible "webservs:appsrvs" -m ping

     ansible "192.168.1.10:192.168.1.20" -m ping

[root@ansible ~]# cat /etc/ansible/hosts |tail -n 8
[webserver]
192.168.1.10
192.168.1.6
[dbserver]
192.168.1.8
192.168.1.6
[root@ansible ~]# ansible "webserver:dbserver" -m ping 
192.168.1.8 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.6 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.10 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

4、逻辑与

  例子:ansible "webservs:&dservs" -m ping  # 在webservs组并且在dbservs中的主机  两台机器同时拥有的

[root@ansible ~]# cat /etc/ansible/hosts |tail -n 8
[webserver]
192.168.1.10
192.168.1.6
[dbserver]
192.168.1.8
192.168.1.6
[root@ansible ~]# ansible "webserver:&dbserver" -m ping  #可以理解为交集
192.168.1.6 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}  

5、逻辑非

  例子:ansible ‘webservs:!dservs‘ -m ping # 在sebsrvs组,但是不在dbservs组中的主机 #注意:此处为单引号

[root@ansible ~]# cat /etc/ansible/hosts |tail -n 8
[webserver]
192.168.1.10
192.168.1.6
[dbserver]
192.168.1.8
192.168.1.6
[root@ansible ~]# ansible ‘webserver:!dbserver‘ -m ping  #注意单引号
192.168.1.10 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

6、综合逻辑

  例子:ansible ‘webservs:dbservs:&appsrvs:!ftpsrvs‘ -m ping

      webservs或者dbservs并且appsrvs而且还不能在ftpsrvs

      比较复杂一般生产中不会这么用

7、正则表达式

  例子:ansible "websrvs:&dbsrvs" -m ping

     ansible "~(web|db).*\.magedu\.com" -m ping 

      匹配 web或者db 已magede和.com结尾的

[root@ansible ~]# cat /etc/ansible/hosts |tail -n 8
[webserver]
192.168.1.10
192.168.1.6
[dbserver]
192.168.1.8
192.168.1.6
[root@ansible ~]# ansible ‘~(web|db)server‘ -m ping 
192.168.1.6 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.10 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.8 | SUCCESS => {
    "changed": false, 
    "ping": "pong"

5、ansible 命令执行过程

??ansible命令执行过程

 1.加载自己的配置文件 默认/etc/ansible/ansible.cfg

 2.加载自己对应的模块文件 如command

 3.通过ansible将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器的对应执行用户$HOME/.ansible/tmp/ansible-tmp-数字/xxx.py文件

   4.给文件加执行权限 执行

   5.执行并返回结果

   6.删除临时py文件,sleep 0 推出

??执行状态:

  1.绿色:执行成功并且不需要做改变的操作

  2.黄色:执行成功并且对目标主机做变更

  3.红色:执行失败

6、ansible 常用模块

ansible支持的模块很多,我们并不需要把每个模块都记住,而需要熟悉一些常见的模块,其他的模块在需要用到时在查询即可。

ansible用法:

  ansible 机器 -m 模块 -a ‘模块参数

  基本格式:ansible 操作的机器名或组 -m 模块名字 -a ‘参数1=值1 参数2=值2 ......

??hostname模块

 ansible 192.168.31.101 -m hostname -a ‘name=tyschool_node1

 修改机器31.101 hostname设置为tyschool_node1

[root@ansible .ssh]# ansible 192.168.31.101 -m hostname -a ‘name=tyschool_node1‘
192.168.31.101 | SUCCESS => {
    "ansible_facts": {
        "ansible_domain": "", 
        "ansible_fqdn": "tyschool_node1", 
        "ansible_hostname": "tyschool_node1", 
        "ansible_nodename": "tyschool_node1"
    }, 
    "changed": true, 
    "name": "tyschool_node1"
}

??file(重点)模块

file模块用于对文件或文件夹相关的操作,主要用来设置文件、链接、目录的属性,或者移除文件、链接、目录,很多其他的模块也会包含这种作用。如copy\assemble\template

path

文件路径

state

操作(touch文件新建、absent删除、link软连接、hard硬链接、directory目录创建)

owner

设置所有者

group

设置所属的组

mode

权限 0000

recurse

递归 yes or no

创建文件:ansible all -m file -a ‘path=/opt/ytschool state=touch‘

192.168.31.101 | SUCCESS => {
    "changed": true, 
    "dest": "/opt/ytschool", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}

 删除文件:ansible all -m file -a ‘path=/opt/ytschool state=absent‘

[root@ansible .ssh]# ansible all -m file -a ‘path=/opt/ytschool state=absent‘
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "path": "/opt/ytschool", 
    "state": "absent"
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "path": "/opt/ytschool", 
    "state": "absent"
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "path": "/opt/ytschool", 
    "state": "absent"
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "path": "/opt/ytschool", 
    "state": "absent"
}

文件权限:ansible all -m file -a ‘path=/opt/ytschool owner=ygcn group=nobody mode=0600‘

[root@ansible .ssh]# ansible all -m file -a ‘path=/opt/ytschool owner=ygcn group=nobody mode=0600‘
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "gid": 99, 
    "group": "nobody", 
    "mode": "0600", 
    "owner": "ygcn", 
    "path": "/opt/ytschool", 
    "size": 0, 
    "state": "file", 
    "uid": 500
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "gid": 99, 
    "group": "nobody", 
    "mode": "0600", 
    "owner": "ygcn", 
    "path": "/opt/ytschool", 
    "size": 0, 
    "state": "file", 
    "uid": 500
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "gid": 99, 
    "group": "nobody", 
    "mode": "0600", 
    "owner": "ygcn", 
    "path": "/opt/ytschool", 
    "size": 0, 
    "state": "file", 
    "uid": 500
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "gid": 99, 
    "group": "nobody", 
    "mode": "0600", 
    "owner": "ygcn", 
    "path": "/opt/ytschool", 
    "size": 0, 
    "state": "file", 
    "uid": 500
}

创建链接文件[软\硬]: ansible all -m file -a ‘src=/opt/ytschool path=/opt/tmp_school state=link‘

            ansible all -m file -a ‘src=/opt/ytschool path=/opt/tmp_school_ying state=hard‘

[root@ansible .ssh]# ansible all -m file -a ‘src=/opt/ytschool path=/opt/tmp_school state=link‘
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "dest": "/opt/tmp_school", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 13, 
    "src": "/opt/ytschool", 
    "state": "link", 
    "uid": 0
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "dest": "/opt/tmp_school", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 13, 
    "src": "/opt/ytschool", 
    "state": "link", 
    "uid": 0
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "dest": "/opt/tmp_school", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 13, 
    "src": "/opt/ytschool", 
    "state": "link", 
    "uid": 0
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "dest": "/opt/tmp_school", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 13, 
    "src": "/opt/ytschool", 
    "state": "link", 
    "uid": 0
}
[root@ansible .ssh]# ansible all -m file -a ‘src=/opt/ytschool path=/opt/tmp_school_ying state=hard‘
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "dest": "/opt/tmp_school_ying", 
    "gid": 99, 
    "group": "nobody", 
    "mode": "0600", 
    "owner": "ygcn", 
    "size": 0, 
    "src": "/opt/ytschool", 
    "state": "hard", 
    "uid": 500
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "dest": "/opt/tmp_school_ying", 
    "gid": 99, 
    "group": "nobody", 
    "mode": "0600", 
    "owner": "ygcn", 
    "size": 0, 
    "src": "/opt/ytschool", 
    "state": "hard", 
    "uid": 500
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "dest": "/opt/tmp_school_ying", 
    "gid": 99, 
    "group": "nobody", 
    "mode": "0600", 
    "owner": "ygcn", 
    "size": 0, 
    "src": "/opt/ytschool", 
    "state": "hard", 
    "uid": 500
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "dest": "/opt/tmp_school_ying", 
    "gid": 99, 
    "group": "nobody", 
    "mode": "0600", 
    "owner": "ygcn", 
    "size": 0, 
    "src": "/opt/ytschool", 
    "state": "hard", 
    "uid": 500
}

创建目录:ansible all -m file -a ‘path=/tmp/tyschool123 state=directory‘

[root@ansible .ssh]# ansible all -m file -a ‘path=/tmp/tyschool123 state=directory‘
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/tmp/tyschool123", 
    "size": 4096, 
    "state": "directory", 
    "uid": 0
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/tmp/tyschool123", 
    "size": 4096, 
    "state": "directory", 
    "uid": 0
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/tmp/tyschool123", 
    "size": 4096, 
    "state": "directory", 
    "uid": 0
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/tmp/tyschool123", 
    "size": 4096, 
    "state": "directory", 
    "uid": 0
}

修改目录及子文件权限:ansible all -m file -a ‘path=/tmp/tyschool123 mode=2755 owner=ygcn recurse=yes‘

[root@ansible .ssh]# ansible all -m file -a ‘path=/tmp/tyschool123 mode=2755 owner=ygcn recurse=yes‘ 192.168.31.102 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "02755", 
    "owner": "ygcn", 
    "path": "/tmp/tyschool123", 
    "size": 4096, 
    "state": "directory", 
    "uid": 500
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "02755", 
    "owner": "ygcn", 
    "path": "/tmp/tyschool123", 
    "size": 4096, 
    "state": "directory", 
    "uid": 500
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "02755", 
    "owner": "ygcn", 
    "path": "/tmp/tyschool123", 
    "size": 4096, 
    "state": "directory", 
    "uid": 500
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "02755", 
    "owner": "ygcn", 
    "path": "/tmp/tyschool123", 
    "size": 4096, 
    "state": "directory", 
    "uid": 500
}

删除一个目录[包括子文件全部删除]: ansible all -m file -a ‘path=/tmp/tyschool123 state=absent‘

[root@ansible .ssh]# ansible all -m file -a ‘path=/tmp/tyschool123 state=absent‘
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "path": "/tmp/tyschool123", 
    "state": "absent"
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "path": "/tmp/tyschool123", 
    "state": "absent"
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "path": "/tmp/tyschool123", 
    "state": "absent"
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "path": "/tmp/tyschool123", 
    "state": "absent"
}

??copy模块(重点)

copy模块用于对文件的远程拷贝操作(如把本地的文件拷贝远程的机器上)

参数

说明

src

文件源路径

dest

目标路径

content

往目标文件输入内容

force

强制 yes or no

backup

是否备份有冲突的源文件[文件名相同,内容不同] yes or no

checksum

拷?完整性校验,使用sha1sum生成校验码

owner

目标文件所有者

group

目标文件所属组

mode

目标文件权限

需求:拷贝31.101机器/root/os_init.sh文件到所有机器上

  1.要求娇艳完整性 注意[checksum 是根据sha1算法做校验的]

  2.所有者、所属组都是ygcn

  3.权限0400

计算os_init.sh的chechsum值

[root@ansible ~]# sha1sum os_init.sh 
a08951cd15d03bc5b5f4d19fca3d9107be34570a  os_init.sh

ansible all -m copy -a ‘src=/root/os_init.sh dest=/opt checksum="a08951cd15d03bc5b5f4d19fca3d9107be34570a" owner=ygcn group=ygcn mode=0400‘

[root@ansible ~]# ansible all -m copy -a ‘src=/root/os_init.sh dest=/opt checksum="a08951cd15d03bc5b5f4d19fca3d9107be34570a" owner=ygcn group=ygcn mode=0400‘
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 25, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571761618.02-247686853591230/source", 
    "state": "file", 
    "uid": 500
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 25, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571761617.97-121365959656855/source", 
    "state": "file", 
    "uid": 500
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 25, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571761617.99-38426809639146/source", 
    "state": "file", 
    "uid": 500
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 25, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571761618.04-15003391334498/source", 
    "state": "file", 
    "uid": 500
}

copy 模块拷贝时要注意拷贝目录后面是否带"/"符号

/etc/yum.repos.d后面不带/符号,则表示把/etc/yum.repos.d整个目录拷?到/tmp/目录下 

[root@manage01 ~]# ansible group1 -m copy -a ‘src=/etc/yum.repos.d dest=/tmp/‘ 

 

/etc/yum.repos.d/后面带/符号,则表示把/etc/yum.repos.d/目录里的所有文件拷?到/tmp/目录  

[root@manage01 ~]# ansible group1 -m copy -a ‘src=/etc/yum.repos.d/ dest=/tmp/‘

 

使用content参数直接往远程文件里写内容(会覆盖原内容)

命令:ansible all -m copy -a ‘content="baism\nhello word\n" dest=/tmp/xiaoqi‘

[root@ansible ~]# ansible all -m copy -a ‘content="baism\nhello word\n" dest=/tmp/xiaoqi‘
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "checksum": "f7cd12ede8f57da4a07cd3b6ea4ee6423191296f", 
    "dest": "/tmp/xiaoqi", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "13996fcf5862fc24a33a535c07425c09", 
    "mode": "0644", 
    "owner": "root", 
    "size": 17, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571762483.62-142731307928961/source", 
    "state": "file", 
    "uid": 0
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "checksum": "f7cd12ede8f57da4a07cd3b6ea4ee6423191296f", 
    "dest": "/tmp/xiaoqi", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "13996fcf5862fc24a33a535c07425c09", 
    "mode": "0644", 
    "owner": "root", 
    "size": 17, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571762483.6-23358853914686/source", 
    "state": "file", 
    "uid": 0
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "checksum": "f7cd12ede8f57da4a07cd3b6ea4ee6423191296f", 
    "dest": "/tmp/xiaoqi", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "13996fcf5862fc24a33a535c07425c09", 
    "mode": "0644", 
    "owner": "root", 
    "size": 17, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571762483.55-262472950495567/source", 
    "state": "file", 
    "uid": 0
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "checksum": "f7cd12ede8f57da4a07cd3b6ea4ee6423191296f", 
    "dest": "/tmp/xiaoqi", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "13996fcf5862fc24a33a535c07425c09", 
    "mode": "0644", 
    "owner": "root", 
    "size": 17, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571762483.59-252720846448780/source", 
    "state": "file", 
    "uid": 0
}

使用force参数控制是否强制覆盖

 ansible all -m copy -a ‘src=/root/os_init.sh dest=/opt/os_init.sh force=no‘  如果文件存在 则不覆盖

 ansible all -m copy -a ‘src=/root/anaconda-ks.cfg  dest=/opt/os_init.sh force=yes‘ 如果文件存在  强制覆盖原文件

[root@ansible ~]# ansible all -m copy -a ‘src=/root/os_init.sh dest=/opt/os_init.sh force=no‘ 
192.168.31.102 | SUCCESS => {
    "changed": false, 
    "dest": "/opt/os_init.sh", 
    "src": "/root/os_init.sh"
}
192.168.31.101 | SUCCESS => {
    "changed": false, 
    "dest": "/opt/os_init.sh", 
    "src": "/root/os_init.sh"
}
192.168.31.103 | SUCCESS => {
    "changed": false, 
    "dest": "/opt/os_init.sh", 
    "src": "/root/os_init.sh"
}
192.168.31.104 | SUCCESS => {
    "changed": false, 
    "dest": "/opt/os_init.sh", 
    "src": "/root/os_init.sh"
}
[root@ansible ~]# ansible all -m copy -a ‘src=/root/anaconda-ks.cfg  dest=/opt/os_init.sh force=yes‘ 
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "checksum": "915bf7dcdab20170ad3e84b0fdb5c6a6a44b2b02", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "d406672afee7d3ee8f1b1c6f1e476631", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 1141, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571762932.25-8685616463152/source", 
    "state": "file", 
    "uid": 500
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "checksum": "915bf7dcdab20170ad3e84b0fdb5c6a6a44b2b02", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "d406672afee7d3ee8f1b1c6f1e476631", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 1141, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571762932.22-227546680774041/source", 
    "state": "file", 
    "uid": 500
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "checksum": "915bf7dcdab20170ad3e84b0fdb5c6a6a44b2b02", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "d406672afee7d3ee8f1b1c6f1e476631", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 1141, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571762932.29-53132209654764/source", 
    "state": "file", 
    "uid": 500
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "checksum": "915bf7dcdab20170ad3e84b0fdb5c6a6a44b2b02", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "d406672afee7d3ee8f1b1c6f1e476631", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 1141, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571762932.21-73508510381906/source", 
    "state": "file", 
    "uid": 500
}

使用backup参数控制是否备份文件

ansible all -m copy -a ‘src=/root/os_init.sh dest=/opt/os_init.sh backup=yes‘

[root@ansible ~]# ansible all -m copy -a ‘src=/root/os_init.sh dest=/opt/os_init.sh backup=yes‘
192.168.31.101 | SUCCESS => {
    "backup_file": "/opt/os_init.sh.2987.2019-10-23@00:55:30~", 
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 25, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571763322.29-17697671205104/source", 
    "state": "file", 
    "uid": 500
}
192.168.31.103 | SUCCESS => {
    "backup_file": "/opt/os_init.sh.5759.2019-10-23@00:55:38~", 
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 25, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571763322.33-67682277495262/source", 
    "state": "file", 
    "uid": 500
}
192.168.31.104 | SUCCESS => {
    "backup_file": "/opt/os_init.sh.6015.2019-10-23@00:55:39~", 
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 25, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571763322.35-276842656771704/source", 
    "state": "file", 
    "uid": 500
}
192.168.31.102 | SUCCESS => {
    "backup_file": "/opt/os_init.sh.6075.2019-10-23@00:55:32~", 
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/os_init.sh", 
    "gid": 500, 
    "group": "ygcn", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "mode": "0400", 
    "owner": "ygcn", 
    "size": 25, 
    "src": "/root/.ansible/tmp/ansible-tmp-1571763322.3-1829570936631/source", 
    "state": "file", 
    "uid": 500
}

??fetch模块

fetch模块与copy模块类似,但作用相反。用于把远程机器的文件拷?到本地。 

 

将机器组的机器/opt/os_init.sh 拷?到ansible主机/opt目录 注意:不管是拷?多个机器还是一个机器的文件,在管理机本地目录都会按照IP/路径/文件名的方式命名,防止冲突 

ansible all -m fetch -a ‘src=/opt/os_init.sh dest=/opt‘

[root@ansible ~]# ansible all -m fetch -a ‘src=/opt/os_init.sh dest=/opt‘
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/192.168.31.101/opt/os_init.sh", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "remote_checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "remote_md5sum": null
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/192.168.31.103/opt/os_init.sh", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "remote_checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "remote_md5sum": null
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/192.168.31.104/opt/os_init.sh", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "remote_checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "remote_md5sum": null
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "dest": "/opt/192.168.31.102/opt/os_init.sh", 
    "md5sum": "1392e1e418ecc8d45d79334b49409f26", 
    "remote_checksum": "a08951cd15d03bc5b5f4d19fca3d9107be34570a", 
    "remote_md5sum": null
}

??user模块

user模块用于管理用户账号和用户组。

用户的管理:创建删除

常用参数
name=""    指定用户名
password=""  指定密码,必须是密文
state=    absent | present  删除|创建 
system=   yes|no    是否为系统用户
shell=""      指定登陆shell 
generate_ssh_key=   yes|no  是否创建秘钥对
uid=           指定用户的uid
create_home= yes|no 是否建立家目录
remove=   yes|no  删除家目录

 需求:

  1.创建一个用户postgres 密码123

  2.要求是系统用户

  3.非交互登陆

  4.生成自己的密钥对

[root@ansible ~]# echo 123|openssl passwd -1 -stdin     #先把明文的密码转换一下,生成md5密文

$1$Y9F5h6YT$2qVdZ4Hhpc8EFQvihAlm60

ansible all -m user -a ‘name=postgres password="$1$Y9F5h6YT$2qVdZ4Hhpc8EFQvihAlm60" shell=/sbin/nologin generate_ssh_key=yes‘

[root@ansible ~]# echo 123|openssl passwd -1 -stdin
$1$Y9F5h6YT$2qVdZ4Hhpc8EFQvihAlm60
[root@ansible ~]# ansible all -m user -a ‘name=postgres password="$1$Y9F5h6YT$2qVdZ4Hhpc8EFQvihAlm60" shell=/sbin/nologin generate_ssh_key=yes‘
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 501, 
    "home": "/home/postgres", 
    "name": "postgres", 
    "password": "NOT_LOGGING_PASSWORD", 
    "shell": "/sbin/nologin", 
    "ssh_fingerprint": "2048 8a:ce:cf:9c:7c:7b:a1:64:3b:13:5d:40:86:cd:9e:8e /home/postgres/.ssh/id_rsa.pub (RSA)", 
    "ssh_key_file": "/home/postgres/.ssh/id_rsa", 
    "ssh_public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA5aPShDf9OTpewm++qtbvEQQhUioaophmTqUzM/HGm3fpxDiae/iHt4zuNjD7VE4OIC7le29JSM/jsnl1tzGXi3Q09+Q7pa4MDqe7kncse8Rgig5Ltxb1q5B1ixtOh3UnC7SldW2NaQier8p6aG0Wk5JMXhqJCbaCcfHY/6U7QctNYl1lY+VOo69zfmh97xajPfKs3dUc0A61v1zJHH94z5FJNaZj3+nt0eko5d8IVR2T60meo0MYRRemw/16YBOef/LjwKQ2IPM+vsmeVAyydo5xIoa1G2csckJc1eJCE48PbEis0u+MF8C+eoej213XIzL7RGO0pStMoa1paKUhaQ== ansible-generated on node2", 
    "state": "present", 
    "system": false, 
    "uid": 501
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 501, 
    "home": "/home/postgres", 
    "name": "postgres", 
    "password": "NOT_LOGGING_PASSWORD", 
    "shell": "/sbin/nologin", 
    "ssh_fingerprint": "2048 96:11:77:ae:ad:29:d8:75:b8:21:83:09:7d:77:4f:1c /home/postgres/.ssh/id_rsa.pub (RSA)", 
    "ssh_key_file": "/home/postgres/.ssh/id_rsa", 
    "ssh_public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAtb1vGuOXf6EPTR7vynnzv8xmX6pG8HG15AIyRNf527BVxaNvekwg0jm/KEYJiT8CSoM5Ot7MvmTi6i2Sr13n7c8XO/46xZeIZrL1NP0E6sgyVYqmHsiG9KcoUEpBpAAY8CqQ1XPfP5PzD7UuSqdeSuM5XrVxHlaJ22Ebq7DFjfYMUeDEEQYqetXwIchYcBg+Rj640XBiJiJ24WtokLWLl+dr51G4AKuk3Wce+l+tew4QW8KdhGTM4md31qr4LswEI5UQE0rFm4JwXsuWIB6IqIXgkssAI4cI+yvf51l8LR+wwEVQ6cAASt70hU/ww1ebWSJWZL5epz7wu/Yo437z5Q== ansible-generated on node3", 
    "state": "present", 
    "system": false, 
    "uid": 501
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 501, 
    "home": "/home/postgres", 
    "name": "postgres", 
    "password": "NOT_LOGGING_PASSWORD", 
    "shell": "/sbin/nologin", 
    "ssh_fingerprint": "2048 aa:cc:de:21:a7:cf:a3:69:cb:1b:ca:f5:4d:c6:ea:ed /home/postgres/.ssh/id_rsa.pub (RSA)", 
    "ssh_key_file": "/home/postgres/.ssh/id_rsa", 
    "ssh_public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAtHQeWY0B96hL0DUZpmZmGG1+gIg/hFCRWilFpdLrND0FY3zQFuyNoRcAa55RO22/Hv7GDixvEsXg3SBH/sHJYXRkeM6IiLAMxJxo8C99yVjz+M6vjlwujqsbn+6yUSElqMesI3HrfekhXB0sBT2Cp9U/K5czzudZHAtO+TasdqonaS5SONXwzNwsatEP3N0Z/B90TtyTZFbEbYsyKsnZJYbccGbmJ5XBSo27w6Ydu5GP+hA/o+2D0dZRbLSlE+nfgljo23hw5SvtShheU/gd0eqoy/lFRDSyhyiqagV6w69dg8q88U+kiAg4nHfWzFVgcPYhC1ZJyZ/MXgE3ql6j0Q== ansible-generated on node1", 
    "state": "present", 
    "system": false, 
    "uid": 501
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 501, 
    "home": "/home/postgres", 
    "name": "postgres", 
    "password": "NOT_LOGGING_PASSWORD", 
    "shell": "/sbin/nologin", 
    "ssh_fingerprint": "2048 82:f3:56:64:70:4f:17:1d:5a:61:e9:d5:0c:ad:71:e5 /home/postgres/.ssh/id_rsa.pub (RSA)", 
    "ssh_key_file": "/home/postgres/.ssh/id_rsa", 
    "ssh_public_key": "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAywcUkk1+F4UIRQCSDHYcK5OktByBHzTb79FzGNHGhT6YYlPV+PpMTfShyOos8nl43IBcLdjVvuM63JqMbXUQOcImsUYtTp69nUMJtib2Q+SbIuUSHMbUzAQUUJrRWlPhqdqd9PfA5OvtE/79whGnNyK6HUg8kHrGBrezewzM+JDnPgEANzHqoMnD7gB4Vj5+t4UZ95vHB7UE3LsqTmwNRO6jS+L9RtJ1frAK8fPo/D1UrILj4l6iqZWoCA4n2skUvD+mM+Uf1uScInmfeCk+3e7AS26Dh9p6FbvCKlKmc/gVNn2Z0dEzNGGElU7FEZ3TOhN3jcaE8Yqyc4PvJLau4w== ansible-generated on node4", 
    "state": "present", 
    "system": false, 
    "uid": 501
}

删除目录

 ansible all -m user -a ‘name=postgres state=absent remove=yes‘

[root@ansible ~]# ansible all -m user -a ‘name=postgres state=absent remove=yes‘
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "force": false, 
    "name": "postgres", 
    "remove": true, 
    "state": "absent"
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "force": false, 
    "name": "postgres", 
    "remove": true, 
    "state": "absent"
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "force": false, 
    "name": "postgres", 
    "remove": true, 
    "state": "absent"
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "force": false, 
    "name": "postgres", 
    "remove": true, 
    "state": "absent"
}

??group模块

模块用于管理用户组和用户组属性。

组创建: ansible all -m group -a ‘name=admin gid=4444 state=present‘

[root@ansible ~]# ansible all -m group -a ‘name=admin gid=4444 state=present‘
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "gid": 4444, 
    "name": "admin", 
    "state": "present", 
    "system": false
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "gid": 4444, 
    "name": "admin", 
    "state": "present", 
    "system": false
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "gid": 4444, 
    "name": "admin", 
    "state": "present", 
    "system": false
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "gid": 4444, 
    "name": "admin", 
    "state": "present", 
    "system": false
}

删除组:ansible all -m group -a ‘name=admin state=absent‘

[root@ansible ~]# ansible all -m group -a ‘name=admin state=absent‘
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "name": "admin", 
    "state": "absent"
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "name": "admin", 
    "state": "absent"
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "name": "admin", 
    "state": "absent"
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "name": "admin", 
    "state": "absent"
} 

??cron模块

 cron模块用于管理周期性时间任务

创建一个cron任务,不指定user的话,默认就是root(我这里就是用root操作)如果minute、hour、day、month、week不指定的话,默认都为*

需求:每天12:23分执行echo “haha”

 ansible all -m cron -a ‘name=tes_cront user=root job="echo haha>/tmp/test" minute=23 hour=12‘ 

[root@ansible ~]# ansible all -m cron -a ‘name=tes_cront user=root job="echo haha>/tmp/test" minute=23 hour=12‘ 
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "tes_cront"
    ]
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "tes_cront"
    ]
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "tes_cront"
    ]
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "tes_cront"
    ]
}

删除cron任务: ansible all -m cron -a "name=tes_cront state=absent"

[root@ansible ~]# ansible all -m cron -a "name=tes_cront state=absent"
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}

??yum_repository模块

 yum_repository模块用于配置yum仓库

需求:增加一个/etc/yum.repo.d/dvd.repo配置文件

首先:用于上述shell模块挂载查看成功与否

[root@ansible ~]# ansible all -m shell -a " mount /dev/cdrom /mnt/"
 [WARNING]: Consider using the mount module rather than running mount.  If you need to use command
because mount is insufficient you can add warn=False to this command task or set
command_warnings=False in ansible.cfg to get rid of this message.

192.168.31.101 | SUCCESS | rc=0 >>
mount: block device /dev/sr0 is write-protected, mounting read-only

192.168.31.104 | SUCCESS | rc=0 >>
mount: block device /dev/sr0 is write-protected, mounting read-only

192.168.31.103 | SUCCESS | rc=0 >>
mount: block device /dev/sr0 is write-protected, mounting read-only

192.168.31.102 | SUCCESS | rc=0 >>
mount: block device /dev/sr0 is write-protected, mounting read-only

[root@ansible ~]# ansible all -m shell -a "df -h"                  
192.168.31.101 | SUCCESS | rc=0 >>
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root
                       18G  1.1G   16G   7% /
tmpfs                 491M     0  491M   0% /dev/shm
/dev/sda1             477M   33M  419M   8% /boot
/dev/sr0              3.7G  3.7G     0 100% /mnt

192.168.31.104 | SUCCESS | rc=0 >>
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root
                       18G  1.1G   16G   7% /
tmpfs                 491M     0  491M   0% /dev/shm
/dev/sda1             477M   33M  419M   8% /boot
/dev/sr0              3.7G  3.7G     0 100% /mnt

192.168.31.102 | SUCCESS | rc=0 >>
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root
                       18G  1.5G   15G  10% /
tmpfs                 491M     0  491M   0% /dev/shm
/dev/sda1             477M   33M  419M   8% /boot
/dev/sr0              3.7G  3.7G     0 100% /mnt

192.168.31.103 | SUCCESS | rc=0 >>
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root
                       18G  1.2G   16G   7% /
tmpfs                 491M     0  491M   0% /dev/shm
/dev/sda1             477M   33M  419M   8% /boot
/dev/sr0              3.7G  3.7G     0 100% /mnt

ansible all -m yum_repository -a ‘name=dvd description=BaseOS baseurl=file:///mnt gpgcheck=0 enabled=yes‘   # description 描述

[root@ansible ~]# ansible all -m yum_repository -a ‘name=dvd description=BaseOS baseurl=file:///mnt gpgcheck=0 enabled=yes‘         
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "repo": "dvd", 
    "state": "present"
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "repo": "dvd", 
    "state": "present"
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "repo": "dvd", 
    "state": "present"
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "repo": "dvd", 
    "state": "present"
}

删除yum源

ansible all -m yum_repository -a ‘name=dvd state=absent‘ 

[root@ansible ~]# ansible all -m yum_repository -a ‘name=dvd state=absent‘
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "repo": "dvd", 
    "state": "absent"
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "repo": "dvd", 
    "state": "absent"
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "repo": "dvd", 
    "state": "absent"
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "repo": "dvd", 
    "state": "absent"
}

??yum模块

 yum模块用于使用yum命令来实现软件包的安装与卸载

相关命令参数

name:     #需要安装软件包名称

list : installed   #列出已安装

     updates    #需要更新

     available   #可获得的

     repos      #yum源

state: absent      #删除

     removed      #删除

     installed    #安装确认

     present    安装确认

     latest    #安装最新版本

list:列出包信息

 ansible  all -m yum -a ‘list=repos‘

 

[root@ansible ~]# ansible  all -m yum -a ‘list=repos‘
192.168.31.101 | SUCCESS => {
    "changed": false, 
    "results": [
        {
            "repoid": "dvd", 
            "state": "enabled"
        }
    ]
}
192.168.31.104 | SUCCESS => {
    "changed": false, 
    "results": [
        {
            "repoid": "dvd", 
            "state": "enabled"
        }
    ]
}
192.168.31.103 | SUCCESS => {
    "changed": false, 
    "results": [
        {
            "repoid": "dvd", 
            "state": "enabled"
        }
    ]
}
192.168.31.102 | SUCCESS => {
    "changed": false, 
    "results": [
        {
            "repoid": "dvd", 
            "state": "enabled"
        }
    ]
}

使用yum安装一个软件(提前定义好yum源 所有node-节点)

ansible all -m yum -a "name=vsftpd"  #安装一个vsftpd服务

[root@ansible ~]# ansible all -m yum -a "name=vsftpd"
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nSetting up Install Process\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package vsftpd.x86_64 0:2.2.2-21.el6 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package          Arch             Version                  Repository     Size\n================================================================================\nInstalling:\n vsftpd           x86_64           2.2.2-21.el6             dvd           155 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 155 k\nInstalled size: 340 k\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\r  Verifying  : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\nInstalled:\n  vsftpd.x86_64 0:2.2.2-21.el6                                                  \n\nComplete!\n"
    ]
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nSetting up Install Process\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package vsftpd.x86_64 0:2.2.2-21.el6 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package          Arch             Version                  Repository     Size\n================================================================================\nInstalling:\n vsftpd           x86_64           2.2.2-21.el6             dvd           155 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 155 k\nInstalled size: 340 k\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\r  Verifying  : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\nInstalled:\n  vsftpd.x86_64 0:2.2.2-21.el6                                                  \n\nComplete!\n"
    ]
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nSetting up Install Process\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package vsftpd.x86_64 0:2.2.2-21.el6 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package          Arch             Version                  Repository     Size\n================================================================================\nInstalling:\n vsftpd           x86_64           2.2.2-21.el6             dvd           155 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 155 k\nInstalled size: 340 k\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\r  Verifying  : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\nInstalled:\n  vsftpd.x86_64 0:2.2.2-21.el6                                                  \n\nComplete!\n"
    ]
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nSetting up Install Process\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package vsftpd.x86_64 0:2.2.2-21.el6 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package          Arch             Version                  Repository     Size\n================================================================================\nInstalling:\n vsftpd           x86_64           2.2.2-21.el6             dvd           155 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 155 k\nInstalled size: 340 k\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\r  Verifying  : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\nInstalled:\n  vsftpd.x86_64 0:2.2.2-21.el6                                                  \n\nComplete!\n"
    ]
}

删除软件包

 ansible all -m yum -a ‘name=vsftpd state=absent‘

[root@ansible ~]# ansible all -m yum -a ‘name=vsftpd state=absent‘
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "已加载插件:fastestmirror\n设置移除进程\n解决依赖关系\n--> 执行事务检查\n---> Package vsftpd.x86_64 0:2.2.2-21.el6 will be 删除\n--> 完成依赖关系计算\n\n依赖关系解决\n\n================================================================================\n 软件包           架构             版本                    仓库            大小\n================================================================================\n正在删除:\n vsftpd           x86_64           2.2.2-21.el6            @dvd           340 k\n\n事务概要\n================================================================================\nRemove        1 Package(s)\n\nInstalled size: 340 k\n下载软件包:\n运行 rpm_check_debug \n执行事务测试\n事务测试成功\n执行事务\n\r  正在删除   : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\r  Verifying  : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\n删除:\n  vsftpd.x86_64 0:2.2.2-21.el6                                                  \n\n完毕!\n"
    ]
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "已加载插件:fastestmirror\n设置移除进程\n解决依赖关系\n--> 执行事务检查\n---> Package vsftpd.x86_64 0:2.2.2-21.el6 will be 删除\n--> 完成依赖关系计算\n\n依赖关系解决\n\n================================================================================\n 软件包           架构             版本                    仓库            大小\n================================================================================\n正在删除:\n vsftpd           x86_64           2.2.2-21.el6            @dvd           340 k\n\n事务概要\n================================================================================\nRemove        1 Package(s)\n\nInstalled size: 340 k\n下载软件包:\n运行 rpm_check_debug \n执行事务测试\n事务测试成功\n执行事务\n\r  正在删除   : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\r  Verifying  : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\n删除:\n  vsftpd.x86_64 0:2.2.2-21.el6                                                  \n\n完毕!\n"
    ]
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "已加载插件:fastestmirror\n设置移除进程\n解决依赖关系\n--> 执行事务检查\n---> Package vsftpd.x86_64 0:2.2.2-21.el6 will be 删除\n--> 完成依赖关系计算\n\n依赖关系解决\n\n================================================================================\n 软件包           架构             版本                    仓库            大小\n================================================================================\n正在删除:\n vsftpd           x86_64           2.2.2-21.el6            @dvd           340 k\n\n事务概要\n================================================================================\nRemove        1 Package(s)\n\nInstalled size: 340 k\n下载软件包:\n运行 rpm_check_debug \n执行事务测试\n事务测试成功\n执行事务\n\r  正在删除   : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\r  Verifying  : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\n删除:\n  vsftpd.x86_64 0:2.2.2-21.el6                                                  \n\n完毕!\n"
    ]
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "已加载插件:fastestmirror\n设置移除进程\n解决依赖关系\n--> 执行事务检查\n---> Package vsftpd.x86_64 0:2.2.2-21.el6 will be 删除\n--> 完成依赖关系计算\n\n依赖关系解决\n\n================================================================================\n 软件包           架构             版本                    仓库            大小\n================================================================================\n正在删除:\n vsftpd           x86_64           2.2.2-21.el6            @dvd           340 k\n\n事务概要\n================================================================================\nRemove        1 Package(s)\n\nInstalled size: 340 k\n下载软件包:\n运行 rpm_check_debug \n执行事务测试\n事务测试成功\n执行事务\n\r  正在删除   : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\r  Verifying  : vsftpd-2.2.2-21.el6.x86_64                                   1/1 \n\n删除:\n  vsftpd.x86_64 0:2.2.2-21.el6                                                  \n\n完毕!\n"
    ]
} 

??service模块

service模块用于控制服务的启动、关闭、开机自启动等。

常用参数:

name : 服务名称

state:reloaded 、restarted、started、stopped (运维没有不知道的把 不多描述)

enabled: yes|no  开机是否启动

开启ftp服务:ansible all -m service -a ‘name=vsftpd state=started enabled=yes‘

[root@ansible ~]# ansible all -m service -a ‘name=vsftpd state=started enabled=yes‘
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "enabled": true, 
    "name": "vsftpd", 
    "state": "started"
}
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "enabled": true, 
    "name": "vsftpd", 
    "state": "started"
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "enabled": true, 
    "name": "vsftpd", 
    "state": "started"
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "enabled": true, 
    "name": "vsftpd", 
    "state": "started"
}

关闭ftp服务: ansible all -m service -a ‘name=vsftpd state=stopped enabled=no‘

[root@ansible ~]# ansible all -m service -a ‘name=vsftpd state=stopped enabled=no‘
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "enabled": false, 
    "name": "vsftpd", 
    "state": "stopped"
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "enabled": false, 
    "name": "vsftpd", 
    "state": "stopped"
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "enabled": false, 
    "name": "vsftpd", 
    "state": "stopped"
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "enabled": false, 
    "name": "vsftpd", 
    "state": "stopped"
}

??script模块

  script模块用于在远程机器上执行本地脚本

 本地有个脚本如下

[root@ansible ~]# pwd
/root
[root@ansible ~]# cat os_init.sh 
#!/bin/bash

echo "haha" > /opt/haha.txt

 执行:ansible all -m script -a ‘/root/os_init.sh

[root@ansible ~]# ansible all -m script -a ‘/root/os_init.sh‘
192.168.31.103 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.31.103 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.31.103 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
192.168.31.101 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.31.101 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.31.101 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
192.168.31.104 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.31.104 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.31.104 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
192.168.31.102 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.31.102 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.31.102 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}

??command模块

  在远程主机执行命令,默认模块,可忽略-m选项

  1. ansible dbserver -m command -a ‘service crond start‘

  2. ansible webserver -m command -a ‘echo magedu |passwd --stdin ygcn‘ 不成功的 并没有修改成

[root@ansible ~]# ansible all -m command -a  "echo xiaoqi|passwd --stdin ygcn"
192.168.1.8 | SUCCESS | rc=0 >>
xiaoqi|passwd --stdin ygcn

192.168.1.6 | SUCCESS | rc=0 >>
xiaoqi|passwd --stdin ygcn

192.168.1.10 | SUCCESS | rc=0 >>
xiaoqi|passwd --stdin ygcn

  3.此命令不支持 $VARNAME < > | ; & 等 ,用shell模块实现

??shell模块(常用)

  和command相似,用shell执行命令

  1. ansible all -m shell -a "echo xiaoqi|passwd --stdin ygcn"

[root@ansible ~]# ansible all -m shell -a "echo xiaoqi|passwd --stdin ygcn"
192.168.1.10 | SUCCESS | rc=0 >>
更改用户 ygcn 的密码 。
passwd: 所有的身份验证令牌已经成功更新。

192.168.1.8 | SUCCESS | rc=0 >>
更改用户 ygcn 的密码 。
passwd: 所有的身份验证令牌已经成功更新。

192.168.1.6 | SUCCESS | rc=0 >>
更改用户 ygcn 的密码 。
passwd: 所有的身份验证令牌已经成功更新。

  2. 调用bash执行命令类似 cat /tmp/stanley.md |awk -F ‘|‘ ‘{print $1,$2}‘ &>/tmp/example.txt 这些复杂命令,即使使用shell也可能会失败,解决办法:写到脚本时,copy到远程,执行,在把需要的结果啦回执行命令的机器

??setup模块(扩展)

 setup模块用于收集远程主机的基本信息(如操作系统类型,主机名,ip,cpu信息,内存信息等)

参数 filter= ‘ansible_processor‘    

其它常?的过滤条件 

ansible_all_ipv4_addresses:显示ipv4的信息。 

ansible_devices:显示磁盘设备信息。

 ansible_distribution_major_version:显示是系统主版本。 

ansible_distribution_version:仅显示系统版本。 

ansible_machine:显示系统类型,例:32位,还是64位。 

ansible_lvm:显示lvm相关信息。 

ansible_memtotal_mb:显示系统总内存。 

ansible_memfree_mb:显示可用系统内存。 

ansible_memory_mb:详细显示内存情况。 

ansible_swaptotal_mb:显示总的swap内存。 

ansible_swapfree_mb:显示swap内存的可用内存。 

ansible_mounts:显示系统磁盘挂载情况。 

ansible_processor:显示cpu个数(具体显示每个cpu的型号)。 

ansible_processor_vcpus:显示cpu个数(只显示总的个数)。 

 

ansible all -m setup -a ‘filter=ansible_processor‘  #打印cpu信息的
[root@ansible ~]# ansible all -m setup -a ‘filter=ansible_processor‘ 
192.168.31.102 | SUCCESS => {
    "ansible_facts": {
        "ansible_processor": [
            "0", 
            "GenuineIntel", 
            "Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz"
        ]
    }, 
    "changed": false
}
192.168.31.103 | SUCCESS => {
    "ansible_facts": {
        "ansible_processor": [
            "0", 
            "GenuineIntel", 
            "Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz"
        ]
    }, 
    "changed": false
}
192.168.31.104 | SUCCESS => {
    "ansible_facts": {
        "ansible_processor": [
            "0", 
            "GenuineIntel", 
            "Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz"
        ]
    }, 
    "changed": false
}
192.168.31.101 | SUCCESS => {
    "ansible_facts": {
        "ansible_processor": [
            "0", 
            "GenuineIntel", 
            "Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz"
        ]
    }, 
    "changed": false
}

??stat模块(了解)

 stat模块类似linux的stat命令,用于获取文件的状态信息。

ansible all -m stat -a ‘path=/etc/fstab‘  

[root@ansible ~]# ansible all -m stat -a ‘path=/etc/fstab‘      
192.168.31.104 | SUCCESS => {
    "changed": false, 
    "stat": {
        "atime": 1570702486.1744049, 
        "attr_flags": "e", 
        "attributes": [
            "extents"
        ], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "b06f425f903a91d26c07bfe9a9dca7a080189da0", 
        "ctime": 1568824684.1169999, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": false, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 130824, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/plain", 
        "mode": "0644", 
        "mtime": 1568824511.8080001, 
        "nlink": 1, 
        "path": "/etc/fstab", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 779, 
        "uid": 0, 
        "version": "482864498", 
        "wgrp": false, 
        "woth": false, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": false, 
        "xoth": false, 
        "xusr": false
    }
}
192.168.31.102 | SUCCESS => {
    "changed": false, 
    "stat": {
        "atime": 1569235590.9143467, 
        "attr_flags": "e", 
        "attributes": [
            "extents"
        ], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "b06f425f903a91d26c07bfe9a9dca7a080189da0", 
        "ctime": 1568824684.1169999, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": false, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 130824, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/plain", 
        "mode": "0644", 
        "mtime": 1568824511.8080001, 
        "nlink": 1, 
        "path": "/etc/fstab", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 779, 
        "uid": 0, 
        "version": "482864498", 
        "wgrp": false, 
        "woth": false, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": false, 
        "xoth": false, 
        "xusr": false
    }
}
192.168.31.103 | SUCCESS => {
    "changed": false, 
    "stat": {
        "atime": 1569649326.9078345, 
        "attr_flags": "e", 
        "attributes": [
            "extents"
        ], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "b06f425f903a91d26c07bfe9a9dca7a080189da0", 
        "ctime": 1568824684.1169999, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": false, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 130824, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/plain", 
        "mode": "0644", 
        "mtime": 1568824511.8080001, 
        "nlink": 1, 
        "path": "/etc/fstab", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 779, 
        "uid": 0, 
        "version": "482864498", 
        "wgrp": false, 
        "woth": false, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": false, 
        "xoth": false, 
        "xusr": false
    }
}
192.168.31.101 | SUCCESS => {
    "changed": false, 
    "stat": {
        "atime": 1571747604.7209976, 
        "attr_flags": "e", 
        "attributes": [
            "extents"
        ], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "b06f425f903a91d26c07bfe9a9dca7a080189da0", 
        "ctime": 1568824684.1169999, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": false, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 130824, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/plain", 
        "mode": "0644", 
        "mtime": 1568824511.8080001, 
        "nlink": 1, 
        "path": "/etc/fstab", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 779, 
        "uid": 0, 
        "version": "482864498", 
        "wgrp": false, 
        "woth": false, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": false, 
        "xoth": false, 
        "xusr": false
    }
}

7、ansible playbook(剧本)

playbook(剧本):是ansible用于配置,部署,和管理被控节点的剧本

使用的格式为yaml格式 (saltstack、elk、docker等也会用到yaml格式)

我认为palybook格式的脚本 就是执行的操作按照ansible编程的语法,放入文件中执行。

  完全可以用shell脚本完成操作

      还可以ansible + shell 脚本 使用script模块

??YAML格式规则

1.文件的第一行以 “---” 开始,表明YMAL文件的开始

2.以#号开头为注视

3.列表中所有成员都开始于相同的缩进级别,并且使用一个“- ”作为开头 #此处注意 是一个杠+一个空格

4.一个字典是由一个简单的 键值对 组成 #键值对就是 键: 值 冒号后面也有空格

5.注意写这种文件 不要使用 tab键 都使用空格 (不然老刺激

??playbook实例

第一步:创建一个存放playbook的目录

  mkdir -p playbook/web

第二步:找一份httpd配置文件,并修改成自己想要需求

  [root@ansible web]# ll httpd.conf
  -rw-r--r-- 1 root root 34421 10月 23 11:57 httpd.conf

第三步:写一个palybook文件(后缀为.yml或者.yaml)

  root@ansible web]# ll apache.yaml 

  -rw-r--r-- 1 root root 464 10月 23 12:17 apache.yaml

实例如下:

*仔细看*

[root@ansible web]# cat apache.yaml 
---
- hosts: all    #机器组 我这里是全部
  remote_user: root  #那个用户执行
  vars:         #定义变量
    - user: tyschool    #定义变量名字name=tyschool
  tasks:
    - name: create user user variable  #描述
    #ansible all -m user -a "user=tyschool state=present" 与下面那条一样 user: user=tyschool state=present
#user: user= {{user}} state=present 这是一种加入变量的方法

- name: install http server #描述
    #ansible all -m yum -a "name=http state=latest(最新的)"
      yum: name=httpd state=latest name=httpd-manual state=latest

    - name: copy httpd.conf to all server:/etc/httpd/conf #描述
      copy: src=/etc/ansible/playbook/web/httpd.conf dest=/etc/httpd/conf

    - name: start httpd #描述
      service: name=httpd state=started enabled=yes 

??playbook常见语法

hosts:用于指定要执行任务的主机,其可以是一个或多个由冒号分隔主机组。

remote_user:用于指定主机上的执行任务的用户

tasks:任务列表,按顺序执行任务 (如果host执行tasks失败,整个tasks都会回滚,修正playbook中的错误,然后重新执行即可。)

handlers:类似task 但是需要使用notify通知调用,实现按需调用。

  (不管有多少个通知者进行了notify,等到play中的所有task执行完成之后,handlers也只会被执行一次 ) 

  (heandlers最佳的应用场景使用来重启服务,或者接触系统重启操作,除此以外很少用了)

注意:handlers 需要notify调用,他和tasks不同的是 tasks每次都会调用,handlers触发才会调用,比如配置文件修改了,在执行playbook的时候,就会将管理机上的新改的copy到被管理机,那么就会触发handlers重启服务,否则不会执行handlers

with_items: 迭代列表:其使用格式为将需要迭代的内容定义为item变量饮用,并通过with_items语句指明迭代的元素列表即可

实例如下

[root@ansible web]# cat apache.yaml     
---
- hosts: all
  remote_user: root
  vars: 
    - user: tyschool123
  tasks:
    - name: create user user variable
      user: user={{user}} state=present

    - name: install http server
      #yum: name=httpd state=latest name=httpd-manual state=latest
      yum: name={{item}} state=latest  #变量
      with_items:    #循环 三个软件包名称带入上边的变量
      - httpd
      - httpd-devel
      - httpd-manual

    - name: copy httpd.conf to all server:/etc/httpd/conf
      copy: src=/etc/ansible/playbook/web/httpd.conf dest=/etc/httpd/conf
      notify:  #触发 如果上边的文件传过去了 那么就触发 文件修改才会被传过去
        - restat httpd service   #handlers name写什么这里写什么

    - name: start httpd
      service: name=httpd state=started enabled=yes


  handlers:  #定义触发做的动作
    - name: restat httpd service  #描述
      service: name=httpd state=restarted    

 如果有警告 WARNING 并且伴有 deprecation_warnings=False 关键参数 可修改配置文件 ansible.cfg 将参数修改成False即可

8、roles(难点)

roles(?色): 就是通过分别将variables, tasks及handlers等放置于单独的目录中,并可以便捷地调用它们 的一种机制。

假设我们要写一个playbook来安装管理lamp环境,那么这个playbook就会写很?。
所以我们希望把这 个很大的文件分成多个功能拆分, 分成apache管理,php管理,mysql管理,然后在需要使用的时候直接调 用就可以了,以免重复写。就类似编程里的模块化的概念,以达到代码复用的效果。

??创建roles的目录结构

files: 用来存放由copy模块或script模块调用的文件。
tasks: 至少有一个main.yml文件,定义各tasks。
handlers: 有一个main.yml文件,定义各handlers。
templates: 用来存放jinjia2模板。
vars: 有一个main.yml文件,定义变量。
meta: 有一个main.yml文件,定义此?色的特殊设定及其依赖关系。

注意: 在每个?色的目录中分别创建files, tasks,handlers,templates,vars和meta目录,用不到的目录可 以创建为空目录.

??案例:

  通过roles实现lamp

  分析:需要订制三个角色分别为:httpd,mysql,php 

      创建roles目录及文件,并确认目录结构

[root@manage01 ansible]# mkdir -p roles/{httpd,mysql,php}/{files,tasks,handlers,templates,vars,meta}
[root@manage01 ansible]# touch roles/{httpd,mysql,php}/{tasks,handlers,vars,meta}/main.yml
[root@manage01 ansible]# tree roles/ 
# 安装以上命令创建即可

?? 准备httpd服务器的主?文件,php测试?和配置文件等 #如下

[root@manage01 files]# ls
httpd.conf  phpinfo.php

??编写httpd?色的main.yml文件

[root@manage01 roles]# cat httpd/tasks/main.yml
- name: httpd httpd-devel httpd-manual软件包安装
  yum: name={{item}} state=latest
  with_items:
    - httpd
    - httpd-devel
    - httpd-manual
- name: 创建apache管理用户 www
  user: name={{user}} state=present
- name: 设置apache开机启动,并启动服务
  service: name=httpd enabled=yes state=started
- name: 拷?配置文件,初始化业务
  copy: src=/etc/ansible/roles/httpd/files/httpd.conf dest=/etc/httpd/conf/httpd.conf
#定义通知调用,当配置文件更新,需要重启服务 notify:
- restart apache - name: 拷?php测试?面
  copy: src=/etc/ansible/roles/httpd/files/phpinfo.php dest=/var/www/html/
[root@manage01 roles]# cat httpd/vars/main.yml user: www
[root@manage01 roles]# cat httpd/handlers/main.yml - name: restart apache service: name=httpd state=restarted

??编写mysql角色的main.yaml文件

 [root@manage01 ansible]# ls roles/php/files/
www.conf
[root@manage01 roles]# cat mysql/tasks/main.yml
- name: mysql 用户创建
  user: name={{user}} state=present
- name: mysql 软件安装
  yum: name={{item}} state=latest with_items:
    - mariadb
    - mariadb-server
- name: 启动服务,并设置开机启动
  service: name=mariadb enabled=yes state=started
- name: 改变mysql文件的所有者为mysql
  file: path=‘/usr/lib/mysql‘ owner={{user}} group={{user}} recurse=yes

[root@manage01 roles]# cat mysql/vars/main.yml
user: mysql

??编写php角色的main.yaml文件

 
[root@manage01 ansible]# cat roles/php/tasks/main.yml 
- name: 安装php yum: name={{item}} state=latest with_items: - php - php-mysqlnd - php-gd - php-ldap - php-odbc - php-pear - php-xml - php-xmlrpc - php-mbstring - php-snmp - php-soap - curl - curl-devel - php-bcmath - php-fpm - name: copy www.conf to /etc/php-fpm.d copy: src=/etc/ansible/roles/php/files/www.conf dest=/etc/php-fpm.d force=yes notify: - restart php-fpm [root@manage01 ansible]# cat roles/php/handlers/main.yml - name: restart php-fpm service: name=php-fpm state=restarted

??编写lamp的playbook文件调用前面定义好的三个?色

 [root@manage01 yaml]# cat lamp.yml
---
- hosts: group1
  remote_user: root
  roles:
  - httpd
  - mysql
  - php
 
测试业务机器

*此文章编写参考白树明老师资料编写如老师看到此文章请谅解* 

ansible基础-模块-playbook-roles角色

标签:hal   其他   type   ansible   nts   返回结果   role   srv   attr   

原文地址:https://www.cnblogs.com/goonxiaoqi/p/11598290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!