3.ansible使用和模块化深入解析

1.主配置文件介绍

ansible配置文件 /etc/ansible/ansible.cfg(一般保持默认)
[defaults]  #默认值
#inventory      = /etc/ansible/hosts  #主机列表配置文件
#library        = /usr/share/my_modules/  #库文件存放目录
#module_utils   = /usr/share/my_module_utils/
#remote_tmp     = ~/.ansible/tmp   #在被控制上执行 并删除
#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   #每次执行ansible命令是否询问ssh密码
#ask_pass      = True
#transport      = smart
#remote_port    = 22   #远程主机默认端口号
#module_lang    = C
#module_set_locale = False  
#host_key_checking = False #检查对应服务器的host_key,建议取消注释   这个如果不取消就会出现 2情况
#log_path=/var/log/ansible.log #日志文件 (取消注释,建议开启)

2.没有建立连接 所以无法ping 通

[root@ansible ~]# cd .ssh/
[root@ansible .ssh]# ls
known_hosts   #这是信任文件  我们ssh之后就出产生记录  才能ping  要不然注释下面的默认值  
[root@ansible .ssh]# rm -rf known_hosts

[root@ansible .ssh]# ansible all -m ping -k
SSH password:
10.0.0.48 | FAILED! => {
    "msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host's fingerprint to your known_hosts file to manage this host."
}
10.0.0.49 | FAILED! => {
    "msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host's fingerprint to your known_hosts file to manage this host."
}

所有的主机都要手动ssh连接一遍才行 
所以
#host_key_checking = False #检查对应服务器的host_key,建议取消注释


#注释后
[root@ansible .ssh]# ansible all -m ping -k
SSH password:
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

3.ansible系列命令

[root@ansible ~]# ansible  # tab
ansible               ansible-console       ansible-doc-2.7       ansible-playbook      ansible-pull-2.7
ansible-2             ansible-console-2     ansible-galaxy        ansible-playbook-2    ansible-test
ansible-2.7           ansible-console-2.7   ansible-galaxy-2      ansible-playbook-2.7  ansible-vault
ansible-config        ansible-doc           ansible-galaxy-2.7    ansible-pull          ansible-vault-2
ansible-connection    ansible-doc-2         ansible-inventory     ansible-pull-2        ansible-vault-2.7


Ansible系列命令
ansible ansible-doc ansible-playbookansible-vault
ansible-consoleansible-galaxyansible-pull
ansible-doc:显示模块帮助
ansible-doc [options][module...]
显示所有模块的文档
-a
-l,--list列出可用模块
-s, --snippet显示指定模块的playbook片段
示例:
ansible-docl列出所有模块
ansible-doc ping查看指定模块帮助用法
ansible-doc -s ping查看指定模块帮助用法

[root@ansible ~]# ansible doc ping  #加上模块名 查看怎么使用
usage: ansible [-h] [--version] [-v] [-b] [--become-method BECOME_METHOD]
               [--become-user BECOME_USER] [-K] [-i INVENTORY] [--list-hosts]
               [-l SUBSET] [-P POLL_INTERVAL] [-B SECONDS] [-o] [-t TREE] [-k]
               [--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER]
               [-c CONNECTION] [-T TIMEOUT]
               [--ssh-common-args SSH_COMMON_ARGS]
               [--sftp-extra-args SFTP_EXTRA_ARGS]
               [--scp-extra-args SCP_EXTRA_ARGS]
               [--ssh-extra-args SSH_EXTRA_ARGS] [-C] [--syntax-check] [-D]
               [-e EXTRA_VARS] [--vault-id VAULT_IDS]
               [--ask-vault-pass | --vault-password-file VAULT_PASSWORD_FILES]
               [-f FORKS] [-M MODULE_PATH] [--playbook-dir BASEDIR]
               [-a MODULE_ARGS] [-m MODULE_NAME]
               pattern
ansible: error: unrecognized arguments: ping

#统计ansible模块数量
[root@ansible ~]# ansible-doc -l | wc -l
3387

[root@ansible ~]# ansible-doc -s ping
- 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.

ansible通过ssh实现配置管理、应用部署、任务执行等功能,建议配置ansible
端能基子密钥认证的方式联系各被管理节点
ansible –version显示版本
-m module指定模块,默认为command
-v详细过程→vv -vv更详细

–list-hosts显示主机列表,可简写—list

[root@ansible ~]# ansible all --list-hosts
  hosts (2):
    10.0.0.48
    10.0.0.49

-k,–ask-pass提示输入ssh连接密码,默认Key验证
-K,–ask-become-pass提示输入sudo时的口令
-C,–check检查,并不执行
-T,–timeout=TIMEOUT 执行命令的超时时间,默认10s
-u,–user=REMOTE_USER执行远程执行的用户

[root@ansible ~]# ansible webserver -m ping -u y -k
SSH password:
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

[root@ansible ~]# ansible webserver -u y -k -m command -a'ls /root'
SSH password:
10.0.0.48 | FAILED | rc=2 >>
ls: cannot open directory /root: Permission deniednon-zero return code
#做不了权限以外的事

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

实战

1.生成密钥

[root@ansible ansible]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:jd0oYIQ0Ms/MYd5V3mV3W3DEr4xfOHbP2dCV3ZIATv0 root@ansible
The key's randomart image is:
+---[RSA 2048]----+
|  o.=.. ..+o  ++*|
|   X.= . + .oo o=|
|    * +   o .o o=|
|     . . + o  E.=|
|        S + .o =.|
|         .  . B +|
|             o *+|
|              ..+|
|                 |
+----[SHA256]-----+

2.拷贝到目标主机

[root@ansible ansible]# ssh-copy-id 10.0.0.48
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '10.0.0.48'"
and check to make sure that only the key(s) you wanted were added.
[root@ansible ansible]# ssh-copy-id 10.0.0.49
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '10.0.0.49'"
and check to make sure that only the key(s) you wanted were added.

3.ansible的Host-pattern

3.1 all

ansible all -m ping

表示所有Inventory中的所有主机

[root@ansible ansible]# ansible all -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
[root@ansible ansible]#

3.2支持分组

ansible webserver -m ping

[root@ansible ansible]# ansible webserver -m ping
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
[root@ansible ansible]# ansible dbserver -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

3.3 * :通配符

ansible *server -m ping
[root@ansible ansible]# ansible *server -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
ansible “10.0.0.*” -m ping
[root@ansible ansible]# ansible "10.0.0.*" -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
ansible “*” -m ping
[root@ansible ansible]# ansible "*" -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

3.4 关系

: 逻辑或

[root@ansible ansible]# ansible webserver:dbserver -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

:& 逻辑与

#必须是两个分组里有相同的主机 才可以使用
ansible 'webserver:&dbserver' -m ping

:!逻辑非

#使用单引号
ansible 'webserver:!dbserver' -m ping

综合逻辑

#既在webserver和dbserver里面并且在appserver里面 不在ftpserver里面
ansible 'webserver:dbserver:&appservers:!ftpserver' -m ping

3.5正则表达式

ansible "webserver:&dbserver" -m ping
ansible "~(web|db).*\.magedu\.com" -m ping
~ :表示主机里面是web|db开头的
. 结尾包含的magedu
[root@ansible ansible]# ansible '~(web|db)' -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}



[root@ansible ansible]# ansible '~(web|db)server' -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

4.ansible命令执行的过程

ansible命令执行过程

  1. 加载自己的配置文件默认/etc/ansible/ansible.cfg
  2. 加载自己对应的模块文件,如command
  3. 通过ansible将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器
    的对应执行用户$HOME/.ansible/tmp/ansible-tmp-数字/xxX.PY文件
  4. 给文件+x执行
  5. 执行并返回结果
  6. 删除临时py文件,sleep o退出

执行状态︰

  • 绿色∶执行成功并且不需要做改变的操作
  • 黄色︰执行成功并且对目标主机做变更
  • 红色:执行失败

查看详细的执行命令

 ansible all -m ping -vvv

5.ansible使用示例

#以wang用户执行ping存活检测
ansible all -m ping-u wang -k

#以wang sudo至root执行ping存活检测
ansible all -m ping -u wang-b-k

#以wang sudo至mage用户执行ping存活检测
ansible all -m|ping-u wang -b-k --become-user mage

#以wang sudo至root用户执行ls
ansible all -m command -u wang --become-user=root -a 'ls /root' -b -k -K

6.ansible常见模块

1.简介

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

```bash
ansible srvs -m command -a 'service vsftpd start'
ansible srvs-m command -a 'echo magedu |passwd --stdin wang’不成功
>此命令不支持$VARNAME< > |;&等,用shell模块实现
  • Shell :和command相似,用shell执行命令
ansible srv-m shell -a 'echo magedu |passwd -stdin wang'
调用bash执行命令类似cat/tmp/stanley.md | awk -F'I'‘iprint $1,$2y&>
/tmp/example.txt这些复杂命令,即使使用shell也可能会失败,解决办法∶写到脚本
时,copy到远程,执行,再把需要的结果拉回执行命令的机器
  • Script:运行脚本
-a "/PATH/TO/SCRIPT_FILE“
snsible websrvs -m script -a f1.sh
  • Copy:从服务器复制文件到客户端
ansible all -m copy -a "src=/root/f1.sh dest=/tmp/f2.sh owner=wang mode=600 backup=yes"
如果目标存在,默认覆盖,此处指定先备份
ansible all -m copy -a "content='test content\n' dest=/tmp/f1.txt" 利用内容,直接生成目标文件
  • Fetch:从客户端取文件至服务器端,copy相反,目标可先tar
ansible all -m fetch -a 'src=/root/a.sh dest=/data/scripts'

File: 设置文件属性

ansible all -m file -a "path=/root/a.sh owner=wang mode=755"
ansible web -m file -a 'src=/app/testfile dest=/app/testfile-link state=link'

2.示例

1.默认command模块

1.条件判断
removes    如果存在 执行
creates    如果不存在 执行
#如果存在/etc/fs 文件 则执行cat
ansible all -a 'removes=/etc/fs cat /etc/fstab'

#如果不存在 所以要执行
ansible all -a 'creates=/etc/fs cat /etc/fstab'
2.切换目录
 ansible all -a 'chdir=/boot ls'
3.创建用户
[root@ansible ansible]# ansible 10.0.0.48 -a 'useradd test1'
10.0.0.48 | CHANGED | rc=0 >>

[root@ansible ansible]# ansible 10.0.0.48 -a 'getent passwd test1'
10.0.0.48 | CHANGED | rc=0 >>
test1:x:1002:1002::/home/test1:/bin/bash
4.command对特殊符号有bug

建议用shell模块

[root@ansible ansible]# ansible 10.0.0.48 -a 'echo magedu|passwd --stdin test1'
10.0.0.48 | CHANGED | rc=0 >>
magedu|passwd --stdin test1
[root@ansible ansible]# ansible 10.0.0.48 -a 'getent shadow test1'
10.0.0.48 | CHANGED | rc=0 >>
test1:!!:18488:0:99999:7:::   #!! 提示为空
[root@ansible ansible]# ansible 10.0.0.48 -a 'echo $HOSTNAME'
10.0.0.48 | CHANGED | rc=0 >>
$HOSTNAME   #直接打印了$HOSTNAME

2.shell模块

shell 比command强
[root@ansible ansible]# ansible 10.0.0.48 -m shell -a 'echo $HOSTNAME'
10.0.0.48 | CHANGED | rc=0 >>
c7-48    #输出成功

#修改密码 也是成功的
[root@ansible ansible]# ansible 10.0.0.48 -m shell -a "echo magedu|passwd --stdin test1"
10.0.0.48 | CHANGED | rc=0 >>
Changing password for user test1.
passwd: all authentication tokens updated successfully.
[root@ansible ansible]# ansible 10.0.0.48 -m shell -a "getent shadow test1"       10.0.0.48 | CHANGED | rc=0 >>
test1:$6$2zu5Lawc$5UgDQI8CR7cImwOu.AcTzM9pnM4UjW.svTM9mY3h3HI4nX4ECMEnoVzzwY0kWPaYVRRLL1p/FFzQQEsvaD.hU/:18488:0:99999:7:::

script模块

## 在本地新建一个脚本
[root@ansible ansible]# vim host.sh 
#!/bin/bash
hostname
[root@ansible ansible]# chmod +X host.sh
[root@ansible ansible]# pwd
/etc/ansible
使用script的模块能使远程主机执行本地脚本

[root@ansible ansible]# ansible all -m script -a "/etc/ansible/host.sh"
10.0.0.48 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 10.0.0.48 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 10.0.0.48 closed."
    ],
    "stdout": "c7-48\r\n",
    "stdout_lines": [
        "c7-48"
    ]
}
10.0.0.49 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 10.0.0.49 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 10.0.0.49 closed."
    ],
    "stdout": "c7-49\r\n",  #标准输出
    "stdout_lines": [
        "c7-49"
    ]
}

copy模块

查找copy选项
ansible-doc -s copy 
  • 将文件复制到目标主机
ansible all -m copy -a 'src=/root/ansible/selinux dest=/etc/selinux/config backup=yes'

ansible all -a 'cat /etc/selinux/config' #验证
ansible all -a 'ls /etc/selinux'  #查看复制文件
ansible all -m shell -a 'rm -f /etc/selinux/config.*'  #删除复制的文件

ansible all -m shell -a 'reboot'
#更改为selinux后需要重启生效
ansible all -m shell -a 'getenforce' #验证

#复制完更改权限
ansible all -m copy -a 'src=/etc/shadow dest=/data/ mode=000 owner=wang'
ansible all -a 'ls -l /data/'  #查看

#编辑文件发送到目标主机
ansible all -m copy -a 'content="hello\nthanks\n" dest=/data/f2'
ansible all -m ping -a 'cat /data/f2'
#content里面是文件内容

src是本机源文件
dest是目标文件
backup=yes 是在推送是进行复制 保留源文件
mode= 权限可以设置
owner= 所有者也可以设置
ansible all -a ‘cat /etc/selinux/config’

你可能感兴趣的:(ansible,运维)