Introduction to Ansible series (9 kinds) commands

1. Execution process of ansible command

  1. Load your own configuration file. The default is / etc / ansible / ansible cfg
  2. Load the corresponding module file, such as command
  3. Generate the corresponding temporary py file from the module command through ansible, and transfer the file to the corresponding executing user $home / Ansible / TMP / ansible TMP digital / xxx Py file
  4. Execute for file + x
  5. Execute and return results
  6. Delete temporary py files, sleep 0 exit

Execution status of ansible

root@ubuntu20:~# grep -A 14 '\[colors\]' /etc/ansible/ansible.cfg
[colors]
#highlight = white
#verbose = blue
#warn = bright purple
#error = red
#debug = dark gray
#deprecate = purple
#skip = cyan
#unreachable = red
#ok = green
#changed = yellow
#diff_add = green
#diff_remove = red
#diff_lines = cyan

root@ubuntu20:~#
  • Green: perform operations that are successful and do not require changes

  • Yellow: the execution is successful and changes are made to the target host

  • Red: execution failed

2. Ansible series commands

header 1header 2
/usr/bin/ansibleMain program, temporary command execution tool
/usr/bin/ansible-docView the configuration document and the module function viewing tool, which is equivalent to man
/usr/bin/ansible-playbookCustomize automatic tasks and arrange script tools, which is equivalent to scripts
/usr/bin/ansible-galaxyDownload / upload excellent code or official website platform of Roles module
/usr/bin/ansible-pullTools for remote command execution
/usr/bin/ansible-vaultFile encryption tool
/usr/bin/ansible-consoleExecution tool based on Console interface and user interaction
/usr/bin/ansible-configView, edit and manage the configuration file of ansible
/usr/bin/ansible-inventoryView the details of the host list of the controlled end

The main way to realize management by using ansible

  • Ansible ad hoc uses the ansible command, which is mainly used in the use scenario of temporary commands

  • Ansible playbook is mainly used for long-term planned and large-scale project scenarios, which requires a preliminary planning process

ansible preparation before use

ansible related tools mostly realize the functions of remote host configuration management, application deployment, task execution and so on through ssh protocol

Suggestion: before using this tool, configure ansible. The master can contact each managed node based on key authentication

2.1 ansible (ansible commands are mainly used in conjunction with modules)

Ansible implements configuration management, application deployment, task assignment and other functions through ssh. It is recommended that the ansible end can contact each managed node based on secret key authentication

Ansible is the main tool for the implementation of ansible ad hoc

format

ansible <host-pattern> [-m module_name] [-a args]

option

header 1header 2
-aSpecify the parameters of the module
–versionDisplay version
-f FORKS, --forks FORKSHow many fork processes are processed concurrently? The default is 5
-m moduleSpecify the module to use. The default is command
-vView the detailed process of execution (- vv, - vvv more detailed)
-iSpecify the path to the hosts file. The default is: / etc/ansible/hosts
-ISpecify pattern and filter the matched hosts again
–list-hostsDisplay host list (can be abbreviated as – list)
For example: ansible all --list
-k,–ask-passPrompt for ssh connection password. key authentication is used by default
-K,–ask-become-passPrompt for sudo password
-C,–checkCheck, not execute
-cSet connection type (default=smart)
-T,–timeout=TIMEOUTThe timeout for executing the command, which is 10s by default
-tThe log is output to this directory, and the log file name is named after the host
-u,–user=REMOTE_USERSpecify the execution user of remote execution. If no user is specified, the current user identity will be used
-UWhich user sudo to, the default is root
-b,–becomeReplace the old version of sudo switch
–become-user=USERNAMESpecify the runas user of sudo. The default is root
-h,–helpdisplay help information
-ssudo run
-oCompressed output

Examples

# vim color
echo export EDITOR=vim >> /etc/profile.d/env.sh
source /etc/profile.d/env.sh

Examples

# Add sudo permission
visudo
%wheel ALL=(ALL) NOPASSWD:ALL

#Will op_biz joins the wheel group and maintains the original primary group permissions
usermod -aG wheel op_biz
ansible dbserv -m command -a 'ls /root' -u op_biz -k -b

# key based authentication
ssh-keygen
ssh-copy-id 10.134.115.56
ansible all -m ping

Ansible host pattern

List of hosts used to match controlled

ALL: indicates ALL hosts in ALL inventories

Example:

ansible all -m ping

*: wildcard

ansible "*" -m ping
ansible 192.168.1.* -m ping
ansible "*srvs" -m ping
ansible "10.0.0.11 10.0.0.12" -m ping

Or relationship

ansible "web:app" -m ping
ansible "192.168.1.10:192.168.1.20" -m ping
ansible "web:app" --list-hosts

Logic and

# Hosts in the web group and in the db group
ansible "web:&db" -m ping

Logical non

# Hosts in the web group but not in the db group
# Note that this is a single quotation mark
ansible 'web:!db' -m ping 

Integrated logic

ansible 'web:db:&app:!ftp' -m ping 

regular expression

ansible "web:&db" -m ping
ansible "~(web|db)srvs" -m ping
ansible "~(web|db).*\.test\.com" -m ping

Example: all machines that contain kube and etcd and do not contain native (10.0.0.11) perform the restart operation

ansible 'kube*:etcd:!10.0.0.11' -a reboot && reboot

Examples

root@ubuntu20:~# cat /etc/ansible/hosts
[web]
10.0.0.15
10.0.0.11
[db]
10.0.0.15
10.0.0.16
[app]
10.0.0.11
10.0.0.12
root@ubuntu20:~# ansible all  --list-hosts
  hosts (4):
    10.0.0.15
    10.0.0.11
    10.0.0.16
    10.0.0.12
root@ubuntu20:~# ansible web  --list-hosts
  hosts (2):
    10.0.0.15
    10.0.0.11
root@ubuntu20:~# ansible app  --list-hosts
  hosts (2):
    10.0.0.11
    10.0.0.12
root@ubuntu20:~#
root@ubuntu20:~# ansible "app:web"  --list-hosts
  hosts (3):
    10.0.0.11
    10.0.0.12
    10.0.0.15
root@ubuntu20:~# ansible "app:&web"  --list-hosts
  hosts (1):
    10.0.0.11
root@ubuntu20:~#

# quote! Do not use double quotation marks, but single quotation marks
root@ubuntu20:~# ansible "app:!db"  --list-hosts
-bash: !db: event not found
root@ubuntu20:~# ansible 'app:!db'  --list-hosts
  hosts (2):
    10.0.0.11
    10.0.0.12
root@ubuntu20:~#

Example: concurrent execution control

# Execute the following two commands to observe the results
root@ubuntu20:~# ansible web -a 'sleep 3' -f10
10.0.0.11 | CHANGED | rc=0 >>

10.0.0.15 | CHANGED | rc=0 >>

root@ubuntu20:~# ansible web -a 'sleep 3' -f1
10.0.0.15 | CHANGED | rc=0 >>

10.0.0.11 | CHANGED | rc=0 >>

root@ubuntu20:~#

2.2 ansible doc (display module help)

Ansible doc: check the documentation of ansible module (plug-in). There are detailed usage instructions for each module. The function is similar to the man command of Linux

format

ansible-doc [-l|-F|-s] [options] [-t <plugin type> ] [plugin]

-l, --list       # List available modules
-s, --snippet    # Displays the playbook fragment of the specified module

view help

root@ubuntu20:~# ansible-doc --help

option

header 1header 2
-a, --allDisplay documents for all modules
-h, --helpdisplay help information
-j, --jsonDump all modules into JSON format
-l, --listList available modules
-F, --list_filesDisplays the name of the module and the original path of the module
-M MODULE_PATH, --module-path=MODULE_PATHModule path
-s, --snippetDisplays the playbook fragment of the specified module
-t TYPE, --type=TYPESpecify the module type (the default is module)
-v, --verboseView the detailed process of execution (- vv, - vv more detailed)
–versionView version

Examples

ansible-doc -l        # List all modules, ansible doc - L | grep ZABBIX
ansible-doc ping      # View the help usage of the specified module
absible-doc -s ping   # View the help usage of the specified module
ansible-doc file      # Check the usage of the file module. Although chown can also be used, it does not have security and idempotency

Example: view the specified plug-in

ansible-doc -t connection -l
ansible-doc -t lookup  -l

2.3 ansible-playbook

A playbook is a list of one or more 'plays'
The main function of play is to dress up the hosts whose implementations are merged into a group as the roles defined in advance through the task in ansible. Fundamentally, the so-called task is nothing more than calling a module in ansible.
By organizing multiple plays in one playbook, they can work together according to the pre arranged mechanism.
Playbook is written in YAML language

# Syntax: ansible playbook [options] playbook yml [playbook2 ...]
# options: 
# Most of the parameters are consistent with those of ansible

Examples

cat uptime.yml
---	
- hosts: web
  remote_user: root
  gather_facts: no
  
  tasks: 
    - name: run time
      command: uptime
      
ansible-playbook uptime.yml

2.4 ansible-galaxy

Galaxy is a free website, similar to github, which publishes a lot of shared roles.

Ansible provides an ansible Galaxy command line tool connection https://galaxy.ansible.com Download the corresponding roles from the website and perform init, search, install, remove and other operations.

grammar

ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ...

option

header 1header 2
-h, --helpView help information
-c, --ignore-certsIgnore SSL certificate validation errors
-s API_SERVER, --server=API_SERVERAPI server address
-v, --verboseView the detailed process of execution (- vv, - vv more detailed)
–versionView version

Examples

# connect https://galaxy.ansible.com Download the corresponding roles

# Search item
[root@ansible ~]#ansible-galaxy search lnmp

# List all installed galaxy
ansible-galaxy list

# Install galaxy and download to ~ /. By default ansible/roles
ansible-galaxy install geerlingguy.nginx
ansible-galaxy install geerlingguy.mysql 
ansible-galaxy install geerlingguy.redis

# Delete galaxy
ansible-galaxy remove geerlingguy.nginx

2.5 ansible-pull

The command function extracts scripts from the VCS repository and executes them for the local host. The use of this command involves another working mode of ansible: pull mode (ansible uses push mode by default). This is just the opposite of the normal push mode working mechanism, which is applicable to the following scenarios.

1. There are a large number of machines that need to be configured. Even if high concurrency threads are used, it still takes a lot of time;

2. Use and run ansible on a newly started host with no network connection

grammar

ansible-pull -U <repository> [options] [<playbook.yml>]

parameter

header 1header 2
-U , --url Website of script database
-d , --directory Check out the directory of the repository
-i, --inventory, --inventory-fileSpecify the host path or comma separated list of hosts. – Inventory files are not recommended
-o, --only-if-changedRun the script only if the repository has been updated
-u <REMOTE_USER>, --user <REMOTE_USER>Connect as this user (default = none)

Usually, ansible pull is implemented in combination with GIT and crontab. Its principle is to pull the playbook in the specified git library to the local regularly through crontab, and automatically run the pre-determined instructions in the specified mode.

Examples

*/20 * * * * root /usr/local/bin/ansible-pull -o -C 2.1.0 -d /srv/www/king-gw/ -i /etc/ansible/hosts -U \
git://git.kingifa.com/king-gw-ansiblepull >> /var/log/ansible-pull.log 2>&1
# Ansible pull is usually used in the scenario of configuring a large number of machines. It lacks flexibility, but the efficiency can be improved almost infinitely. It has high requirements for the technical level and forward-looking planning of operation and maintenance personnel.

2.6 ansible-config

Ansible config: view, edit and manage ansible configuration files

ansible-config [view|dump|list] [--help] [options] [ansible.cfg]
list            # Print all configuration options
dump            # Backup configuration information
view            # View profile

option

header 1header 2
-c CONFIG_FILE, --config=CONFIG_FILESpecify the path where the configuration file is located
-h, --helpView help information
-v, --verboseView the detailed process of execution (- vv, - vv more detailed)
–versionView version

2.7 ansible-inventory

Ansible inventory: view the detailed information of the host list of the controlled end. By default, it uses the inventory script and returns JSON format

grammar

ansible-inventory [options] [host|group]

parameter

header 1header 2
–ask-vault-passAsk for vault password
–output OUTPUT_FILEOutput the display information in the specified file
–tomlDisplay in TOML format
-h, --helpdisplay help information
-i INVENTORYSpecify the invetniory file
-y, --yamlDisplay in yaml format
-v, --verboseView the detailed process of execution (- vv, - vv more detailed)
–versionView version

Examples

[root@node1 ~]# ansible-inventory --list
{
    "_meta": {
        "hostvars": {}
    }, 
    "all": {
        "children": [
            "ungrouped"
        ]
    }
} 

2.8 ansible-vault

Ansible vault is mainly used to encrypt the configuration file (yml file). For example, the playbook configuration file contains sensitive information and does not want others to read it casually,

# Function: manage encryption and decryption yml files
ansible-vault [create|decrypt|edit|encrypt|encrypt_string|rekey|view] [options] [vaultfile.yml]
create			#establish
decrypt			#decrypt
edit			#edit
encrypt			#encryption
rekey			#Change Password
view			#see

option

header 1header 2
–ask-vault-passAsk for vault password
-h, --helpView help information
–new-vault-id=NEW_VAULT_IDSet the new vault ID for rekey
–new-vault-password-file=NEW_VAULT_PASSWORD_FILThe new vault password file is rekey
–vault-id=VAULT_IDSVault ID to use
–vault-password-file=VAULT_PASSWORD_FILESLibrary password file
-v, --verboseView the detailed process of execution (- vv, - vv more detailed)
–versionView version

Examples

ansible-vault create bidding.yml    # create a new file
ansible-vault encrypt bidding.yml   # encryption
ansible-vault decrypt bidding.yml   # decrypt
ansible-vault view bidding.yml      # see
ansible-vault eidt bidding.yml      # Edit encrypted file
ansible-vault rekey bidding.yml     # Change password

# It cannot run after encryption. It can only run after decryption
ansible-playbook bidding.yml       

2.9 ansible-console

2.0 + new, can execute ansible command interactively

tab completion is supported. It is often used in scenes between ad-hoc and ansible playbook, and it is often used to centralize a batch of temporary operations or commands.

Prompt format

Executive user@Host group of the current operation (number of hosts in the current group)[f:Concurrent number]$

Common subcommands:

  • Set the number of concurrent: forks n, for example: forks 10

  • Switching group: cd host group, for example: cd bidding

  • list current group hosts: list

  • List all built-in commands:? Or help

Examples

root@ubuntu20:~# ansible-console
Welcome to the ansible console.
Type help or ? to list commands.

root@all (4)[f:5]$ list
10.0.0.15
10.0.0.11
10.0.0.16
10.0.0.12
root@all (4)[f:5]$ cd db
root@db (2)[f:5]$ list
10.0.0.15
10.0.0.16
root@db (2)[f:5]$ ping
[DEPRECATION WARNING]: Distribution ubuntu 20.10 on host 10.0.0.16 should use /usr/bin/python3, but is using /usr/bin/python
for backward compatibility with prior Ansible releases. A future Ansible release will default to using the discovered
platform python for this host. See https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for
more information. This feature will be removed in version 2.12. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.
10.0.0.16 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.15 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
root@db (2)[f:5]$

Keywords: ansible

Added by scifo on Tue, 08 Feb 2022 17:51:37 +0200