ansible become 使用总结

ansible become使用总结

四种使用方式:

  • hosts文件中进行配置
  • playbook中进行设置
  • task中或者task的main.yml中进行设置
  • 在ansible.cfg文件中进行配置(此种方式不多赘述,网上资料很多)

此处需要说明的是
后两种使用的命令是以become开头
而hosts文件中为ansible_becom开头

hosts文件中进行配置

在hosts文件中主机信息中配置

host1 ansible_connection=ssh ansible_ssh_host=192.168.106.128 ansible_ssh_user=deployer ansible_ssh_pass=123456 ansible_become=true ansible_become_method=sudo ansible_become_user=root ansible_become_pass=123456

在hosts文件中group中进行设置

[test:vars]
ansible_become=true
ansible_become_method=sudo
ansible_become_user=root
ansible_become_pass=123456

需要注意的是ansible_become ansible_become_method ansible_become_user ansible_become_pass 是可以单独设置的比如

[test:vars]
ansible_become_user=root
[test:vars]
ansible_become=true

个人测试当其他值不设置的时候使用的是默认值
默认值为
ansible_become=false
ansible_become_method=sudo
ansible_become_user=root

在playbook中设置

- hosts: postgresql_install
  become: yes
  become_user: root
  roles:
    - role: test_auth

默认值同上

在task中或者task的main.yml中进行设置

# 切换为root用户
- name: test root
  become: yes
  become_user: root
  shell: whoami
# 切换为test普通用户
- name: test start
  become: yes
  become_user: test
  shell: whoami

默认值同上

使用场景

1.当批量操作同一批服器并且权限统一都为root时,前两种比较合适
2.当需要在操作过程中进行角色的切换时,我这摸索了三种方式

第一种: 在hosts文件中将一个主机录入两次

host1 ansible_connection=ssh ansible_ssh_host=192.168.106.128 ansible_ssh_user=deployer ansible_ssh_pass=123456
host2 ansible_connection=ssh ansible_ssh_host=192.168.106.128 ansible_ssh_user=postgres ansible_ssh_pass=postgres

第二种: 在task中进行使用就可以
第三种: 在playbook中满足不了之后使用playbook和task配合使用

注意事项

  • hosts、playbook、task都设置时的优先级
    hosts>task>playbook
原创文章 2 获赞 4 访问量 381

猜你喜欢

转载自blog.csdn.net/weixin_42257195/article/details/106130776
今日推荐