• Ansible-安装-秘钥-部署-使用


    本文转自:https://www.cnblogs.com/ylqh/p/5902259.html

    ansiblemaster:192.168.74.146

    ansibleslave1 :192.168.74.144

    ansibleslave2 :  192.168.74.140

    安装ansible:

    [root@ansiblemaster /]# yum -y install ansible

    生成ssh秘钥文件,并且分发给所有客户端

    复制代码
    [root@ansible_master ~]# ssh-keygen -t rsa #生成密钥
    #将公钥分别发送到slave机器上面 [root@ansible_master ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.74.144 -bash: ssh-copy-id: command not found 报错了 解决方法: yum -y install openssh-clients

     [root@ansible_master ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.74.144
      The authenticity of host '192.168.74.144 (192.168.74.144)' can't be established.
      RSA key fingerprint is b8:5b:58:13:6f:71:12:0b:10:70:97:f8:c7:71:2c:c5.
      Are you sure you want to continue connecting (yes/no)? yes
      Warning: Permanently added '192.168.74.144' (RSA) to the list of known hosts.
      root@192.168.74.144's password: 
      Now try logging into the machine, with "ssh '192.168.74.144'", and check in:

      .ssh/authorized_keys

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

     在slave端见检查是否出现一个authorized_keys的文件。

      root@ansibleslave1 .ssh]# ls /root/.ssh/
      authorized_keys

     检查一下是否安装成功:

     [root@ansible_master ~]# ansible --version
      ansible 2.1.1.0
      config file = /etc/ansible/ansible.cfg
      configured module search path = Default w/o overrides

    复制代码
     
     

    安装ssh过程中如果出现sign_and_send_pubkey: signing failed: agent refused operation,解决方式为执行

    eval "$(ssh-agent -s)"

    ssh-add

    ansible安装完成

    ansible的配置:

    首先配置三台主机的hosts的文件:

    [root@ansiblemaster ansible]# cat /etc/hosts
    192.168.74.146 ansiblesmaster
    192.168.74.144 ansibleslave1
    192.168.74.140 ansibleslave2

    配置ansible的host分组

    [root@ansiblemaster ansible]# cat /etc/ansible/hosts 
    [www]
    ansibleslave1
    ansibleslave2

    测试ansible与slave的是否可用了

    复制代码
    [root@ansiblemaster ansible]# ansible *www* -m shell -a "df -h" -k
    SSH password: 
    ansibleslave1 | SUCCESS | rc=0 >>
    Filesystem      Size  Used Avail Use% Mounted on
    devtmpfs        488M     0  488M   0% /dev
    tmpfs           495M     0  495M   0% /dev/shm
    tmpfs           495M  624K  495M   1% /run
    tmpfs           495M     0  495M   0% /sys/fs/cgroup
    /dev/sda3        18G  1.4G   17G   8% /
    tmpfs           495M   44K  495M   1% /tmp
    /dev/sda1       283M   74M  191M  28% /boot
    tmpfs            99M     0   99M   0% /run/user/0
    tmpfs            99M     0   99M   0% /run/user/1000
    
    ansibleslave2 | SUCCESS | rc=0 >>
    Filesystem      Size  Used Avail Use% Mounted on
    devtmpfs        488M     0  488M   0% /dev
    tmpfs           495M     0  495M   0% /dev/shm
    tmpfs           495M  648K  495M   1% /run
    tmpfs           495M     0  495M   0% /sys/fs/cgroup
    /dev/sda3        18G  2.1G   16G  12% /
    tmpfs           495M   48K  495M   1% /tmp
    /dev/sda1       283M   74M  191M  28% /boot
    tmpfs            99M     0   99M   0% /run/user/0
    tmpfs            99M     0   99M   0% /run/user/1000
    复制代码

    到此ansible已经支持简单的批量命令了

    ansible错误排除:

    第一:

    复制代码
    [root@ansiblemaster ansible]# ansible -m ping all -k
    SSH password: 
    ansibleslave1 | UNREACHABLE! => {
        "changed": false, 
        "msg": "Failed to connect to the host via ssh.", 
        "unreachable": true
    }
    解决方法:
    第一:首先查看客户端的/root/.ssh/下面是否存在 authorized_keys文件。
    第二:测试master端是否可以无密钥登录slave端
    (注意:检查防火墙与selinux)
    第三:ping主机名是否可以ping通。

    复制代码

    第二:

    复制代码
    [root@ansiblemaster ansible]# ansible all -m ping -k
    SSH password: 
    ansibleslave1 | FAILED! => {
        "failed": true, 
        "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第一次连接的时候一般会提示输入yes 进行确认为将key字符串加入到  ~/.ssh/known_hosts 文件中。而本机的~/.ssh/known_hosts文件中并有fingerprint key串
    解决方法:在ansible.cfg文件中更改下面的参数:
    # host_key_checking = False
    将#号去掉即可
    复制代码

     ###################ansible内置模块的使用####################

    先介绍一下ansible的命令参数:

    复制代码
     1 [root@ansiblemaster ansible]# ansible --help
     2 Usage: ansible <host-pattern> [options]
     3 
     4 Options:
     5   -a MODULE_ARGS, --args=MODULE_ARGS  #(指定模块参数)
     6                         module arguments
     7   --ask-vault-pass      ask for vault password
     8   -B SECONDS, --background=SECONDS   #(在后台运行命令,在制定NUM秒后kill该任务)
     9                         run asynchronously, failing after X seconds
    10                         (default=N/A)
    11   -C, --check           don't make any changes; instead, try to predict some
    12                         of the changes that may occur  #(只是测试一下会改变什么内容,不会真正去执行)
    13   -D, --diff            when changing (small) files and templates, show the
    14                         differences in those files; works great with --check
    15   -e EXTRA_VARS, --extra-vars=EXTRA_VARS
    16                         set additional variables as key=value or YAML/JSON
    17   -f FORKS, --forks=FORKS
    18                         specify number of parallel processes to use
    19                         (default=5)
    20   -h, --help            show this help message and exit #(帮助信息)
    21   -i INVENTORY, --inventory-file=INVENTORY #(指定hosts文件路径,默认default=/etc/ansible/hosts)
    22                         specify inventory host path
    23                         (default=/etc/ansible/hosts) or comma separated host
    24                         list.
    25   -l SUBSET, --limit=SUBSET
    26                         further limit selected hosts to an additional pattern
    27   --list-hosts          outputs a list of matching hosts; does not execute
    28                         anything else
    29   -m MODULE_NAME, --module-name=MODULE_NAME #(指定模块)
    30                         module name to execute (default=command)
    31   -M MODULE_PATH, --module-path=MODULE_PATH #(要执行的模块路径,默认为/usr/share/ansible)
    32                         specify path(s) to module library (default=None)
    33   --new-vault-password-file=NEW_VAULT_PASSWORD_FILE
    34                         new vault password file for rekey
    35   -o, --one-line        condense output   #(一个主机的执行结果在一行显示)
    36   --output=OUTPUT_FILE  output file name for encrypt or decrypt; use - for
    37                         stdout
    38   -P POLL_INTERVAL, --poll=POLL_INTERVAL
    39                         set the poll interval if using -B (default=15)
    40   --syntax-check        perform a syntax check on the playbook, but do not
    41                         execute it
    42   -t TREE, --tree=TREE  log output to this directory #(日志输出到该目录,日志文件名以主机名命名)
    43   --vault-password-file=VAULT_PASSWORD_FILE
    44                         vault password file
    45   -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
    46                         connection debugging)
    47   --version             show program's version number and exit
    48 
    49   Connection Options:
    50     control as whom and how to connect to hosts
    51 
    52     -k, --ask-pass      ask for connection password #(输入ssh密码,而不是使用秘钥)
    53     --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE
    54                         use this file to authenticate the connection
    55     -u REMOTE_USER, --user=REMOTE_USER #(指定远程机器的用户)
    56                         connect as this user (default=None)
    57     -c CONNECTION, --connection=CONNECTION #(指定建立连接的类型,一般有ssh,localhost FILES)
    58                         connection type to use (default=smart)
    59     -T TIMEOUT, --timeout=TIMEOUT  #(超时时间)
    60                         override the connection timeout in seconds
    61                         (default=10)
    62     --ssh-common-args=SSH_COMMON_ARGS
    63                         specify common arguments to pass to sftp/scp/ssh (e.g.
    64                         ProxyCommand)
    65     --sftp-extra-args=SFTP_EXTRA_ARGS
    66                         specify extra arguments to pass to sftp only (e.g. -f,
    67                         -l)
    68     --scp-extra-args=SCP_EXTRA_ARGS
    69                         specify extra arguments to pass to scp only (e.g. -l)
    70     --ssh-extra-args=SSH_EXTRA_ARGS
    71                         specify extra arguments to pass to ssh only (e.g. -R)
    72 
    73   Privilege Escalation Options:
    74     control how and which user you become as on target hosts
    75 
    76     -s, --sudo          run operations with sudo (nopasswd) (deprecated, use
    77                         become)
    78     -U SUDO_USER, --sudo-user=SUDO_USER
    79                         desired sudo user (default=root) (deprecated, use
    80                         become)
    81     -S, --su            run operations with su (deprecated, use become)
    82     -R SU_USER, --su-user=SU_USER
    83                         run operations with su as this user (default=root)
    84                         (deprecated, use become)
    85     -b, --become        run operations with become (does not imply password
    86                         prompting)
    87     --become-method=BECOME_METHOD
    88                         privilege escalation method to use (default=sudo),
    89                         valid choices: [ sudo | su | pbrun | pfexec | runas |
    90                         doas | dzdo ]
    91     --become-user=BECOME_USER
    92                         run operations as this user (default=root)
    93     --ask-sudo-pass     ask for sudo password (deprecated, use become)
    94     --ask-su-pass       ask for su password (deprecated, use become)
    95     -K, --ask-become-pass                          #(提示输入sudo密码,与sudo一起使用)
    96                         ask for privilege escalation password
    (解释的不是太全,有些我还没有用到,欢迎大牛指定!)
    复制代码

    ansible的模块的使用:

    第一个:copy模块

    用途:把master端文件拷贝到其他slave端上

    复制代码
    [root@ansiblemaster ansible]# ansible *www* -m copy -a 'src=/etc/ansible/test1.txt dest=/opt/'
    ansibleslave2 | FAILED! => {
        "changed": false, 
        "checksum": "44b9edcf7d3cb15a005a3eb16b8011d352399eed", 
        "failed": true, 
        "msg": "Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!"
    }
    问题:被控机器上开启selinux的,需要要安装上libselinux-python
    解决办法:被控机器上安装:
    yum -y install libselinux-python

     [root@ansiblemaster ansible]# ansible *www* -m copy -a 'src=/etc/ansible/test1.txt dest=/opt/' -k
      SSH password: 
      ansibleslave2 | SUCCESS => {
      "changed": true, 
      "checksum": "44b9edcf7d3cb15a005a3eb16b8011d352399eed", 
      "dest": "/opt/test1.txt", 
      "gid": 0, 
      "group": "root", 
      "md5sum": "0a1d32cf98dac2652ecca0aa4571ac3b", 
      "mode": "0644", 
      "owner": "root", 
      "secontext": "system_u:object_r:usr_t:s0", 
      "size": 5, 
      "src": "/root/.ansible/tmp/ansible-tmp-1474886175.03-280566111251484/source", 
      "state": "file", 
      "uid": 0
      }

    复制代码

    第二个:file模块:

    用途:更改被控节点的权限为777,属主数组为root

    复制代码
    [root@ansiblemaster ansible]# ansible all -m file -a "dest=/opt/test1.txt mode=777 owner=root group=root"
    ansibleslave1 | SUCCESS => {
        "changed": true, 
        "gid": 0, 
        "group": "root", 
        "mode": "0777", 
        "owner": "root", 
        "path": "/opt/test1.txt", 
        "secontext": "system_u:object_r:usr_t:s0", 
        "size": 5, 
        "state": "file", 
        "uid": 0
    }
    复制代码

    第三个:cron

    用途:在所有节点上设置crontab

    复制代码
    [root@ansiblemaster ansible]# ansible all -m cron -a 'name="custom job" minute=*/3 hour=* day=* month=* weekday=* job="/usr/sbin/ntpdate 192.168.74.146"'
    ansibleslave1 | SUCCESS => {
        "changed": true, 
        "envs": [], 
        "jobs": [
            "custom job"
        ]
    }
    ansibleslave2 | SUCCESS => {
        "changed": true, 
        "envs": [], 
        "jobs": [
            "custom job"
        ]
    }
    复制代码

    第四个:group模块

    用途:在所有被控端上创建gid是2048的名字为zzl的组

    复制代码
    [root@ansiblemaster ansible]# ansible all -m group -a 'gid=2048 name=zzl'
    ansibleslave1 | SUCCESS => {
        "changed": true, 
        "gid": 2048, 
        "name": "zzl", 
        "state": "present", 
        "system": false
    }
    ansibleslave2 | SUCCESS => {
        "changed": true, 
        "gid": 2048, 
        "name": "zzl", 
        "state": "present", 
        "system": false
    }
    复制代码

    第五个:user模块

    用途:在所有被控端上创建用户名为zzl,组名为zzl的用户

    复制代码
    [root@ansiblemaster ansible]# ansible all -m user -a 'name=zzl groups=zzl state=present'
    ansibleslave1 | SUCCESS => {
        "changed": true, 
        "comment": "", 
        "createhome": true, 
        "group": 100, 
        "groups": "zzl", 
        "home": "/home/zzl", 
        "name": "zzl", 
        "shell": "/bin/bash", 
        "state": "present", 
        "system": false, 
        "uid": 1003
    }
    ansibleslave2 | SUCCESS => {
        "changed": true, 
        "comment": "", 
        "createhome": true, 
        "group": 100, 
        "groups": "zzl", 
        "home": "/home/zzl", 
        "name": "zzl", 
        "shell": "/bin/bash", 
        "state": "present", 
        "system": false, 
        "uid": 1002
    }
    复制代码

    第六:get_url模块:

    用途: 将http://ip/的index.html下载到所有节点的/home目录下

    复制代码
    [root@ansiblemaster ~]# ansible all -m get_url -a 'url=http://ip/ dest=/home'
    ansibleslave1 | SUCCESS => {
        "changed": true, 
        "checksum_dest": null, 
        "checksum_src": "3b8a8ccd603538b663776258db5265adf1e87ece", 
        "dest": "/home/index.html", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "8235b10c5e8177ab388f9b0f7073bcb9", 
        "mode": "0644", 
        "msg": "OK (unknown bytes)", 
        "owner": "root", 
        "secontext": "unconfined_u:object_r:home_root_t:s0", 
        "size": 3209, 
        "src": "/tmp/tmp5dcxVi", 
        "state": "file", 
        "uid": 0, 
        "url": "http://211.151.81.74/"
    }
    ansibleslave2 | SUCCESS => {
        "changed": true, 
        "checksum_dest": null, 
        "checksum_src": "67190352276452de41c7b08b0eb98d0b997ea21a", 
        "dest": "/home/index.html", 
        "gid": 0, 
        "group": "root", 
        "md5sum": "643988ed5105422eaf813b6acde9661a", 
        "mode": "0644", 
        "msg": "OK (unknown bytes)", 
        "owner": "root", 
        "secontext": "unconfined_u:object_r:home_root_t:s0", 
        "size": 3209, 
        "src": "/tmp/tmpmGTNeq", 
        "state": "file", 
        "uid": 0, 
        "url": "http://211.151.81.74/"
    }
    复制代码

    第七:script模块

    用途:在所有节点上执行/home/1.sh脚本(该脚本是在ansible控制节点上的)

    复制代码
    [root@ansiblemaster ~]# ansible all -m script -a '/home/1.sh'
    ansibleslave1 | SUCCESS => {
        "changed": true, 
        "rc": 0, 
        "stderr": "", 
        "stdout": "", 
        "stdout_lines": []
    }
    ansibleslave2 | SUCCESS => {
        "changed": true, 
        "rc": 0, 
        "stderr": "", 
        "stdout": "", 
        "stdout_lines": []
    }
    复制代码

    第八:command:

    用途:在指定节点上运行df -h的命令

    复制代码
    [root@ansiblemaster ~]# ansible all -m command -a 'df -h'
    ansibleslave1 | SUCCESS | rc=0 >>
    Filesystem      Size  Used Avail Use% Mounted on
    devtmpfs        488M     0  488M   0% /dev
    tmpfs           495M     0  495M   0% /dev/shm
    tmpfs           495M  624K  495M   1% /run
    tmpfs           495M     0  495M   0% /sys/fs/cgroup
    /dev/sda3        18G  1.4G   17G   8% /
    tmpfs           495M   44K  495M   1% /tmp
    /dev/sda1       283M   74M  191M  28% /boot
    tmpfs            99M     0   99M   0% /run/user/0
    tmpfs            99M     0   99M   0% /run/user/1000
    
    ansibleslave2 | SUCCESS | rc=0 >>
    Filesystem      Size  Used Avail Use% Mounted on
    devtmpfs        488M     0  488M   0% /dev
    tmpfs           495M     0  495M   0% /dev/shm
    tmpfs           495M  648K  495M   1% /run
    tmpfs           495M     0  495M   0% /sys/fs/cgroup
    /dev/sda3        18G  2.2G   16G  12% /
    tmpfs           495M   48K  495M   1% /tmp
    /dev/sda1       283M   74M  191M  28% /boot
    tmpfs            99M     0   99M   0% /run/user/0
    tmpfs            99M     0   99M   0% /run/user/1000
    复制代码
  • 相关阅读:
    python D5
    python D4
    python D3
    python D2
    python D1
    day12——闭包,装饰器,迭代器
    day11——考试python2和python3的区别
    day10——动态参数,名称空间,global,nonlocal
    day9——函数初识
    day8——文件操作
  • 原文地址:https://www.cnblogs.com/shuiyelifang/p/8422347.html
Copyright © 2020-2023  润新知