自动化运维工具--ansible

作用:ansible是一款强大的配置管理工具,可以对成百上千台服务器进行管理,ansible可以理解为一个管理员,基于SSH协议对多台服务器进行指令下

发实现多台服务器的批量操作,一次下发一条命令(ansible ad-hoc模式)的方式来控制服务器,也可以将多条命令写在纸上(ansible playbook模式)让服

务器按照你写好指令工作,也可以通过管理配置实现多台服务器同一时间做不通的事情。上述这些操作都可以基于ansible来实现,前提是ansible可以通

过SSH协议远程服务器

安装:

Centos或者redhat可以通过yum安装

yum -y install ansible

配置:正常情况下默认配置即可满足

规划:

自动化运维工具--ansible

配置文件详解:/etc/ansible/ansible.cfg

inventory=/etc/ansible/hosts  表示主机清单inventory文件的位置

forks=5    并发连接数默认为5

sudo_user=root  默认执行命令的用户

remote_port=22     指定连接被管理节点的管理端口,默认是22端口,建议修改成其它的端口,能够更安全

host_key_checking = False  设置是否检查SSH主机的秘钥,值为True/False。关闭后第一次连接不会提示配置实例

timeout=60  设置SSH连接的超时时间,单位为秒

log_path = /var/log/ansible.log  指定一个存储ansible的文件

配置文件参考:

[defaults]          #通用默认配置
inventory      = /etc/ansible/hosts     #被控制端IP或者DNS列表
library        = /usr/share/my_modules/     ##默认搜寻模块的位置
remote_tmp     = ~/.ansible/tmp            #远程执行临时文件
local_tmp      = ~/.ansible/tmp
plugin_filters_cfg = /etc/ansible/plugin_filters.yml
forks          = 5      ##并行线程数
poll_interval  = 15     ##回频率或轮询间隔时间
sudo_user      = root       ##sudo远程执行用户名
ask_sudo_pass = True        ##使用sudo,是否需要输入密码
ask_pass      = True        ##是否需要输入密码
transport      = smart      ##通信机制
remote_port    = 22         ##远程SSH端口
module_lang    = C          ##模块和系统之间通信的语言
module_set_locale = False
gathering = implicit        ##控制默认facts收集(远程系统变量)
gather_subset = all
gather_timeout = 10
roles_path    = /etc/ansible/roles      ##使用playbook搜索Ansible roles
host_key_checking = False       ##是否检查远程主机密钥
sudo_exe = sudo         ##sudo远程执行命令
sudo_flags = -H -S -n       ##传递sudo之外的参数
timeout = 10            ##SSH超时时间
remote_user = root      ##远程登录用户名
log_path = /var/log/ansible.log     ##日志文件存放路径
module_name = command       ##Ansible命令默认执行的模块
executable = /bin/sh        ##执行的shell环境,用户shell模块
hash_behaviour = replace    ##特定的优先级覆盖变量
jinja2_extensions = jinja2.ext.do,jinja2.ext.i18    ##允许开启jinja2扩展模块
private_key_file = /path/to/file    ##私钥文件存储位置
display_skipped_hosts = True        ##显示跳过任何任务的状态
system_warnings = True      ##禁用系统运行Ansible潜在问题警告
deprecation_warnings = True     ##PlayBook输出禁用“不建议使用”警告
command_warnings = False    ##command模块Ansible默认发出警告
nocolor = 1         ##输出带上颜色区别,0表示开启,1表示关闭
pipelining = False      ##开启pipe SSH通道优化

[accelerate]        ##accelerate缓存加速
accelerate_port = 5099      ##加速连接端口5099
accelerate_timeout = 30     ##命令执行超过时间,单位为s
accelerate_connect_timeout = 5.0    ##上一个活动连接的时间,单位为min
accelerate_daemon_timeout = 30      ##允许多个私钥被加载到daemon
accelerate_multi_key = yes      ##任何客户端想要连接daemon都要开启这个选项
————————————————
版权声明:本文为CSDN博主「皛皛」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lcl_xiaowugui/article/details/81908445

inventory文件编辑:  

ansible_connection   与主机的连接类型,比如local,ssh或者paramiko ansible1.2以前默认使用

ansible_ssh_host  如果要远程的主机名与你设置的主机的别名不通,就可以通过该变量设置

ansible_ssh_port  如果不是默认是22端口,可以通过该变量设置

ansible_ssh_user  默认的ssh用户名

ansible_ssh_pass  远程主机的远程密码,该方式不安全,建议使用--ask-sudo-pass或者ssh密钥的方式连接

ansible_sudo_pass  输入sudo所需的密码,即被连接主机的普通账号密码,建议使用--ask-sudo-pass(手动输入密码验证的方式,相对安全)

ansible_sudo_exe  sudo命令路径,适用于1.8及以上版本

ansible_ssh_private_key_file  ssh使用的私钥文件,适用于有多个密钥

ansible_python_interpreter  目标主机python的路径,主要用于多python版本来指定用哪个python版本

举例说明

[test]
172.16.204.134  ansible_connection=ssh  ansible_ssh_user=root  ansible_ssh_port=2222  ansible_ssh_pass="mimashi123"

ansible ad-hoc模式(使用ansible命令来控制inventory中的主机列表)

查看ansible命令参数  ansible -h

[ ansible]# ansible -h
Usage: ansible <host-pattern> [options]

Define and run a single task ‘playbook‘ against a set of hosts

Options:
  -a MODULE_ARGS, --args=MODULE_ARGS
                        module arguments
  --ask-vault-pass      ask for vault password
  -B SECONDS, --background=SECONDS
                        run asynchronously, failing after X seconds
                        (default=N/A)
  -C, --check           don‘t make any changes; instead, try to predict some
                        of the changes that may occur
  -D, --diff            when changing (small) files and templates, show the
                        differences in those files; works great with --check
  -e EXTRA_VARS, --extra-vars=EXTRA_VARS
                        set additional variables as key=value or YAML/JSON, if
                        filename prepend with @
  -f FORKS, --forks=FORKS
                        specify number of parallel processes to use
                        (default=5)
  -h, --help            show this help message and exit
  -i INVENTORY, --inventory=INVENTORY, --inventory-file=INVENTORY
                        specify inventory host path or comma separated host
                        list. --inventory-file is deprecated
  -l SUBSET, --limit=SUBSET
                        further limit selected hosts to an additional pattern
  --list-hosts          outputs a list of matching hosts; does not execute
                        anything else
  -m MODULE_NAME, --module-name=MODULE_NAME
                        module name to execute (default=command)
  -M MODULE_PATH, --module-path=MODULE_PATH
                        prepend colon-separated path(s) to module library
                        (default=[u‘/root/.ansible/plugins/modules‘,
                        u‘/usr/share/ansible/plugins/modules‘])
  --new-vault-id=NEW_VAULT_ID
                        the new vault identity to use for rekey
  --new-vault-password-file=NEW_VAULT_PASSWORD_FILES
                        new vault password file for rekey
  -o, --one-line        condense output
  -P POLL_INTERVAL, --poll=POLL_INTERVAL
                        set the poll interval if using -B (default=15)
  --syntax-check        perform a syntax check on the playbook, but do not
                        execute it
  -t TREE, --tree=TREE  log output to this directory
  --vault-id=VAULT_IDS  the vault identity to use
  --vault-password-file=VAULT_PASSWORD_FILES
                        vault password file
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)
  --version             show program‘s version number and exit

  Connection Options:
    control as whom and how to connect to hosts

    -k, --ask-pass      ask for connection password
    --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE
                        use this file to authenticate the connection
    -u REMOTE_USER, --user=REMOTE_USER
                        connect as this user (default=None)
    -c CONNECTION, --connection=CONNECTION
                        connection type to use (default=smart)
    -T TIMEOUT, --timeout=TIMEOUT
                        override the connection timeout in seconds
                        (default=10)
    --ssh-common-args=SSH_COMMON_ARGS
                        specify common arguments to pass to sftp/scp/ssh (e.g.
                        ProxyCommand)
    --sftp-extra-args=SFTP_EXTRA_ARGS
                        specify extra arguments to pass to sftp only (e.g. -f,
                        -l)
    --scp-extra-args=SCP_EXTRA_ARGS
                        specify extra arguments to pass to scp only (e.g. -l)
    --ssh-extra-args=SSH_EXTRA_ARGS
                        specify extra arguments to pass to ssh only (e.g. -R)

  Privilege Escalation Options:
    control how and which user you become as on target hosts

    -s, --sudo          run operations with sudo (nopasswd) (deprecated, use
                        become)
    -U SUDO_USER, --sudo-user=SUDO_USER
                        desired sudo user (default=root) (deprecated, use
                        become)
    -S, --su            run operations with su (deprecated, use become)
    -R SU_USER, --su-user=SU_USER
                        run operations with su as this user (default=None)
                        (deprecated, use become)
    -b, --become        run operations with become (does not imply password
                        prompting)
    --become-method=BECOME_METHOD
                        privilege escalation method to use (default=sudo),
                        valid choices: [ sudo | su | pbrun | pfexec | doas |
                        dzdo | ksu | runas | pmrun ]
    --become-user=BECOME_USER
                        run operations as this user (default=root)
    --ask-sudo-pass     ask for sudo password (deprecated, use become)
    --ask-su-pass       ask for su password (deprecated, use become)
    -K, --ask-become-pass
                        ask for privilege escalation password

Some modules do not make sense in Ad-Hoc (include, meta, etc)

使用ansible命令^_^:

1.列出配置过的主机列表(可以看到hosts中的node节点配置成功)

ansible]# ansible all --list
  hosts (1):
    172.16.204.134

2.使用--ask-pass(使用ansible_ssh_pass等类似变量是非常危险的,容易导致密码泄露,使用--ask-pass则可以避免密码泄露)

ansible]# ansible all -m ping --ask-pass     #ansible all -m ping   测试所有主机的连通性
SSH password: 
172.16.204.134 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

3.配置密钥方式控制所有主机

  • ansible本机生成公钥:执行一条 ssh-keygen -t rsa命令即可
[ .ssh]# ssh-keygen -t rsa
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:ZHO/Ttd8KD6r+pehmUmXCUxgn1qto0n7oaOQ0e2pKCA 
The key‘s randomart image is:
+---[RSA 2048]----+
|        o.       |
|       . ..o     |
|        +o= .    |
|     . + =oo     |
|    . . S o..o   |
|E    o o =..=. + |
|..  o   *..*+oo +|
|  .  o ..o==+o  .|
|   .. o.o++o+o   |
+----[SHA256]-----+
[ .ssh]# pwd
/root/.ssh
[ .ssh]# ll
total 12
-rw------- 1 root root 1675 Jan  9 22:57 id_rsa
-rw-r--r-- 1 root root  395 Jan  9 22:57 id_rsa.pub
-rw-r--r-- 1 root root  358 Jan  9 20:49 known_hosts

相关推荐