Ansible automation operation and maintenance II

Posted by joozt on Tue, 18 Jan 2022 02:28:34 +0100

1. Manage Ansible configuration files

Ansible configuration file

Customize ansible installation behavior by modifying ansible's configuration file. Ansible configuration files can exist in multiple locations, and different configuration files can be used according to different situations.

Use / etc / ansible / ansible cfg
​ /etc/ansible/ansible.cfg is the default configuration file. If no other configuration file can be found, this file will be used by default when the ansible command is executed.

Use/ ansible.cfg
When executing the ansible command, if ansible. Exe exists in the current directory Cfg file, ansible will use ansible. In the current directory Cfg file instead of ansible's default configuration file.

Use ~ / ansible.cfg
When the ansible command is executed, if ansible.exe does not exist in the current directory Cfg file, it will be found in the user's home directory ansible.cfg file. If this configuration file exists in the home directory, the configuration file in the user's home directory will be used ansible.cfg configuration file.

Use ANSIBLE_CONFIG environment variable
The location of the configuration file is defined through the environment variable. After definition, the configuration file defined by the environment variable will be used by default regardless of the location, and none of the above-mentioned configuration files will be used.

[root@server ~]# export ANSIBLE_CONFIG=/tmp/ansible.cfg
[root@server ~]# ansible --version
ansible 2.9.23
  config file = /tmp/ansible.cfg	##You can see that the profile path used has changed
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Dec  3 2020, 18:11:24) [GCC 8.4.1 20200928 (Red Hat 8.4.1-1)] 

The recommended practice is to create ansible. Exe in the directory where the ansible command needs to be run Cfg file, and create files to be used in this directory, such as managed host list and playbook. This makes it easier to manage hosts of different projects.

Profile priority

​ ANSIBLE_CONFIG > ./ansible.cfg > ~/.ansible.cfg > /etc/ansible/ansible.cfg

​ ANSIBLE_ Any file specified by the config environment variable overwrites all other configuration files. If the environment variable is not set, it will look for the directory where the ansible command is executed to see if ansible exists Cfg file. If the configuration file does not exist in the directory where the ansible command is executed, check whether there is * * in the user's home directory ansible.cfg file. The default / etc / ansible / ansible. Is used only if no other configuration file can be found CFG * * configuration file

We can execute the following command to see which configuration file is currently used

[root@server ~]# ansible --version
ansible 2.9.23
  config file = /etc/ansible/ansible.cfg	##This line displays the currently used configuration file
  configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.6.8 (default, Dec  3 2020, 18:11:24) [GCC 8.4.1 20200928 (Red Hat 8.4.1-1)]

Manage settings in profiles

The Ansible configuration file consists of several parts, each containing settings defined in the form of key value pairs. The title of the section is enclosed in square brackets.

The modification of basic operation has two parts:

​ 1. The [defaults] section sets the default value of Ansible operation

​ 2. [privilege_escalation] configure how Ansible performs privilege escalation on the managed host

[defaults]				##General default configuration
#inventory      = /etc/ansible/hosts			##Specify the path to the manifest file
#library        = /usr/share/my_modules/		##Path of module
#module_utils   = /usr/share/my_module_utils/	##Path to module tool
#remote_tmp     = ~/.ansible/tmp		##Specifies the path for remote execution
#local_tmp      = ~/.ansible/tmp		##Execution path of management node
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml	
#forks          = 5			##The number of managed hosts for parallel processing can be determined according to the performance of the control host and the number of managed nodes
#poll_interval  = 15		##Polling interval
#sudo_user      = root		##The default user used by sudo is root by default
#ask_sudo_pass = True		##Does the user need to enter sudo password
#ask_pass      = True		##Do you need the user to enter the connection password
#transport      = smart		##Communication mechanism
#remote_port    = 22		##Specify the management port to connect to the peer node. The default is 22, unless a special SSH port is set
#remote_user    = root      ##Specifies the user who is executed by the managed host. The default is root
#module_lang    = C			##The default is the computer language for communication between the module and the system. The default is' C '
#module_set_locale = False
#host_key_checking = False   		    ##Check remote host key
#sudo_exe = sudo         			##sudo remote execution command
#sudo_flags = -H -S -n    		   ##Pass parameters other than sudo
#timeout = 10           			 ##SSH timeout
#remote_user = root      			##Remote login user name
#log_path = /var/log/ansible.log     ##Log file storage path
#module_name = command      			 ##The Ansible command is executed by default
#executable = /bin/sh       				 ##Shell environment for execution, user shell module
#hash_behaviour = replace   				 ##Specific priority override variables
#jinja2_extensions = jinja2.ext.do,jinja2.ext.i18   	 ##Allow to open jinja2 extension module
#private_key_file = /path/to/file   			 ##Private key file storage location
#display_skipped_hosts = True	       		 ##Displays the status of skipping any task
#system_warnings = True    	 			 ##Disable system running Ansible potential problem warnings
#deprecation_warnings = True     		##PlayBook output disables the "not recommended" warning
#command_warnings = False    			##The command module Ansible issues a warning by default
#nocolor = 1         				##The output band has color difference. 0 means on and 1 means off
#pipelining = False    	 			 ##Enable pipe SSH channel optimization

Let the managed host operate using the tom user

##Modify the ansible configuration file first
[root@server ansible]# vim /etc/ansible/ansible.cfg
# default user to use for playbooks if user is not specified
# (/usr/bin/ansible will use current user as default)
#remote_user = root
remote_user = tom		##Find this line, copy it, and change the user to tom

##The managed host does not create a tom user to see the effect. If it finds no user, it will report an error
[root@server ansible]# ansible 192.168.10.201 -m ping 
192.168.10.201 | UNREACHABLE! => {
    "changed": false,
    "msg": "Invalid/incorrect password: Permission denied, please try again.",
    "unreachable": true
}
[root@server ansible]#
##Then create a tom user and find that you can communicate
[root@client ~]# useradd tom	##Create tom user for managed host
[root@server ansible]# ansible 192.168.10.201 -m ping 
192.168.10.201 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
[root@server ansible]#

Let the tom user use sudo to execute commands

##First, add sudo permission of tom user on the managed host
[root@client ~]# visudo
## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL
tom     ALL=(ALL)       ALL		##Find this line and add sudo permission of tom user

##Then modify the ansible configuration file
[root@server ansible]# vim /etc/ansible/ansible.cfg
[privilege_escalation]
become=True						##Find these lines and delete the comment
become_method=sudo
become_user=root
become_ask_pass=False
##Then, in the manifest file, add the sudo password of the managed host user tom after the managed host
[root@server ansible]# vim /etc/ansible/inventory
192.168.10.201  ansible_sudo_pass=1
##Then execute the command and find that you have permission to create
[root@server ~]# ansible 192.168.10.201 -a "touch /root/123"
[WARNING]: Consider using the file module with state=touch rather than running 'touch'.
If you need to use command because file is insufficient you can add 'warn: false' to this
command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
192.168.10.201 | CHANGED | rc=0 >>

[root@server ~]#

2. Use of ansible module

Viewing module help documents

ansible has thousands of plug-ins and modules, which can manage various software, platforms and versions, and support multi-level deployment of virtual containers.

You can view the help documentation for ansible modules and plug-ins with the following command

[root@server ~]# ansible-doc -l
a10_server                                                    Manage A10 Networks AX/...
a10_server_axapi3                                             Manage A10 Networks AX/...
a10_service_group                                             Manage A10 Networks AX/...
a10_virtual_server                                            Manage A10 Networks AX/...
aci_aaa_user                                                  Manage AAA users (aaa:U...
aci_aaa_user_certificate                                      Manage AAA user certifi...
############################Slightly
[root@server ~]# ansible-doc -l |grep user  ##You can use filtering
aci_aaa_user                                                  Manage AAA users (aaa:U...
aci_aaa_user_certificate                                      Manage AAA user certifi...
avi_cloudconnectoruser                                        Module for setup of Clo...
avi_user                                                      Avi User Module        
avi_useraccount                                               Avi UserAccount Module 
avi_useraccountprofile                                        Module for setup of Use...
bigip_apm_acl                                                 Manage user-defined APM...
#############################Slightly

You can also view help documents directly on the official website

Use of user module

The user module is used to manage the user account of the controlled machine.

##Add a system user on the controlled machine. The user name is apache, uid is 306, and its shell is set to / sbin/nologin. There is no home directory
[root@server ~]# ansible 192.168.10.201 -m user -a "name=apache uid=306 shell=/sbin/nologin create_home=no"
192.168.10.201 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "comment": "",
    "create_home": false,
    "group": 1002,
    "home": "/home/apache",
    "name": "apache",
    "shell": "/sbin/nologin",
    "state": "present",
    "system": false,
    "uid": 306
}
[root@server ~]#
##Then check the managed host to see if the creation was successful
[root@client ~]# grep apache  /etc/passwd
apache:x:306:1002::/home/apache:/sbin/nologin
[root@client ~]# ls /home/
abc
[root@client ~]#
##Modify the uid of apache user to 399
[root@server ~]# ansible 192.168.10.201 -m user -a "name=apache uid=399"
192.168.10.201 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "append": false,
    "changed": true,
    "comment": "",
    "group": 1002,
    "home": "/home/apache",
    "move_home": false,
    "name": "apache",
    "shell": "/sbin/nologin",
    "state": "present",
    "uid": 399
}
[root@server ~]#
##Then check whether the modification is successful in the managed host
[root@client ~]# id apache 
uid=399(apache) gid=1002(apache) groups=1002(apache)
[root@client ~]#
##Delete apache user on managed host
[root@server ~]# ansible 192.168.10.201 -m user -a "name=apache state=absent"
192.168.10.201 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "force": false,
    "name": "apache",
    "remove": false,
    "state": "absent"
}
[root@server ~]#
##Then check the managed host to see if the deletion was successful
[root@client ~]# id apache 
id: 'apache': no such user
[root@client ~]#

This is the use of the user module

Topics: Linux