Ansible automated O & M tools (2)

Source: Internet
Author: User
Tags ansible modules

Iii. Use of ansible

1. ansible Command Execution Process and status

Process:

  1. Load your configuration file. The default value is/etc/ansible. cfg.
  2. Load the corresponding module File, such as command Ping
  3. Use ansible to generate a temporary py file for the module or command and transmit the file to the remote server.
  4. Grant file + x Permissions
  5. Execute and return results
  6. Delete the temporary py file and exit sleep 10.

Status:

  • Green: action that is successfully executed and does not need to be changed
  • Yellow: executed successfully and changed the target host
  • RED: execution failed

2. ansible commands

Ansible-Doc ansible-playbook ansible-vault ansible-console ansible-Galaxy ansible-pull

  • Ansible-Doc display module help

Ansible-Doc [Options] [module...]

-A: displays documents of all modules.

-L -- list available modules

-S -- snippet: Display The Playbook clip of the module

Example:

Ansible-doc-l list all modules

Ansible-Doc Ping

Ansible-doc-s Ping

  • Ansible command usage

Ansible

-- Display version

-M module: the default module is command.

-V detailed process-VV-vvv For more details

-- List-hosts: Host list can be abbreviated as -- list

-K -- ask-pass prompt data SSH connection password default key verification

-K -- ask-become-pass prompt to enter sodu Password

-C check is not executed

-T -- timeout = Timeout: the default timeout value is 10 s.

-U -- user = remote_user: the user who executes Remote Execution

-B -- become replaces the old sudo switchover

Test: use the white user to connect to the server in the web group to view the contents in the root directory:

[[email protected] ~]# ansible web -u white -k -m command -a ‘ls /root‘SSH password: 172.16.111.7 | FAILED | rc=2 >>ls: cannot open directory /root: Permission deniednon-zero return code172.16.111.8 | FAILED | rc=2 >>ls: cannot open directory /root: Permission deniednon-zero return code

Show no Permissions

[[email protected] ~]# ansible web -m command -a ‘ls /root‘ -u white -k -b  -KSSH password: SUDO password[defaults to SSH password]: 172.16.111.8 | FAILED! => {    "changed": false,     "module_stderr": "Shared connection to 172.16.111.8 closed.\r\n",     "module_stdout": "\r\nWe trust you have received the usual lecture from the local System\r\nAdministrator. It usually boils down to these three things:\r\n\r\n    #1) Respect the privacy of others.\r\n    #2) Think before you type.\r\n    #3) With great power comes great responsibility.\r\n\r\n\r\nSorry, user white is not allowed to execute ‘/bin/sh -c echo BECOME-SUCCESS-mpdogqixumfmgqlscdyojejjgicjppfi; /usr/bin/python /home/white/.ansible/tmp/ansible-tmp-1540363523.36-270983856118240/command.py; rm -rf \"/home/white/.ansible/tmp/ansible-tmp-1540363523.36-270983856118240/\" > /dev/null 2>&1‘ as root on node2.\r\n",     "msg": "MODULE FAILURE",     "rc": 1}172.16.111.7 | SUCCESS | rc=0 >>aanaconda-ks.cfgCentOS-Base.repocheckoutelasticsearch-6.0.0.rpmnginx-1.12.2nginx-1.12.2.tar.gzupdate

At this time, we found that node1 can be 2 and cannot be queried. Because white users do not have sudo authorization in node2, mongodo modifies mongodo-C detection.

[[email protected] ~]# ansible web -m command -a ‘ls /root‘ -u white -k -b  -KSSH password: SUDO password[defaults to SSH password]: 172.16.111.7 | SUCCESS | rc=0 >>aanaconda-ks.cfgCentOS-Base.repocheckoutelasticsearch-6.0.0.rpmnginx-1.12.2nginx-1.12.2.tar.gzupdate172.16.111.8 | SUCCESS | rc=0 >>315586643?lang=zh-CNanaconda-ks.cfgelasticsearch-2.3.5.rpmelasticsearch-6.0.0.rpmkibana-4.5.4-1.x86_64.rpmlogstash-2.3.4-1.noarch.rpmnginx-1.12.2nginx-1.12.2.tar.gzrh-nginx112-nginx-1.12.1-2.el7.x86_64.rpm

All of the above are password-based verification and root permissions are required. There are security risks. Key-based verification is recommended in production.

3. Key-based verification Configuration

Generate a public key on the ansible master and send it to all the control terminals.

[[email protected] ~]# ssh-keygen Generating public/private rsa key pair.Enter file in which to save the key (/root/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa.Your public key has been saved in /root/.ssh/id_rsa.pub.The key fingerprint is:SHA256:dOv+zF1JdDLy9dpJzfGf1cYl1zGuPC9m2w/0nsLFGPc [email protected]The key‘s randomart image is:+---[RSA 2048]----+|               o ||              . +||        . . . ++*||       . . ..+oXO||        S .  [email protected]||         .   o=BE||          . .++==||         . oo+++.||          ..+.oo+|+----[SHA256]-----+You have new mail in /var/spool/mail/root[[email protected] ~]# ssh-copy-id 172.16.111.7/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys[email protected]‘s password: Number of key(s) added: 1Now try logging into the machine, with:   "ssh ‘172.16.111.7‘"and check to make sure that only the key(s) you wanted were added.[[email protected] ~]# ssh-copy-id 172.16.111.8/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys[email protected]‘s password: Number of key(s) added: 1Now try logging into the machine, with:   "ssh ‘172.16.111.8‘"and check to make sure that only the key(s) you wanted were added.[[email protected] ~]# ssh-copy-id 172.16.111.9/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys[email protected]‘s password: Number of key(s) added: 1Now try logging into the machine, with:   "ssh ‘172.16.111.9‘"and check to make sure that only the key(s) you wanted were added.

Verify

[[email protected] ~]# ansible all -m ping172.16.111.9 | SUCCESS => {    "changed": false,       "ping": "pong"}172.16.111.7 | SUCCESS => {    "changed": false,     "ping": "pong"}172.16.111.8 | SUCCESS => {    "changed": false,     "ping": "pong"}

4. ansible Working Mode

5. Host-pattern of ansible

List of matched hosts

  • ALL: indicates all hosts in inverntory.
    Ansible all-M Ping
    • : Wildcard
      Ansible""-M Ping
      Ansible 172.16.111.
      -M Ping
      Ansible "Web"-M Ping
  • Logic or
    Ansible "Web: app"-M Ping
    Ansible "172.16.111.7: 172.16.111.9"-M Ping
  • Logic and
    Ansible "Web: & App"-M Ping
  • Non-logical
    Ansible 'web :! App'-M Ping
    !!! Note !!! The logical and or non-logical values are: &,:, and :&,:,:! It can only be, but cannot be, double quotation marks.
  • Integrated Logic
    Ansible 'web: & App :! Db'-M Ping

  • Regular Expression
    Ansible "Web: & App :! DB "-M Ping # Differentiated comprehensive Logic
    Ansible "~ (Web | dB). * .white.com "-M Ping

6. Common ansible modules

  • Command: execute commands on the host. The-M option can be ignored by default.
    Ansible web-M command-A 'ls/data'
    This command does not support @ varname <> |; & and so on. It must be implemented using the shell module.
    [[Email protected] ~] # Ansible-Doc command
    -Chdir # Switch Directories
    -Creates # if a file is created, no command is executed.
    = Free_form #
    -Removes # If the file does not exist, no command is executed.

    ansible web -m command -a ‘removes =/data ls /data‘
  • Shell: similar to command, use shell to execute commands.
    Ansible web-M shell-A 'echo white | passwd-stdin wange'
    Call Bash to execute commands similar to CAT/tmp/Stanley. MD | AWS-F' | ''{print $1, $2} '&>/tmp/asd.txt: when writing the script, copy it to remote execution and pull the desired result back to the machine where the command is executed.

  • Script: run the script
    -A "/path/to/script_file"
    Ansible web-M script-A f1.sh
  • Copy: Copy files from the server to the client
    Ansible all-M copy-A 'src =/etc/hosts DEST =/etc/hosts backup = yes'
    SRC Source DEST target backup onwer owner mode permission
  • Fetch: Get files from the client to the server, opposite to copy
    Ansibles web-M fetch-A 'src =/root/a. Sh DEST =/data/scripts /'
    By default, only one file is supported, and multiple files or directories are not supported. It is recommended to put a file in the TAR Directory for pulling After packaging.
    In this case, the hostname in/data/scripts/Hostname/is the host name of the controlled host.
  • File: it is important to set the state attribute of a file. Different results can be achieved based on different values of state.
    Ansible EWB-M file-a "Path =/root/a. Sh owner = white mode = 755"
    Ansible web-M file-A 'src =/APP/testfile DEST =/APP/testfile-link state = link'
    # Creating files
    [[Email protected] ~] # Ansible all-M file-A 'path =/tmp/ADS state = Touch'
    [[Email protected] ~] # Ansible all-M shell-A 'LS-L/tmp | grep ads'
    172.16.111.9 | Success | rc = 0>
    -RW-r --. 1 Root 0 Oct 25 ads

    172.16.111.7 | Success | rc = 0>-RW-r --. 1 Root 0 Oct 24 16:48 ads172.16.111.8 | Success | rc = 0>-RW-r --. 1 Root 0 Oct 24 ads # delete a file [[email protected] ~] # Ansible all-M file-A 'path =/tmp/ADS state = absent '[[email protected] ~] # Ansible all-M shell-A 'LS-L/tmp | grep analytics' 172. 16.111.9 | failed | rc = 1> non-zero return code172.16.111.7 | failed | rc = 1> non-zero return code172.16.111.8 | failed | rc = 1> non-zero return code

    If you want to create a folder state = directory to delete it, use absent
    # Creating soft links
    [[Email protected] ~] # Ansible all-M file-A 'src =/etc/fstab DEST =/data/fstab. Link State = link'
    [[Email protected] ~] # Ansible all-M shell-A 'LS-L/data'
    172.16.111.9 | Success | rc = 0>
    Total 0
    Lrwxrwxrwx. 1 Root 10 Oct 25 fstab. Link->/etc/fstab

    172.16.111.7 | Success | rc = 0> total 0lrwxrwxrwx. 1 Root 10 Oct 24 fstab. link->/etc/fstabdrwxr-XR-X. 3 root 21 Oct 22 svndata172.16.111.8 | Success | rc = 0> total 0lrwxrwxrwx. 1 Root 10 Oct 24 fstab. link->/etc/fstabdrwxr-XR-X. 3 root 21 Oct 22 svndata # Delete soft link [[email protected] ~] # Ansible all-M file-A 'dest' =/data/fstab. Link State = absent'
  • Hostname: Modify the Host Name
    Ansible 172.16.111.7-M hostname-a 'name = web01'
    In this case, both the configuration file and temporary modification are performed simultaneously. It is valid after restart.
  • Cron: scheduled task Module
    1) create a Task Scheduler
    Ansible all-M Cron-a 'minute = * weekday = 1, 3, 5 job = "/usr/bin/wall FBI warining" name = warningcron'
    2) disable the Task Scheduler
    Ansible all-M Cron-A 'Disabled = true job = "/usr/bin/wall FBI warining" name = warningcron'
    # When canceling a Job Schedule, the job and name must have no name, and a new scheduled task is created and commented out.
    3) Open the task scheduler again
    Disabled = false
    True can also use Yes
    If the value is false, no can be used.
    4) delete a scheduled task
    Ansible all-M Cron-a 'job = "/usr/bin/wall FBI warining" name = warningcron state = absent'
  • Yum: Management Package Module
    By default, present or installed can be installed. Multiple packages are separated.
    Ansible all-M Yum-a 'name = vsftpd'
    You can also install an independent Binary Package. First, copy the package to each controlled host, and then install the package in the name =/data/*** path.
    View installed
    Ansible all-M Yum-a 'list = installed'
    You can uninstall both removed and absent.
    Ansible all-M Yum-a 'name = vsftpd state = removed'
    You can use the shell module rpm-Q to view
  • Service: Service Module
    Remotely enable the Service and add it to enable auto-start
    Ansible all-M Service-a 'name = vsftpd state = started enabled = yes'
    Enabled
    State = started enable service
  • User: User Management
    Create user
    Ansible all-M User-a 'name = nginx shell =/sbin/nologin system = Yes home =/var/nginx groups = root, bin Group = nginx uid = 1005 comment = "nginx serveice "'
    Home Directory
    Group main group groups auxiliary Group
    Delete a user
    Ansible all-M User-a 'name = nginx state = absent remove = yes'
    Remove = Yes Delete home directory
  • Group: Group Management
    Similar to user
    Create Group
    Ansible all-M group-a 'name = nginx system = Yes gid = 80'
    Delete Group
    Ansible all-M group-a 'name = nginx state = absent'

Ansible automated O & M tools (2)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.