Use of the ad-hoc command line for ansible serials

1. ansible batch operations and configuration management:

In this blog, the following points of knowledge and practical experience are mainly explained for your reference:

Introduction to ansible:

_2. Use of common modules in ansible:

_3. Use of ansible playbook:

1. Introduction to ansible:

1.1 Introduction to Ansible:
_ansible is a python-based, lightweight, automated operation and maintenance management tool that can be used to batch execute commands, install programs, and support playbook orchestration.It uses the ssh protocol to connect to the host machine, which is more simple and lightweight than puppet and saltstack to achieve file transfer, command execution, application deployment, configuration management, task scheduling without installing customers.Ansible only provides a framework that works on modules and does not deploy in bulk.

1.2 Ansible Core Components:
_1. connection plugins: responsible and monitored for communication;
_2. host inventory: The host for the specified operation is the host for which monitoring is defined in the configuration file;
_3. Various module core modules, command modules, custom modules;
_4. With the help of plug-ins, log mail and other functions can be completed;
_5. playbook: When a script performs multiple tasks, it is not necessary for a node to run multiple tasks at once.

1.3 Ansible features:
_1. no agents: No clients need to be installed on the managed host;
_2. no server: no server, run commands directly when using;
_3. modules in any languages: Module-based work, modules can be developed in any language;
_4. yaml, not code: use yaml language to customize playbook;
_5. ssh by default: work based on SSH;
_6. strong multi-tier solution: multi-level command can be achieved;

1.4 Ansible installation:

_Installation of ansible server conditions, the first is the LInux system, the second is the need to install Python version 2.7 above, install epel warehouse source

yum install epel-release -y
yum install ansible -y
[root@rainbondmanager yum.repos.d]# ansible --version
ansible 2.8.1
  config file = /etc/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, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
[root@rainbondmanager yum.repos.d]#
# View version of ansible

# Execute on ansible server and ansible client:
ssh-keygen -t rsa -P "" -f /root/.ssh/id_rsa

# Then, on the ansible server, copy the public key file to the / root/.ssh/authorized_keys file of the ansible client machine
ssh-copy-id -i /root/.ssh/id_rsa 10.93.32.130
ssh-copy-id -i /root/.ssh/id_rsa 10.93.32.131

#The main configuration and execution files for ansible are as follows:
/etc/ansible/ansible.cfg
# The main configuration file of ansible mainly defines roles_path path path, host list path, host mode in connection list, etc. Most of these default configurations are sufficient for us to use in normal times, you can modify them if you need special configurations.
/etc/ansible/hosts
# This profile is the default host manifest profile, which can be redefined by ansible.cfg;

ansible                 #Main executor, generally used to execute from the command line
ansible-playbook        #Execute tasks in playbook
ansible-doc             #Get help for each module

# The configured/etc/ansible/hosts file contains the following:

[websrvs]
10.83.32.130
10.83.32.131

2. Common command modules for ansible:

_There are many modules available in ansible, so here are just some of the commonly used modules. First, let's look at the command line format of ansible:

ansible

HOST-PATTERN      #Match host mode, such as all for all hosts
-m MOD_NAME       #The module name is as follows:
-a MOD_ARGS       #Parameters for module execution
-f FORKS          #Generate several subprocesses for execution
-C                #(no execution, simulation run)
-u Username       #User name of a host
-c  CONNection    #Connection mode (default smart)
ansible More modules,By ansible-doc --help display help information
ansible doc -l Get available modules and brief information for all current versions
ansible-doc -s Module Name Gets Help Information for a Specified Module Description``

_2.1 COPY module: Distribution from local copy files to directory host path

Parameter description:
src=source file path
 dest = destination path
 Note that src = path followed by a band / means that everything inside the band is copied to the destination directory, not a directory recursively copied to the past
 Content = self-filling file content
 Owner owner
 group
 mode permissions
ansible all -m copy -a "src=/data/ncp/pom.xml dest=/tmp/pom.xml mode=600"
Ansible all-m copy-a "content='hello ansible\n'dest=/tmp/hello.txt"#Generate a file by entering the contents of the file
 Ansible all-m shell-a "cat/tmp/hello.txt" #View files on remote hosts

_2.2 fetch module: pull files from remote host to local

[root@rainbondmanager ncp]# ansible all -m fetch -a "src=/tmp/hello.txt dest=/tmp"
10.83.32.131 | CHANGED => {
    "changed": true,
    "checksum": "df800445bb74b4abb144b3f9bf03f90aa9618f4c",
    "dest": "/tmp/10.83.32.131/tmp/hello.txt",
    "md5sum": "f61d358bbdd6a9bd2e93322023a4e29d",
    "remote_checksum": "df800445bb74b4abb144b3f9bf03f90aa9618f4c",
    "remote_md5sum": null
}
10.83.32.130 | CHANGED => {
    "changed": true,
    "checksum": "df800445bb74b4abb144b3f9bf03f90aa9618f4c",
    "dest": "/tmp/10.83.32.130/tmp/hello.txt",
    "md5sum": "f61d358bbdd6a9bd2e93322023a4e29d",
    "remote_checksum": "df800445bb74b4abb144b3f9bf03f90aa9618f4c",
    "remote_md5sum": null
}
[root@rainbondmanager ncp]# ls /tmp/10.83.32.131/tmp/hello.txt
/tmp/10.83.32.131/tmp/hello.txt
[root@rainbondmanager ncp]#
#Description: fetch is easy to use, src and dest,dest only specify a receive directory, the default will be followed by the path of remote host and src

_2.3 command module: execute command on remote host, belong to bare execution, non-key-value pair display; do not shell parse;

[root@rainbondmanager ncp]# ansible all -m command -a "ifconfig"
10.83.32.131 | CHANGED | rc=0 >>
ens192: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.83.32.131  netmask 255.255.255.0  broadcast 10.83.32.255
        inet6 fe80::e40:453c:4d1:d859  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:62:5a:6a  txqueuelen 1000  (Ethernet)
        RX packets 4703751  bytes 322962815 (308.0 MiB)
        RX errors 0  dropped 7  overruns 0  frame 0
        TX packets 22169  bytes 1642865 (1.5 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

10.83.32.130 | CHANGED | rc=0 >>
ens192: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.83.32.130  netmask 255.255.255.0  broadcast 10.83.32.255
        inet6 fe80::ae8b:7313:3f36:ca25  prefixlen 64  scopeid 0x20<link>
        ether 00:0c:29:0e:2f:ab  txqueuelen 1000  (Ethernet)
        RX packets 4703839  bytes 322848456 (307.8 MiB)
        RX errors 0  dropped 17  overruns 0  frame 0
        TX packets 22942  bytes 1621244 (1.5 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

[root@rainbondmanager ncp]# ansible all -m command -a "ifconfig|grep ens192"
10.83.32.130 | FAILED | rc=2 >>
[Errno 2] No such file or directory

10.83.32.131 | FAILED | rc=2 >>
[Errno 2] No such file or directory

# Since commnad can only execute naked commands (i.e. supported commands in the system environment), functions such as pipes are not supported.
shell Modules can do this

_2.4 shell module: complex pipeline commands can be used

[root@rainbondmanager ncp]# ansible all -m shell -a "ifconfig|grep ens192"
10.83.32.130 | CHANGED | rc=0 >>
ens192: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500

10.83.32.131 | CHANGED | rc=0 >>
ens192: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500

[root@rainbondmanager ncp]#

_2.5 file module: set file properties, create directory, etc.

Common parameters:
path Target Path
state directory Is Directory,link Link for software
group Catalog Subgroup
owner Owner etc,Other parameters passed ansible-doc -s file Obtain

# Create directory
[root@rainbondmanager ncp]# ansible all -m file -a "path=/var/tmp/hello.dir state=directory"
10.83.32.130 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/var/tmp/hello.dir",
    "secontext": "unconfined_u:object_r:user_tmp_t:s0",
    "size": 6,
    "state": "directory",
    "uid": 0
}
10.83.32.131 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/var/tmp/hello.dir",
    "secontext": "unconfined_u:object_r:user_tmp_t:s0",
    "size": 6,
    "state": "directory",
    "uid": 0
}
[root@rainbondmanager ncp]# ansible all -m shell -a "ls -l /var/tmp/hello.dir"
10.83.32.131 | CHANGED | rc=0 >>
total 0

10.83.32.130 | CHANGED | rc=0 >>
total 0

[root@rainbondmanager ncp]#

# Configure Soft Links
[root@rainbondmanager ncp]# ansible all -m file -a "src=/etc/fstab path=/var/tmp/fstab.link state=link"
10.83.32.131 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "dest": "/var/tmp/fstab.link",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "secontext": "unconfined_u:object_r:user_tmp_t:s0",
    "size": 10,
    "src": "/etc/fstab",
    "state": "link",
    "uid": 0
}
10.83.32.130 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "dest": "/var/tmp/fstab.link",
    "gid": 0,
    "group": "root",
    "mode": "0777",
    "owner": "root",
    "secontext": "unconfined_u:object_r:user_tmp_t:s0",
    "size": 10,
    "src": "/etc/fstab",
    "state": "link",
    "uid": 0
}
[root@rainbondmanager ncp]# ansible all -m shell -a "ls -l /var/tmp/fstab.link"
10.83.32.131 | CHANGED | rc=0 >>
lrwxrwxrwx. 1 root root 10 Jul 23 04:29 /var/tmp/fstab.link -> /etc/fstab

10.83.32.130 | CHANGED | rc=0 >>
lrwxrwxrwx. 1 root root 10 Jul 23 04:29 /var/tmp/fstab.link -> /etc/fstab

_2.6 cron module: setting timer tasks

adopt cron Module generates scheduled tasks for target host
//Common parameters:
//Except minute hour day month week
name: Name of this planned task
state: present generate(default) |absent delete (Be based on name)
//Example: Add synchronization time from time.windows.com every 3 minutes to each host
[root@rainbondmanager ~]# ansible all -m cron -a "minute=*/3 job='/usr/sbin/update time.windows.com &>/dev/null' name=update_time"  #Increase crontab tasks, specify synchronization time every 3 minutes
10.83.32.130 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "envs": [],
    "jobs": [
        "update_time"
    ]
}
10.83.32.131 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "envs": [],
    "jobs": [
        "update_time"
    ]
}
[root@rainbondmanager ~]# ansible all -m shell -a "crontab -l"
10.83.32.131 | CHANGED | rc=0 >>
#Ansible: update_time
*/3 * * * * /usr/sbin/update time.windows.com &>/dev/null

10.83.32.130 | CHANGED | rc=0 >>
#Ansible: update_time
*/3 * * * * /usr/sbin/update time.windows.com &>/dev/null

//Example 2: Delete scheduled tasks
[root@rainbondmanager ~]# ansible all -m cron -a "name=update_time state=absent" #Delete crontab task
10.83.32.131 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "envs": [],
    "jobs": []
}
10.83.32.130 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "envs": [],
    "jobs": []
}
[root@rainbondmanager ~]# ansible all -m shell -a "crontab -l"
10.83.32.131 | CHANGED | rc=0 >>
10.83.32.130 | CHANGED | rc=0 >>

_2.7 yum module: module for yum installation package

Description of common parameters:
enablerepo,disablerepo means to enable and disable a repo Library
 name Installation Package name
 State (present'orinstalled', latest') means installation, (absent'or `removed') means deletion
 Example: by installing epel extension source and nginx
ansible all -m yum -a "name=epel-release state=installed"
ansible all -m yum -a "name=nginx state=installed"

_2.8 service module: service management module

Service Management Module
 Common parameters:
Name:Service name
 state:Service state
 enabled: whether to start true|false
 runlevel: Startup level (ignored by systemed)
ansible all -m service -a "name=nginx state=started enabled=true"
#Set the nginx software you just installed to start on and start the service
iptables -I INPUT -p tcp --dport 80 -j ACCEPT
 #Additional firewall open policy is required because the target machine has firewall software installed

_2.9 script module: transfer local scripts to remote execution

# Create a script for test.sh on the ansible server

[root@rainbondmanager ~]# cat test.sh
#!/bin/bash
ipaddr=$(ip addr|grep ens192|grep inet|awk '{print $2}'|awk -F "/" '{print $1}')
echo "This host ip address is ${ipaddr}" >> /tmp/ip.txt

ansible all -m script -a "/root/test.sh"

_Write here today, I will also post a few more articles on the use of ansible, including the definition of ansible-playbook, the management of roles hierarchical directory, and so on.

For more details, please pay attention to my personal WeChat public number "IT Operations and Maintenance in the Cloud Age". This public number is designed to share new technologies and trends in Internet Operations and Maintenance, including consulting from the IT Operations and Maintenance industry and sharing of Operations and Maintenance technical documents.Focus on devops, jenkins, zabbix monitoring, kubernetes, ELK, the use of various middleware, such as redis, MQ; shell and python, and other operations and maintenance programming languages; I have been engaged in IT operations and maintenance related work for more than 10 years.In 2008, I started working on Linux/Unix system operation and maintenance; I have a certain understanding of operation and maintenance related technology.All posts on this public number are summaries of my actual work experience and are basically original posts.I would like to share my experience, experience and technology with you!I hope to grow and progress with you along the IT operation and maintenance career path.

Keywords: Linux ansible Python shell ssh

Added by nemesis.2002 on Sat, 27 Jul 2019 19:10:11 +0300