[email protected]:/$ ansible version WARNING : log file at /var/log/ansible.log is not writeable and we cannot crea...">

当前位置:网站首页>Ansible learning summary (8) -- Summary of ansible control right raising related knowledge

Ansible learning summary (8) -- Summary of ansible control right raising related knowledge

2022-06-23 00:41:00 Technology d life

Preface

Ansible edition

[email protected]:/$ ansible --version
[WARNING]: log file at /var/log/ansible.log is not writeable and we cannot create it, aborting

ansible 2.9.6
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/zhanghaiyang/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.8.5 (default, Jan 27 2021, 15:41:15) [GCC 9.3.0]
[email protected]:/$

For beginners ansible Most of the small partners are configured through configuration ansible.cfg To configure the authorization , Configure the authorization through the configured file , Have the right to promote all script roles , The advantage of this is , Easy and convenient , But there are risks , Any command is universal root To execute , That is, any process has the highest authority of the system , For hackers , What you want most is root jurisdiction , If the process is implanted with a Trojan virus or the like , If you control the process, you have root jurisdiction . So any command goes through root It is a very dangerous thing to carry out . So from a security point of view , Follow the principle of minimum authority , That is, the system is required to grant only the necessary permissions to the principal , Don't over authorize , This can effectively reduce the system 、 The Internet 、 application 、 Opportunities for database errors . therefore Linux In the system , A good practice is to log in with a normal account , In execution, you need root When operating with permission , Re pass sudo Command complete . This can minimize the risk caused by some misoperation ; At the same time, after the ordinary account is stolen , And root The consequences of account theft are completely different . stay Ansible There are many fine-grained methods for raising rights in , Optional rights can be raised according to needs , Different rights raising strategies are used to configure rights raising .

Choose the appropriate method of raising rights

When the task is performed , Especially in use ansible Handle some cases of batch initialization of cluster nodes , Most of them need to be handled with power , When choosing how to control the delegation of rights , Where to raise the right , We need to consider the following requirements :

  • To make Playbook Try to keep it simple , Not because of the right to deal with , Increase the complexity of the script , The variable parts are managed uniformly , Lifting the right to deal with unified constraints .  If it is too complex, consider layering . It is necessary to propose the right script task and consider grouping, layering and independent management , Use group variables to control the lifting of weights , Or separate ansibler If the complexity of the script is considered in character processing 、 Read only , Configuration files are available , Command line method to raise authority . If different hosts of the same script need different rights , Can pass ansible Connect variables (ansible_*) To control the lifting of power .
  • Run the task with minimum privileges to avoid accidental damage and damage to the managed host due to script errors .

Sometimes we just use root User to connect the managed machine , To avoid privilege escalation . But in the production environment , This is usually not a good practice ; If anyone who runs a script uses root To connect to the management host . This also makes it difficult to determine which O & M has executed which script . It's easy to carry the pot . But the experimental environment or test environment can be used like this . A good practice is to selectively control which games or quests require privilege escalation . for example , If apache The user can start httpd The server , There is no need to root User run . Ideally , Configure escalation in the simplest possible way , And it should be clear whether it is used for tasks .

Power raising strategy

Ansible Playbook Rights can be raised at many different levels . Common methods of raising rights :

  • Configuration file and command line authorization
  • Right in the script
  • Lifting weight in a block
  • Delegate authority in the task
  • In the role
  • Connection variable configuration authorization

Configuration file and command line authorization

Configuration file authorization

If you will Ansible In the configuration file  privilege_escalation  In section become Boolean set to  yes/True, be Playbook All in Play Will default to the use of the right to lift .

[privilege_escalation]
become=True
become_method=sudo
become_user=root
become_ask_pass=False

When running on a managed host , these Play The current... Will be used become_method To switch between the current user and the current user  become_user user . You can see that the authorized user after configuration is root

┌──[[email protected]:]-[~/ansible]
└─$ansible all -m command -a id
vms81.liruilongs.github.io | CHANGED | rc=0 >>
uid=0(root) gid=0(root)  Group =0(root)

When put become Set to false when , We observe , No right has been raised , Instead, use ordinary users liruilongs Connect

┌──[[email protected]]-[~/ansible]
└─$ansible all -m command -a id
vms82.liruilongs.github.io | CHANGED | rc=0 >>
uid=1003(liruilong) gid=1003(liruilong)  Group =1003(liruilong)
┌──[[email protected]]-[~/ansible]
└─$

Raise authority through the command line

When using the command line option to execute Playbook when , You can also overwrite the configuration file and specify the authorization settings . The following table compares the configuration instructions with the command line . Options :

Profile parameters   Command line arguments  

become --become / -b become_method --become-method=BECOME_METIHOD become_user --become-user=BECOME_USER become_password --ask-become-pass /-K

If Ansible The configuration file specifies  become: false, But the command line contains -b Options , be Ansible The configuration file... Will be ignored , And the default use of the right to lift . That is, the command line method is higher than the configuration file extraction

┌──[[email protected]]-[~/ansible]
└─$cat ansible.cfg
[defaults]
#  Host manifest file , Is the list of hosts to control 
inventory=inventory
#  The user name of the remote connection to the managed machine 
remote_user=liruilong
#  Role catalog 
roles_path=roles
#  Set the user's su  Raise the right 
[privilege_escalation]
become=False
#become_method=sudo
#become_user=root
#become_ask_pass=False

Don't use the command line

┌──[[email protected]]-[~/ansible]
└─$ansible all -m command -a id
vms82.liruilongs.github.io | CHANGED | rc=0 >>
uid=1003(liruilong) gid=1003(liruilong)  Group =1003(liruilong)

Use the right raising command

┌──[[email protected]]-[~/ansible]
└─$ansible all -m command -a id -b
vms82.liruilongs.github.io | CHANGED | rc=0 >>
uid=0(root) gid=0(root)  Group =0(root)

That is, the authorization of the command line is higher than that of the configuration file

Play The rights in the script

If Play It does not specify whether to use the right of withdrawal , The default is not to mention the right , Will use the default settings in the configuration file or the command line .ansible_user_id Used to display the user of the current operation

---
- name: Become the user "manager"
  hosts: all
  tasks:
    - name: Show the user used by this play
      debug:
        var: ansible_user_id

It can be found that the right has not been raised

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook becomet.yaml

PLAY [Become the user "manager"] ***********************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [Show the user used by this play] *****************************************************************
ok: [vms82.liruilongs.github.io] => {
    "ansible_user_id": "liruilong"
}

PLAY RECAP *********************************************************************************************
vms82.liruilongs.github.io : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Each... Can be specified explicitly Play Whether to use the right of withdrawal . Through the script become: true The way

- name: Become the user "manager"
  hosts: webservers
  become: true
  tasks:
  - name: Show the user used by this play
    debug:
      var: ansible_user_id

Default not to mention the right , After configuration, you can implement the right lifting , That is, the script should be authorized higher than the default configuration

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook become.yaml

PLAY [Become the user "manager"] ***********************************************************************

TASK [Gathering Facts] *********************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [Show the user used by this play] *****************************************************************
ok: [vms82.liruilongs.github.io] => {
    "ansible_user_id": "root"
}

PLAY RECAP *********************************************************************************************
vms82.liruilongs.github.io : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Delegation of authority in the task

Or just for Play Turn on or off delegation of authority for a task in

---
- name: Become the user "manager"
  hosts: all
  become: false
  tasks:
    - name: tasks sudo 1
      become: true
      yum:
        name: httpd
        state: installed
    - name: tasks sudo 2
      yum:
        name: nginx
        state: installed

Task 2 has no right , Remind us that we need root To execute an order

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook become.yaml

PLAY [Become the user "manager"] ***************************************************************************************

TASK [Gathering Facts] *************************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [tasks sudo 1] ****************************************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [tasks sudo 2] ****************************************************************************************************
fatal: [vms82.liruilongs.github.io]: FAILED! => {"changed": false, "changes": {"installed": ["nginx"]}, "msg": "You need to be root to perform this command.\n", "rc": 1, "results": ["Loaded plugins: fastestmirror\n"]}

PLAY RECAP *************************************************************************************************************
vms82.liruilongs.github.io : ok=2    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

block Lifting weight in block

If Play There are some tasks that need ( Or not ) Raise the right , Can be in  block Set up become. There's a little bit of caution here , stay block If the right is raised in the middle , The parameter of lifting weight can only be placed at the end of the task , Cannot be placed in the first position of the task . The following is not correct , Can report grammatical errors

---
- name: Become the user "manager"
  hosts: all
  become: false
  tasks:
   - block:
     become: true
     - name: tasks sudo 1
       become: false
       yum:
         name: tomcat
         state: installed
     - name: tasks sudo 2
       yum:
         name: nginx
         state: installed

That is, the following expression is correct

---
- name: Become the user "manager"
  hosts: all
  become: false
  tasks:
   - block:
     - name: tasks sudo 1
       become: false
       yum:
         name: tomcat
         state: installed
     - name: tasks sudo 2
       yum:
         name: nginx
         state: installed
     become: true

Let's have a look , install tomcat need root jurisdiction , Although we are block The right has been raised , But set not to mention the right in the task , So it will be covered .

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook become-block.yaml

PLAY [Become the user "manager"] *********************************************************************
TASK [Gathering Facts] *******************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [tasks sudo 1] **********************************************************************************
fatal: [vms82.liruilongs.github.io]: FAILED! => {"changed": false, "changes": {"installed": ["tomcat"]}, "msg": "You need to be root to perform this command.\n", "rc": 1, "results": ["Loaded plugins: fastestmirror\n"]}

PLAY RECAP *******************************************************************************************
vms82.liruilongs.github.io : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

┌──[[email protected]]-[~/ansible]
└─$

modify yaml After the document , Let's take a look at , By default , When block Right lifting is set in , So by default ,block All tasks in the block are in the status of raising rights

┌──[[email protected]]-[~/ansible]
└─$cat become-block.yaml
---
- name: Become the user "manager"
  hosts: all
  become: false
  tasks:
   - block:
     - name: tasks sudo 1
       become: trueb
       yum:
         name: tomcat
         state: installed
     - name: tasks sudo 2
       yum:
         name: nginx
         state: installed
       become: false
     become: true

You can see Tomcat Installed successfully , however nginx Installation failed , Tips need to be root jurisdiction , Because we're right yum The module is set to not mention the right become: false, That is for block Right in , The specific module in the task should be higher than block The right to raise

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook become-block.yaml

PLAY [Become the user "manager"] *********************************************************************

TASK [Gathering Facts] *******************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [tasks sudo 1] **********************************************************************************
changed: [vms82.liruilongs.github.io]

TASK [tasks sudo 2] **********************************************************************************
fatal: [vms82.liruilongs.github.io]: FAILED! => {"changed": false, "changes": {"installed": ["nginx"]}, "msg": "You need to be root to perform this command.\n", "rc": 1, "results": ["Loaded plugins: fastestmirror\n"]}

PLAY RECAP *******************************************************************************************
vms82.liruilongs.github.io : ok=2    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

┌──[[email protected]]-[~/ansible]
└─$

Raising authority in the role

Roles can perform delegation in two basic ways : For the role itself , Set the escalation variable inside or for its task . Not much here , There are too many ways , In the role, you can use variables or directly task List your main.yaml The right shall be mentioned in the document . Role play , Create a user :

---
# tasks file for become_demo
- name: become roles  Demo
  debug:
    var: ansible_user_id
- user:
    name: liruilong1
    state: present
~   

Call the role play

┌──[[email protected]]-[~/ansible]
└─$cat become_roles_demo.yaml
---
- hosts: all
  roles:
    - role: become_demo

Creating users requires root jurisdiction , So the execution error report

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook become_roles_demo.yaml

PLAY [all] *******************************************************************************************

TASK [Gathering Facts] *******************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [become_demo : become roles  Demo] **************************************************************
ok: [vms82.liruilongs.github.io] => {
    "ansible_user_id": "liruilong"
}

TASK [become_demo : user] ****************************************************************************
fatal: [vms82.liruilongs.github.io]: FAILED! => {"changed": false, "cmd": "/sbin/useradd -m liruilong1", "msg": "[Errno 13] Permission denied", "rc": 13}

PLAY RECAP *******************************************************************************************
vms82.liruilongs.github.io : ok=2    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

Modify the role task execution file , Add rights

┌──[[email protected]]-[~/ansible]
└─$cat roles/become_demo/tasks/main.yml
---
# tasks file for become_demo
- name: become roles  Demo
  debug:
    var: ansible_user_id
- user:
    name: liruilong1
    state: present
  become: true

Users can be created by normal authorization .

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook become_roles_demo.yaml

PLAY [all] *******************************************************************************************

TASK [Gathering Facts] *******************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [become_demo : become roles  Demo] **************************************************************
ok: [vms82.liruilongs.github.io] => {
    "ansible_user_id": "liruilong"
}

TASK [become_demo : user] ****************************************************************************
changed: [vms82.liruilongs.github.io]

PLAY RECAP *******************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

We can also do that  Ansible Configuration or  Playbook  Specify this information in .

┌──[[email protected]]-[~/ansible]
└─$cat roles/become_demo/tasks/main.yml
---
# tasks file for become_demo
- name: become roles  Demo
  debug:
    var: ansible_user_id
- user:
    name: liruilong2
    state: present

Here we modify and call the script file , Right raising

┌──[[email protected]]-[~/ansible]
└─$cat become_roles_demo.yaml
---
- hosts: all
  roles:
    - role: become_demo
      become: true

User created successfully

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook become_roles_demo.yaml

PLAY [all] *******************************************************************************************

TASK [Gathering Facts] *******************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [become_demo : become roles  Demo] **************************************************************
ok: [vms82.liruilongs.github.io] => {
    "ansible_user_id": "liruilong"
}

TASK [become_demo : user] ****************************************************************************
changed: [vms82.liruilongs.github.io]

PLAY RECAP *******************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Let's finally take a look at the managed machine

┌──[[email protected]]-[~/ansible]
└─$ansible all -m shell -a "grep liruilong  /etc/passwd "
vms82.liruilongs.github.io | CHANGED | rc=0 >>
liruilong:x:1003:1003::/home/liruilong:/bin/bash
liruilong1:x:1006:1006::/home/liruilong1:/bin/bash
liruilong2:x:1007:1007::/home/liruilong2:/bin/bash
┌──[[email protected]]-[~/ansible]
└─$

Use variables to carry out weight raising

Of course, we can also use variables to configure the lifting weight . These variables can be applied as manifest variables to groups or individual hosts . The following table will  Playbook  And configuration instructions and connection variable names : The so-called connection variable , namely ansible When connecting the managed machine, the variables related to the connection will be assigned . There are default values by default , We can also take the initiative to modify . Profile parameters   Connect variable parameters :

become ansible_become become_method ansible_become_method become_user ansible_become_user become_password ansible_become_pass

Variables can be defined in many ways , Interested friends can see my previous blog , Let's simply look at a few

Set connection variables at the host group level

webservers: 
  hosts: 
    servera.lab.example.com:
    serverb.lab.example.com: 
  vars: 
     ansible_become: true

Come and have a look at Demo, add to all Group variable ansible_become: true

┌──[[email protected]]-[~/ansible]
└─$echo "ansible_become: true" > inventory/group_vars/all
┌──[[email protected]]-[~/ansible]
└─$vim roles/become_demo/tasks/main.yml

The role behavior is to delete the user just created

┌──[[email protected]]-[~/ansible]
└─$cat  roles/become_demo/tasks/main.yml
---
# tasks file for become_demo
- name: become roles  Demo
  debug:
    var: ansible_user_id
- user:
    name: liruilong2
    state: absent

Role deleted successfully , That is to say, the right is raised by connecting variables

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook become_roles_demo.yaml

PLAY [all] *******************************************************************************************

TASK [Gathering Facts] *******************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [become_demo : become roles  Demo] **************************************************************
ok: [vms82.liruilongs.github.io] => {
    "ansible_user_id": "root"
}

TASK [become_demo : user] ****************************************************************************
changed: [vms82.liruilongs.github.io]

PLAY RECAP *******************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Set connection variables at the host level

webservers: 
  hosts: 
    servera.lab.example.com: 
      ansible_become: true 
    serverb.lab.example.com:

Same way , Here, we set the group variable to no weight , The host variable is lifting .

┌──[[email protected]]-[~/ansible]
└─$echo "ansible_become: false" > inventory/group_vars/all
┌──[[email protected]]-[~/ansible]
└─$echo "ansible_become: true" >  inventory/host_vars/vms82.liruilongs.github.io.yaml

The role behavior is to delete users

┌──[[email protected]]-[~/ansible]
└─$cat roles/become_demo/tasks/main.yml
---
# tasks file for become_demo
- name: become roles  Demo
  debug:
    var: ansible_user_id
- user:
    name: liruilong1
    state: absent

The user was deleted successfully , That is, the priority of host variables should be greater than that of group variables

┌──[[email protected]]-[~/ansible]
└─$ansible-playbook become_roles_demo.yaml

PLAY [all] *******************************************************************************************

TASK [Gathering Facts] *******************************************************************************
ok: [vms82.liruilongs.github.io]

TASK [become_demo : become roles  Demo] **************************************************************
ok: [vms82.liruilongs.github.io] => {
    "ansible_user_id": "root"
}

TASK [become_demo : user] ****************************************************************************
changed: [vms82.liruilongs.github.io]

PLAY RECAP *******************************************************************************************
vms82.liruilongs.github.io : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Of course, we can also be in Playbook Set connection variables in

- name: Example play using connection variables
  hosts: webservers
  vars:
    ansibte_become: true
  tasks:
    - name: Play will use privilege escalation even if inventory says no
      yum:
        name: httpd
        state: installed

Refer to blog books

  • 《Red Hat Ansible Engine 2.8 DO447》
  • 《 White hat speak Web Security 》
  • https://docs.ansible.com/ansible/latest/user_guide/become.html
  • https://docs.ansible.com/ansible/latest/user_guide/playbooks_blocks.html
原网站

版权声明
本文为[Technology d life]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222134340893.html