ansible-笔记


1、安装 ansible

// 在管理机上进行 ansible 安装
yum install ansible -y

2、配置主机清单

做个免密
ssh-keygen
ssh-copy-id -i ~/.ssh/id_rsa.pub systemusers@22.50.2.137

vim /etc/ansible/hosts 里面为被控制主机

---
all:
  children:
    prod:
      children:
        A:
          hosts:
            22.50.2.[140:141]:
        B:
          hosts:
            172.16.171.88:
          vars:
            testhostvar: test88_host_var
            B_group_var1: 'group var test1'
            B_group_var2: 'group var test2'
    test:
      children:
        testk:
          hosts:
            22.50.8.42:
            22.50.8.43:
            22.50.8.148:
        testx:
          hosts:
            22.50.2.137:
  vars:
    ansible_user: systemusers
    ansible_become: yes
    become_method: sudo
    become_user: root

上述配置表示, pro 组有两个子组,分别为 A 组和 B 组,而这两个组分别有自己组内的主机

环境变量除了写在主机清单文件中,也可以定义多个 inventory 文件并放在一个目录下,并按一定的命名规则为每个 inventory 命名,以便见名知意
例如:创建一个名为 /etc/ansible/inventorys 的目录,在其中定义 a 和 b 两个 inventory 文件

/etc/ansible/inventorys/a 的内容:
[nginx]
192.168.200.27
192.168.200.28 ansible_password='123456'
192.168.200.29
[apache]
192.168.200.3[0:3]

/etc/ansible/inventorys/b 的内容:
[mysql]
192.168.200.27
192.168.200.29
[web:children]
apache
nginx
[os:children]
web
mysql
ansible-config init --disabled > ansible.cfg
mkdir -p /etc/ansible/inventorys
mv /etc/ansible/hosts /etc/ansible/inventorys/

vim /etc/ansible/ansible.cfg
;inventory=/etc/ansible/hosts改为
inventory=/etc/ansible/inventorys
或者 ansible 或 ansible-playbook 命令使用 -i INVENTORY 选项指定的路径应当为目录
ansible-playbook -i 10.3.2.99,10.3.1.142, /opt/logback.yaml
ansible-playbook -i ./linshi linshi.yaml
ansible all -u systemusers -i ./hosts_150_VM -m "ping"
ansible  all -u systemusers -i "18.11.2.167,"  -m shell -a 'sudo su -l app -c "mkdir -p  /home/app/nfs_data/idCard" '

3、ansible模块

1. 查看ansible都有哪些模块

ansible-doc -l

2. 获取ping模块的详细使用方法

ansible-doc -s ping

3. ping

ansible B -m ping

4. command

ansible B -m command -a "chdir=/tmp removes=/tmp/1.txt ls"

5. shell

ansible B -m shell -a "chdir=/tmp creates=1.sh echo test >1.sh"

6. script

ansible B -m script -a "creates=/tmp/1.sh /root/1.sh" #/root/1.sh位置在ansible机器

7. copy

ansible 10.1.1.60 -m copy -a "src=./host dest=/tmp/ force=yes backup=yes mode=0644 mode=u+x"

8. file

ansible B -m file -a "path=/tmp/1.txt state=touch owner=root group=root mode=0644 recurse=yes" #recurse递归
ansible B -m file -a "path=/tmp/1 state=directory"
ansible B -m file -a "path=/tmp/2.link state=link src=/tmp/1.txt force=no"
ansible B -m file -a "path=/tmp/1.txt.25728.2022-03-29@15:52:05~ state=absent"

9. blockinfile

ansible B -m blockinfile -a 'path=/tmp/1.txt block="systemctl start mariadb\nsystemctl start httpd" marker=#{mark}-j state=present insertafter=EOF backup=yes create=yes'
ansible B -m blockinfile -a 'path=/tmp/1.txt block="#blockinfile test#" marker=#{mark}-j state=present insertafter="^222" backup=yes create=yes'

10. lineinfile

文件末尾添加行
ansible xtest -m lineinfile -a 'path=/tmp/1.txt line="#lineinfile test#" backup=yes'
匹配行添加

  • name: /etc/pam.d/sshd
    lineinfile:
    backup: yes
    path: "/etc/pam.d/sshd"
    insertbefore: '#%PAM-1.0'
    line: 'auth required pam_tally2.so onerr=fail deny=5 unlock_time=900 root_unlock_time=900'
    添加多行
  • name: /etc/hosts.allow
    lineinfile:
    backup: yes
    path: "/etc/hosts.allow"
    line: "{{ item }}"
    with_items:
    • 'sshd:18.11.108.175:allow'
    • 'sshd:18.11.108.181:allow'

tasks:

  • name: /etc/hosts
    lineinfile:
    backup: yes
    path: "/etc/hosts"
    line: "10.3.9.155 ng1.api-qrcode-consume.suixingpay.com\n10.3.9.156 ng2.api-qrcode-consume.suixingpay.com"
    删除匹配行
    ansible test70 -m lineinfile -a 'path=/testdir/test regexp="^10.3.9.155" state=absent'
    tasks:
  • name: /etc/hosts
    lineinfile:
    backup: yes
    path: "/etc/hosts"
    state: absent
    regexp: "^10.3.9.155"
    ansible B -m lineinfile -a 'path=/tmp/1.txt line="#lineinfile test#" state=present regexp="^222" backrefs=yes backup=yes create=yes'

11. find

ansible B -m find -a 'paths=/tmp recurse=yes hidden=no file_type=any patterns=".sh" use_regex=no'
ansible B -m find -a 'paths=/tmp contains=".
111.*" hidden=no recurse=yes'

12. replace

ansible B -m replace -a 'path=/tmp/1.txt regexp="#lineinfile test#" replace=222 backup=yes'

13. cron 模块

新增
ansible B -m cron -a 'name="log-compress" user="app" minute="1" hour="2" job="/bin/sh /home/app/shell/log-compress.sh"'
注释
ansible B -m cron -a 'name="test1" minute=5 hour=1 job="/bin/sh /tmp/1.sh >/dev/null 2>&1" disabled=yes backup=yes'
删除
ansible B -m cron -a 'name="test1" minute=5 hour=1 job="/bin/sh /tmp/1.sh >/dev/null 2>&1" state=absent backup=yes'

14. service

ansible B -m service -a "name=crond state=stopped enabled=no" #started、stopped、restarted、reloaded

15. user

python环境下import crypt; crypt.crypt('123456')
ansible B -m user -a 'name=abc state=present password="$6$G1xlNP4YTDayvukM$zP67StDgVqXje.GsdKoWfw0FoQfoKEni1lr.U0P8zEWZTQKl8DnJloZHdUiCHb6CUp2LVm6IRZBVOcaMctcy61" update_password=always'
ansible B -m user -a "name=abc state=absent remove=yes"

16. yum_repository

ansible B -m yum_repository -a 'name=local baseurl=file:///media description="local cd yum" gpgcheck=yes gpgkey=file:///media/RPM-GPG-KEY-CentOS-7 enabled=no'
ansible B -m yum_repository -a 'file=local name=local state=absent'

17. yum

ansible B -m yum -a "name=lrzsz state=installed state=latest"
ansible B -m yum -a "name=lrzsz state=removed"

18. mount

ansible B -m mount -a 'src=/dataTest path=/mnt fstype=xfs state=mounted opts=default'

19 unarchive ( 解包解压缩 )

  1. 将 ansible 主机上的压缩包传到远程主机后解压缩至特定目录,设置 copy=yes
  2. 将远程主机上的某个压缩包解压缩到指定路径下,设置 copy=no
    常见参数:
    copy:默认为 yes,当 copy=yes,拷贝的文件是从 ansible 主机复制到远程主机上,如果设置为 copy=no,会在远程主机上寻找 src 源文件
    remote_src:和 copy 功能一样且互斥,yes 表示在远程主机,不在ansible主机,no表示文件在ansible主机上
    src:源路径,可以是 ansible 主机上的路径,也可以是远程主机上的路径,如果是远程主机上的路径,则需要设置 copy=no
    dest:远程主机上的目标路径
    mode:设置解压缩后的文件权限
    ansible all -m unarchive -a 'src=/data/foo.tgz dest=/var/lib/foo owner=wang group=bin'
    ansible all -m unarchive -a 'src=/tmp/foo.zip dest=/data copy=no mode=0777'
    ansible all -m unarchive -a 'src=https://example.com/example.zip dest=/data copy=no'
    ansible websrvs -m unarchive -a 'src=https://releases.ansible.com/ansible/ansible-2.1.6.0-0.1.rc1.tar.gz dest=/data/ owner=mysql remote_src=yes

20.样例:

vim command.yaml

---
- hosts: all
  vars:
    testvar1: 123
    testvar3: /tmp/2
    sysctl_conf: /etc/sysctl.conf
    users:
      alice:
        name: Alice Appleworth
        gender: female
        telephone: 123-456-7890
  vars_files:
  - /etc/ansible/vars.yml
  gather_facts: false

  remote_user: systemusers
  become: yes
  become_user: root
  become_method: sudo

  tasks:
  - name: 1-ping
    ping:
  - name: 2-mkdir
    file: path=/tmp/1 state=directory
    register: reg2
    notify: handler group1
    ignore_errors: true
  - meta: flush_handlers
  - name: debug demo
    debug:
      msg: "value of reg2 is : {{reg2}}"
  - name: 3-copy
    file: path={{ testvar3 }} state=directory    
    changed_when: true
    notify: handler3
  - name: debug demo
    debug:
      msg: this is debug info,The {{ testvar3 }} has been touched
  - debug:
      msg: "{{item.test1}}"
    with_items:
    - { test1: a, test2: b }
    - { test1: c, test2: d }
    with_list:
    - [ 1, 2, 3 ]
    - [ a, b ]    
    with_together:
    - [ 1, 2, 3 ]
    - [ a, b, c ]
    with_cartesian:
    - [ a, b, c ]
    - [ test1, test2 ]
    with_sequence: start=6 end=2 stride=-2
    with_sequence: start=2 end=6 stride=2 format="number is %0.2f"
  - debug:
      msg: "User {{ item.key }} is {{ item.value.name }}, Gender: {{ item.value.gender }}, Tel: {{ item.value.telephone }}"
    with_dict: "{{users}}"
  - debug:
      msg: "System release is centos"
    when: ansible_distribution == "CentOS"
  - debug:
      msg: "task1 not in block"
  - fail:
  - block:
      - debug:
          msg: "task2 in block1"
      - debug:
          msg: "task3 in block1"
    when: 2 > 1
  - include: install_MysqlAndPhp.yml
  - include_tasks: in.yml
  - yum:
      name: nginx
      state: present
  - name: Adjust kernel parameters to sysctl.conf
    sysctl:
      name: "{{ item.key }}"
      value: "{{ item.value }}"
      sysctl_file: "{{ sysctl_conf }}"
      state: present
      reload: yes
    with_items:
      - { key: 'net.ipv4.tcp_tw_reuse', value: '1' }
      - { key: 'net.ipv4.tcp_tw_recycle', value: '0' }
      - { key: 'net.ipv4.tcp_timestamps', value: '0' }

  handlers:
  - name: handler1
    listen: handler group1
    file: path=/tmp/1/1.txt state=touch
  - name: handler2
    listen: handler group1
    file: path=/tmp/1/2.txt state=touch
  - name: handler3
    copy: src=/etc/hosts  dest=/tmp/2

ansible-playbook command.yml

21. 检查语法

ansible-playbook --syntax-check command.yml

22. 外部传入变量

ansible-playbook command.yml -e 'pass_var="test"'

23. bind {{ansible_host}}

ansible B -m template -a "src=/testdir/ansible/redis.conf dest=/opt/redis.conf force=yes backup=yes"

4、在 ansible 中,我们可以使用如下比较运算符

==  :比较两个对象是否相等,相等为真
!=  :比较两个对象是否不等,不等为真
>   :比较两个值的大小,如果左边的值大于右边的值,则为真
<  :比较两个值的大小,如果左边的值小于右边的值,则为真
>=  :比较两个值的大小,如果左边的值大于右边的值或左右相等,则为真
<=  :比较两个值的大小,如果左边的值小于右边的值或左右相等,则为真
我们总结的这些运算符其实都是jinja2的运算符,ansible使用jinja2模板引擎,在ansible中也可以直接使用jinja2的这些运算符.
说完了比较运算符,再来说说逻辑运算符,可用的逻辑运算符如下
and  :逻辑与,当左边与右边同时为真,则返回真
or  :逻辑或,当左边与右边有任意一个为真,则返回真
not  :取反,对一个操作体取反
( )  :组合,将一组操作体包装在一起,形成一个较大的操作体

5、Ansible 执行过程分析、异步、效率优化

ansible 命令或 ansible-playbook 命令加上 -vvv 选项,会输出很多调试信息,包括建立的连接、发送的文件等等

1. ssh 的多路复用

(有些特殊情况下可能需要关闭 SSH 的多路复用功能,比如网络环境不稳定或存在安全隐患等.但在正常情况下,开启 SSH 的多路复用功能可以显著提升连接速度和效率)
cat << EOF > ~/.ssh/config
Host *
ControlMaster auto
ControlPath /tmp/%r@%h:%p
ControlPersist 6000
EOF
// 建立ssh连接所需时间
time ssh root@172.16.171.88 /usr/bin/pwd

ansible 的 ssh 多路复用
ControlMaster=auto -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=publickey,gssapi-with-mic,gssapi-keyex,hostbased -o PasswordAuthentication=no -o ControlPath=~/.ansible/cp/%h-%p-%r -o ConnectTimeout=6 -o ControlPersist=120s root@172.16.171.88 /usr/bin/pwd
ssh_args = -o ControlMaster=auto -o StrictHostKeyChecking=no -o PasswordAuthentication=no -o ControlPath=~/.ansible/cp/%h-%r -o ConnectTimeout=6 -o ControlPersist=6000

2. 启用流水线

vim /etc/ansible/ansible.cfg

[ssh_connection]
ssh_args = -o ControlMaster=auto -o StrictHostKeyChecking=no -o PasswordAuthentication=no -o ConnectTimeout=6 -o ControlPersist=1h

control_path_dir = ~/.ansible/cp

control_path = %(directory)s/%%h-%%r
// 启用流水线(visudo禁用requiretty)
pipelining = True

[inventory]
# enable inventory plugins, default: 'host_list', 'script', 'auto', 'yaml', 'ini', 'toml'
#enable_plugins = host_list, virtualbox, yaml, constructed

# ignore these extensions when parsing a directory as inventory source
ignore_extensions = .pyc, .pyo, .swp, .bak, ~, .rpm, .md, .txt, ~, .orig, .ini, .cfg, .retry, .sh

[defaults] 下面加入
callback_whitelist= profile_tasks
// profile_tasks:该回调插件用于计时每个任务的执行时长
// profile_roles插件用于计时每个Role的执行时长
// timer插件用于计时每个play执行时长

gathering = explicit
// smart 表示默认收集 facts,但 facts 已有的情况下不会收集,即使用缓存 facts
// implicit 表示默认收集 facts,要禁止收集,必须使用 gather_facts: False
// explicit 则表示默认不收集,要显式收集,必须使用 gather_facts: True

// 搜索去掉注释
host_key_checking = False
// 并行数量20
forks          = 10

3. fact 配置 redis 缓存方法

vim  /etc/ansible/ansible.cfg 
 [defaults]
gathering = smart
fact_caching_timeout = 86400
fact_caching = redis
#redis的ip和端口,也可使用域名
fact_caching_connection = 192.168.1.5:6379
#如果redis设置了密码为admin
#fact_caching_connection = 192.168.1.5:6379:0:admin

6、ansible 互信

1.首先采用 Ansible 批量建立 ssh 无密码登录的信任关系!!

[root@ansible-server ~]# ssh-keygen -t rsa          #一路回车
[root@ansible-server ~]# ls /root/.ssh/
id_rsa  id_rsa.pub
  
####################################################################################################
需要注意ssh建立互信的命令格式:
# ssh-copy-id -i ~/.ssh/id_rsa.pub username@ip或hostname
####################################################################################################
  
在客户机比较多的情况下,使用 ssh-copy-id命令的方法显然是有些费时,使用ansible-playbook 推送 ymal进行批量创建ssh互信关系就显得省事多了,
这里就使用到了ansible的authoried_keys 模块:
  
首先要配置ansible清单 (远程主机的密码这里为"123456")
[root@ansible-server ~]# vim /etc/ansible/hosts
................
................
[ssh-host]
172.16.60.204
172.16.60.205
172.16.60.206
172.16.60.207
  
[ssh-host:vars]
ansible_ssh_pass="123456"
  
####################################################################################################
发送公钥到目标机器命令格式如下:
# ansible ssh-host -m copy -a "src=/root/.ssh/id_rsa.pub dest=/root/.ssh/authorized_keys mode=600"
####################################################################################################
在上面分发密钥中,如果清单文件/etc/ansible/hosts里没有使用ansible_ssh_pass变量指明密码,则可以使用下面命令:
这里默认ssh-host组下的机器root密码都一样,使用-k 参数,回车输入root密码即可:
# ansible ssh-host -m authorized_key -a "user=root state=present key=\"{{ lookup('file', '/root/.ssh/id_rsa.pub') }} \"" -k
####################################################################################################
  
编写playbook文件
[root@ansible-server ~]# vim /opt/ssh_key.yaml
---
  - hosts: ssh-host
    user: root
    tasks:
     - name: ssh-copy
       authorized_key: user=root key="{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"
  
注意上面yaml脚本中的"ssh-key-host"是在/etc/ansible/hosts清单文件里配置的远程客户机列表
这里做的是基于远程主机root用户的ssh互信
  
执行批量互信
[root@ansible-server ~]# ansible-playbook /opt/ssh_key.yaml
  
PLAY [ssh-host] ************************************************************************************************************************
  
TASK [Gathering Facts] *****************************************************************************************************************
ok: [172.16.60.204]
ok: [172.16.60.205]
ok: [172.16.60.206]
ok: [172.16.60.207]
  
TASK [ssh-copy] ************************************************************************************************************************
changed: [172.16.60.205]
changed: [172.16.60.204]
changed: [172.16.60.206]
changed: [172.16.60.207]
  
PLAY RECAP *****************************************************************************************************************************
172.16.60.204              : ok=2    changed=1    unreachable=0    failed=0 
172.16.60.205              : ok=2    changed=1    unreachable=0    failed=0 
172.16.60.206              : ok=2    changed=1    unreachable=0    failed=0 
172.16.60.207              : ok=2    changed=1    unreachable=0    failed=0
  
最后验证下ssh互信
[root@ansible-server ~]# ansible -i /etc/ansible/hosts ssh-host -m shell -a "whoami"
172.16.60.204 | SUCCESS | rc=0 >>
root

2.Ansible 批量更新远程主机用户密码方法

方法一:  使用Ansible的user模块批量修改远程客户机的用户密码
由于在使用ansible修改用户密码的时候不能使用明文的方式,需要先加密,所以就需要使用一个方法对输入的明文的密码进行加密.
废话不多说了. 下面直接记录下操作方法:

[root@ansible-server ~]# vim /opt/root_passwd.yaml
---
  - hosts: ssh-host
    gather_facts: false
    tasks:
    - name: change user passwd
      user: name={{ item.name }} password={{ item.chpass | password_hash('sha512') }}  update_password=always
      with_items:
           - { name: 'root', chpass: 'kevin@123' }
           - { name: 'app', chpass: 'bjop123' }
 
注意上面在yaml文件中修改了远程客户机的root用户密码, app用户密码.
如果还想要修改其他用户密码, 则继续按照上面规则添加即可!
 
执行ansible-play
[root@ansible-server ~]# ansible-playbook /opt/root_passwd.yaml
 
PLAY [ssh-host] ************************************************************************************************************************
 
TASK [change user passwd] **************************************************************************************************************
changed: [172.16.60.204] => (item={u'chpass': u'kevin@123', u'name': u'root'})
changed: [172.16.60.205] => (item={u'chpass': u'kevin@123', u'name': u'root'})
changed: [172.16.60.204] => (item={u'chpass': u'bjop123', u'name': u'app'})
changed: [172.16.60.205] => (item={u'chpass': u'bjop123', u'name': u'app'})
changed: [172.16.60.206] => (item={u'chpass': u'kevin@123', u'name': u'root'})
changed: [172.16.60.206] => (item={u'chpass': u'bjop123', u'name': u'app'})
changed: [172.16.60.207] => (item={u'chpass': u'kevin@123', u'name': u'root'})
changed: [172.16.60.207] => (item={u'chpass': u'bjop123', u'name': u'app'})
 
PLAY RECAP *****************************************************************************************************************************
172.16.60.204              : ok=1    changed=1    unreachable=0    failed=0  
172.16.60.205              : ok=1    changed=1    unreachable=0    failed=0  
172.16.60.206              : ok=1    changed=1    unreachable=0    failed=0  
172.16.60.207              : ok=1    changed=1    unreachable=0    failed=0

方法二:  修改远程主机的单个用户密码使用此方法比较方便
编写playbook文件
[root@ansible-server ~]# vim /opt/root_passwd2.yaml
---
  - hosts: ssh-host
    gather_facts: false
    tasks:
    - name: Change password
      user: name={{ name1 }}  password={{ chpass | password_hash('sha512') }}  update_password=always
 
执行ansible-playbook,  使用-e参数传递用户名和密码给剧本,其中root为用户名,admin#123就是修改后的root密码
[root@ansible-server ~]# ansible-playbook /opt/root_passwd2.yaml -e "name1=root chpass=admin#123"           
 
PLAY [ssh-host] ************************************************************************************************************************
 
TASK [Change password] *****************************************************************************************************************
changed: [172.16.60.204]
changed: [172.16.60.205]
changed: [172.16.60.206]
changed: [172.16.60.207]
 
PLAY RECAP *****************************************************************************************************************************
172.16.60.204              : ok=1    changed=1    unreachable=0    failed=0  
172.16.60.205              : ok=1    changed=1    unreachable=0    failed=0  
172.16.60.206              : ok=1    changed=1    unreachable=0    failed=0  
172.16.60.207              : ok=1    changed=1    unreachable=0    failed=0

方法三:  使用如下Ansible脚本, 适用于修改清单中部分远程主机的用户密码
编写ansible-playbook脚本 (需要注意下面脚本中"ens192"是客户机ip所在的网卡设备名称, 这个要根据自己实际环境去配置, 比如eth0, eth1等)
[root@ansible-server ~]# cat /opt/root_passwd4.yaml
- hosts: test-host
  remote_user: root
  tasks:
  - name: change password for root
    shell: echo '{{ item.password }}' |passwd --stdin root
    when: ansible_ens192.ipv4.address  == '{{ item.ip }}'
    with_items:
     - { ip: "172.16.60.220", password: 'haha@123' }
     - { ip: "172.16.60.221", password: 'kevin@123' }
     - { ip: "172.16.60.222", password: 'bobo@123' }
 
 执行ansible-playbook:
 [root@ansible-server ansible]# ansible-playbook /opt/root_passwd3.yaml
 
PLAY [ssh-host] ************************************************************************************************************************
 
TASK [Gathering Facts] *****************************************************************************************************************
ok: [172.16.60.204]
ok: [172.16.60.205]
ok: [172.16.60.206]
ok: [172.16.60.207]
 
TASK [change password for root] ********************************************************************************************************
 [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: ansible_eth0.ipv4.address
== '{{ item.ip }}'
 
 [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: ansible_eth0.ipv4.address
== '{{ item.ip }}'
 
skipping: [172.16.60.205] => (item={u'ip': u'172.16.60.204', u'password': u'haha@123'})
 [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: ansible_eth0.ipv4.address
== '{{ item.ip }}'
 
skipping: [172.16.60.206] => (item={u'ip': u'172.16.60.204', u'password': u'haha@123'})
skipping: [172.16.60.206] => (item={u'ip': u'172.16.60.205', u'password': u'kevin@123'})
 [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: ansible_eth0.ipv4.address
== '{{ item.ip }}'
 
skipping: [172.16.60.207] => (item={u'ip': u'172.16.60.204', u'password': u'haha@123'})
skipping: [172.16.60.207] => (item={u'ip': u'172.16.60.205', u'password': u'kevin@123'})
skipping: [172.16.60.207] => (item={u'ip': u'172.16.60.206', u'password': u'bobo@123'})
changed: [172.16.60.205] => (item={u'ip': u'172.16.60.205', u'password': u'kevin@123'})
skipping: [172.16.60.205] => (item={u'ip': u'172.16.60.206', u'password': u'bobo@123'})
changed: [172.16.60.204] => (item={u'ip': u'172.16.60.204', u'password': u'haha@123'})
skipping: [172.16.60.204] => (item={u'ip': u'172.16.60.205', u'password': u'kevin@123'})
skipping: [172.16.60.204] => (item={u'ip': u'172.16.60.206', u'password': u'bobo@123'})
changed: [172.16.60.206] => (item={u'ip': u'172.16.60.206', u'password': u'bobo@123'})
 
PLAY RECAP *****************************************************************************************************************************
172.16.60.204              : ok=2    changed=1    unreachable=0    failed=0  
172.16.60.205              : ok=2    changed=1    unreachable=0    failed=0  
172.16.60.206              : ok=2    changed=1    unreachable=0    failed=0  
172.16.60.207              : ok=1    changed=0    unreachable=0    failed=0

如果ansible服务端没有和远程主机做ssh信任关系, 则可以在hosts清单配置里直接指明用户名和密码.
如果使用普通用户, 并且允许sudo, 则需要提前在客户机里的/etc/sudoers文件里配置好该普通用户的sudo配置, 即允许该普通用户有sudo权限.
  
[root@ansible-server ~]# vim /etc/ansible/hosts
................
[test-host]
172.16.60.220 ansible_ssh_user=root ansible_ssh_pass=123456 ansible_ssh_port=22
172.16.60.221 ansible_ssh_user=root ansible_ssh_pass=bo@123 ansible_ssh_port=22
172.16.60.222 ansible_ssh_user=app ansible_ssh_pass=bj@123 ansible_ssh_port=22 ansible_sudo_pass=bj@123
  
即172.16.60.222客户机上要提前配置, 允许app用户具有sudo权限.
 
执行:
[root@ansible-server ~]# ansible test-host -m shell -a "hostname"                     
172.16.60.222 | SUCCESS | rc=0 >>
k8s-node02
 
172.16.60.220 | SUCCESS | rc=0 >>
k8s-master01
 
172.16.60.221 | SUCCESS | rc=0 >>
k8s-node01
 
[root@ansible-server ~]# ansible -i /etc/ansible/hosts test-host -m shell -a "hostname"
172.16.60.222 | SUCCESS | rc=0 >>
k8s-node02
 
172.16.60.220 | SUCCESS | rc=0 >>
k8s-master01
 
172.16.60.221 | SUCCESS | rc=0 >>
k8s-node01

参考文献

https://www.zsythink.net/archives/tag/ansible/page/5
https://www.junmajinlong.com/ansible/index/
https://docs.ansible.com/ansible/2.4/modules_by_category.html
https://blog.csdn.net/qq_45637155/article/details/109167893
https://www.cnblogs.com/kevingrace/p/5569648.html

             ------------------------------- THE END -------------------------------

posted @ 2025-02-10 17:02  ordinaryRoadX  阅读(2)  评论(0编辑  收藏  举报