当前位置:网站首页>Ansible best practices playbook different context rights raising demo
Ansible best practices playbook different context rights raising demo
2022-06-29 04:00:00 【The mountains and rivers are all right】
Write it at the front
- Life cheer , Today, I'd like to share some with my friends Ansible Notes on raising rights
- The content of the blog involves
- How to choose Ansible Right raising method
- What are the strategies for raising rights
- The strategy of raising rights is specific Demo
- How to eat :
- Need to have Ansible Basics , understand Ansible Use of variables
- If you don't understand enough, please help me correct
- In recent days, there are both wind and cloud in Inner Mongolia , It's just a little hot , Where are you
^_^
In the evening , You sit under the eaves , Watching the sky slowly darken , My heart is lonely and desolate , Feel deprived of your life . I was a young man , But I'm afraid to live like this , Aging goes on . in my opinion , This is more terrible than death .-------- Wang Xiaobo
Ansible Control right
ansible edition
┌──[[email protected]]-[~/ansible]
└─$ansible --version
ansible 2.9.25
config file = /root/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
For beginners ansible My little friend will , The allocation of rights is mostly through configuration ansible.cfg The way to Allocation and right raising , 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 is Have 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 A lot of A fine-grained method of raising rights , You can have... As needed The right to choose , Through different Power raising strategy To configure the right lifting .
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
PlaybookTry 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 Role processing
- If you consider the complexity of the script 、 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
Power raising strategy Demo
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
vms82.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 liruilong 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 , It's fine too Overwrite profile And designate Authorization settings . The following table compares Configure instructions and command lines
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 To configureorPlaybookSpecify 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 instruction and connection variable name Compare :
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
stay Host group Set connection variables in 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
stay host Set connection variables in 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
边栏推荐
- 科班出身,结果外包都不要
- Ask the handler about the memory leak scenario in the interview. Don't just know static internal classes & weak references!
- The efficiency of 20 idea divine plug-ins has been increased by 30 times, and it is necessary to write code
- PostgreSQL 出现cross-database references are not implemented的bug
- 88. (cesium chapter) cesium aggregation diagram
- sink端 一般都是jdbc的insert update delete么?
- Seekbar custom pictures are not displayed completely up, down, left, right / bitmaptodrawable / bitmaptodrawable inter rotation / paddingstart/paddingend /thumboffset
- SQL performance optimization is really eye popping
- 【C语言】开启一个线程
- c语言 --- 分支结构
猜你喜欢

Distributed ID solution

女程序员晒出5月的工资条:工资是高,但是真累,网友评论炸锅了

在命令行登录mysql数据库以及查看版本号

leetcode - 295. 数据流的中位数

VG4131SxxxN0S1无线模块硬件规格书

Technology: how to design zkvm circuit

Influence of air resistance on the trajectory of table tennis

开发者方案 · 环境监测设备(小熊派物联网开发板)接入涂鸦IoT开发平台

Common methods of JS date and time

干货丨微服务架构是什么?有哪些优点和不足?
随机推荐
在命令行登录mysql数据库以及查看版本号
How to merge upstream and downstream SQL data records
Do you feel confused when you study at three in the morning?
Distributed ID solution
Draft competition process of Intelligent Vision Group
要不是和阿里P7聊过,我也不知道自己是个棒槌
Libuv库概述及libevent、libev、libuv对比(转载)
Qtableview gets all currently selected cells
Data collection and management [10]
Common methods of JS date and time
Technology cloud report: side B of mixed office: how to have both security and efficiency?
20款IDEA 神级插件 效率提升 30 倍,写代码必备
你为什么做测试/开发程序员?还能回想出来吗......
4种分布式session解决方案
SQL two columns become multi row filter display
女程序员晒出5月的工资条:工资是高,但是真累,网友评论炸锅了
【滤波器设计】根据设计指标使用matlab定制滤波器
New listing of operation light 3.0 -- a sincere work of self subversion across the times
Devops note-05: what are the roles of Ba, SM, Po, PM, PD, dev, OPS and QA in the IT industry
[tcapulusdb knowledge base] modify business modify cluster