1. Ansible features:

  • Ansible combines the advantages of many established operations and maintenance tools, and basically implements all the functions that Pubbet and SaltStack can achieve.
  • Simple deployment: You do not need to install any client on the managed host. You can run commands to operate the client.
  • Based on Python language, there are Paramiko, PyYAML and Jinja2 three key modules.
  • Modularity: Calls to specific modules to accomplish specific tasks. Modules can be developed in any language, and custom modules are supported.
  • Customize the playbook script using the YAML language.
  • Based on the SSH for

2. Ansible modules

  • Connection plugins: Use SSH to connect plug-ins
  • Host Inventory: Inventory of hosts to be managed
  • Playbooks: Scripts, yamL format configuration files
  • Core modules: Core modules
  • Custom Modules: custom modules
  • Plugins and emails. – loggings: Records logs

3. The installation

Ansible place:

  • Extranet hosts: Intranet hosts can be managed through VPN connections
  • Intranet host: Directly managed

Ansible installation: Configure the epel source and install it directly through yum

~] # yum -y install ansible
Copy the code

Ansible configuration file: /etc/ansible/ansible. CFG Ansible host list: /etc/ansible/hosts ** Ansible main program: **ansible, ansible-playbos, ansible-doc

4. Use ansible commands:

[root@nfs ~]# ansible -h Usage: ansible <host-pattern> [options] Options: -a MODULE_ARGS, --args=MODULE_ARGS module arguments -c, --check don't make any changes; Instead, try to predict some of the changes that may occur --module-name=MODULE_NAME Module name to execute (default=command) Specify the module name -- syntactic -check perform a syntax check on the Playbook, but do not execute it syntax detection -f FORKS, --forks= forks Specify number of parallel processes to use (default=5) -u REMOTE_USER, --user=REMOTE_USER connect as this user (default=None) -c CONNECTION, --connection=CONNECTION connection type to use (default=smart) --list-hosts outputs a list of matching hosts; Does not execute anything else Lists the hosts and does not execute anything else. -b, --become run operations with become (does not imply password prompting)Copy the code

5. Define host list:

Example 1. Define the host list by specifying the host name or IP address.

# Ex 1: Ungrouped hosts, specify before any group headers.

## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10
Copy the code

Example 2. Define the group name, and then enter the host name or IP address under the group

# Ex 2: A collection of hosts belonging to the 'webservers' group

## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110

# If you have multiple hosts following a pattern you can specify
# them like this:
#If there are multiple consecutive hosts, you can also specify the host in the following way.

## www[001:006].example.com
Copy the code

Example 3.

# Ex 3: A collection of database servers in the 'dbservers' group

## [dbservers]
## 
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57

# Here's another example of host ranges, this time there are no
# leading 0s:

## db-[99:101]-node.example.com
## The following host can be extended:
## db-99-nod.example.com
## db-100-nod.example.com
## db-101-nod.example.com
Copy the code

Example 1 for defining a host list:

[root@nfs ~]# tail -2 /etc/ansible/hosts
np[1:2].lxk.com
nfs.lxk.com
Copy the code

To obtain the host list:

[root@nfs ~]# ansible all --list-hosts
  hosts (3):
    np1.lxk.com
    np2.lxk.com
    nfs.lxk.com
Copy the code

Define host list 2:

[root@nfs ansible_workshop]# tail -8 /etc/ansible/hosts 
[db]
node1.lxk.com
node2.lxk.com
[web]
np1.lxk.com
np2.lxk.com
[nfs]
nfs.lxk.com
Copy the code

To obtain the host list:

[root@nfs ansible_workshop]# ansible all --list-hosts
  hosts (5):
    node1.lxk.com
    node2.lxk.com
    np1.lxk.com
    np2.lxk.com
    nfs.lxk.com
[root@nfs ansible_workshop]# ansible db --list-hosts
  hosts (2):
    node1.lxk.com
    node2.lxk.com
[root@nfs ansible_workshop]# ansible web --list-hosts
  hosts (2):
    np1.lxk.com
    np2.lxk.com

Copy the code

6. Ansible common modules:

Obtain module help information:

[root@nfs ~]# ansible-doc --help Usage: ansible-doc [-l|-F|-s] [options] [plugin] plugin documentation tool Options: -a, --all **For internal testing only** Show documentation For all plugins. --help show this help message and exit -l, --list list available plugins -- Snippet Show Playbook Snippet for specified Plugin (s) ##Copy the code

Get a list of modules:

~] #ansible-doc -l
Copy the code

6.1 Ping Module: Detects remote hosts

[root@nfs ~]# ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
#Try to connect to the host and respond with one if the target host is available'pong'
  ping:
      data:           # Data to return for the `ping' return value. If this parameter is set to `crash', the module will cause an exception.
Copy the code

** Example 1: ** Ping all controllable hosts

[root@nfs ~]# ansible all -m ping
np2.lxk.com | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
nfs.lxk.com | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
np1.lxk.com | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
Copy the code

** Example 2: **data The command output is ABC

[root@nfs ~]# ansible all -m ping -a data='abc' 
np1.lxk.com | SUCCESS => {
    "changed": false, 
    "ping": "abc"
}
np2.lxk.com | SUCCESS => {
    "changed": false, 
    "ping": "abc"
}
nfs.lxk.com | SUCCESS => {
    "changed": false, 
    "ping": "abc"
}
Copy the code

** Example 3: * If data is set to crash, false is displayed

[root@nfs ~]# ansible all -m ping -a data='crash'
np1.lxk.com | FAILED! => {
    "changed": false, 
    "module_stderr": "Shared connection to np1.lxk.com closed.\r\n", 
    "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_2DLaM3/ansible_module_ping.py\", line 84, in <module>\r\n    main()\r\n  File \"/tmp/ansible_2DLaM3/ansible_module_ping.py\", line 74, in main\r\n    raise Exception(\"boom\")\r\nException: boom\r\n", 
    "msg": "MODULE FAILURE", 
    "rc": 1
}
nfs.lxk.com | FAILED! => {
    "changed": false, 
    "module_stderr": "Shared connection to nfs.lxk.com closed.\r\n", 
    "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_imV6B2/ansible_module_ping.py\", line 84, in <module>\r\n    main()\r\n  File \"/tmp/ansible_imV6B2/ansible_module_ping.py\", line 74, in main\r\n    raise Exception(\"boom\")\r\nException: boom\r\n", 
    "msg": "MODULE FAILURE", 
    "rc": 1
}
np2.lxk.com | FAILED! => {
    "changed": false, 
    "module_stderr": "Shared connection to np2.lxk.com closed.\r\n", 
    "module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_iocg2P/ansible_module_ping.py\", line 84, in <module>\r\n    main()\r\n  File \"/tmp/ansible_iocg2P/ansible_module_ping.py\", line 74, in main\r\n    raise Exception(\"boom\")\r\nException: boom\r\n", 
    "msg": "MODULE FAILURE", 
    "rc": 1
}
Copy the code

6.2 Command module: Runs commands on a remote host

Module usage: For command, use the -a option and give the command itself.

Example 1: Create a temporary file

[root@nfs ~]# ansible all -m command -a "mktemp /tmp/abc.XXXX" nfs.lxk.com | SUCCESS | rc=0 >> /tmp/abc.Xyz7 np2.lxk.com  | SUCCESS | rc=0 >> /tmp/abc.lwqo np1.lxk.com | SUCCESS | rc=0 >> /tmp/abc.jjHWCopy the code

Example 2: Create a user

/ root @ NFS ~ # ansible all -m command - a "useradd user1" # first create SUCCESS nfs.lxk.com | SUCCESS | rc = 0 > > np1.lxk.com | SUCCESS | | rc = 0 > > np2.lxk.com SUCCESS | rc = 0 > > / root @ NFS ~ # ansible all -m command - a "useradd user1" # for the second time failed to create the same user nfs.lxk.com | FAILED | rc=9 >> useradd: user 'user1' already existsnon-zero return code np1.lxk.com | FAILED | rc=9 >> useradd: user 'user1' already existsnon-zero return code np2.lxk.com | FAILED | rc=9 >> useradd: user 'user1' already existsnon-zero return codeCopy the code

Use add condition judgment failed to create a user, because | | run the kernel is sent directly to the target host, is not run by the shell, and | | is a built-in command shell.

[root@nfs ~]# ansible all -m command -a "id user1 || useradd user1" nfs.lxk.com | FAILED | rc=1 >> id: Extra operand '| |' Try 'id -- help' for more information. The non - zero return code np1.lxk.com | FAILED | rc = 1 > > id: Extra operand '| |' Try 'id -- help' for more information. The non - zero return code np2.lxk.com | FAILED | rc = 1 > > id: Extra operand '| |' Try 'id -- help' for more information. The non - zero return codeCopy the code

6.3 Shell Module: Executes commands on a node

It is very similar to the Command module except that it runs under a shell. Executable can also be used to switch to running commands under specified nodes. ** example: ** add conditional judgment to create user

[root@nfs ~]# ansible all -m shell -a "id user1 || useradd user1"
np2.lxk.com | SUCCESS | rc=0 >>
uid=1001(user1) gid=1001(user1) groups=1001(user1)

nfs.lxk.com | SUCCESS | rc=0 >>
uid=1000(user1) gid=1000(user1) groups=1000(user1)

np1.lxk.com | SUCCESS | rc=0 >>
uid=1000(user1) gid=1000(user1) groups=1000(user1)

Copy the code

6.4 Group module: Adds or deletes groups

Group module:

[root@nfs ~]# ansible-doc -s group - name: Add or remove groups group: gid: # Optional `GID' to set for the group. Name: # (required) name of the group to manage. The name of the group to be managed must be defined. state: # Whether the group should be present or not on the remote host. Status information that determines whether to delete or add. Create :present, delete: Absent system: # If 'yes', indicates that the group created is a system group. Whether to create a system userCopy the code

Example: ** Create a system group

[root@nfs ~]# ansible np1.lxk.com -m group -a 'name=mygrp gid=200 system=yes' np1.lxk.com | SUCCESS => { "changed": "Gid ": 200," ID ": 200, "name": "mygrp", "name": "mygrp", "state": "present", "status ": add "system": trueCopy the code

** Example: ** Delete a group

[root@nfs ~]# ansible np1.lxk.com -m group -a 'name=mygrp state=absent'
np1.lxk.com | SUCCESS => {
    "changed": true, 
    "name": "mygrp", 
    "state": "absent"
}
Copy the code

When the preceding command is repeatedly executed, the changed state is false.

[root@nfs ~]# ansible np1.lxk.com -m group -a 'name=mygrp state=absent'
np1.lxk.com | SUCCESS => {
    "changed": false, 
    "name": "mygrp", 
    "state": "absent"
}
Copy the code

6.5 User module: Manages user accounts

Module built-in command a pile, please check by yourself, the basic name know meaning. ** Example: ** Create a user whose name is Tom, ID is 2000, group name is mygrp, shell type is /bin/bash and status is Added.

[root@nfs ~]# ansible np1.lxk.com -m user -a 'name=tom state=present uid=2000 groups=mygrp shell=/bin/bash'
np1.lxk.com | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 2000, 
    "groups": "mygrp", 
    "home": "/home/tom", 
    "name": "tom", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 2000
}
Copy the code

** Example: ** Change the ID of user Tom to 2020 and shell type to /bin/tcsh

[root@nfs ~]# ansible np1.lxk.com -m user -a 'name=tom state=present uid=2020 groups=mygrp shell=/bin/tcsh'
np1.lxk.com | SUCCESS => {
    "append": false, 
    "changed": true, 
    "comment": "", 
    "group": 2000, 
    "groups": "mygrp", 
    "home": "/home/tom", 
    "move_home": false, 
    "name": "tom", 
    "shell": "/bin/tcsh", 
    "state": "present", 
    "uid": 2020
}
Copy the code

6.6 copy module

[root@nfs ~]# ansible-doc -s copy - name: Copies files to remote locations # copy: dest # (required) Remote absolute path where the file should be copied to. If `src' is a directory, this must be a directory too. If `dest' is a nonexistent path and if either `dest' ends with "/" or `src' is a directory, `dest' is created. If `src' and `dest' are files, the parent directory of `dest' isn't created: The task fails if it doesn't already exist. If SRC is a directory, dest must also be a directory. Dest is automatically created if it is a non-existent path and does not end in/or SRC is a directory. If both SRC and dest are multiple files, the copy will fail if the dest parent directory is not created. src: # Local path to a file to copy to the remote server; can be absolute or relative. If path is a directory, it is copied recursively. In this case, if path ends with "/", only inside contents of that directory are copied to destination. Otherwise, if it does not end with "/", The directory itself with all contents is copied. This behavior is similar to Rsync. It can be an absolute path or a relative path. If the path is a directory, it is recursively copied. If the path ends with a /, only the files in the directory are copied to the target path. If it does not end with a /, the directory and its contents will be copied to the target host. This behavior is similar to that of rsync. content: # When used instead of `src', sets the contents of a file directly to the specified value. For anything advanced or with formatting also look at the Template module. # If you use content instead of SRC, specify the contents of the file directly as specified by content. And then the rest of the translation is too lazy. owner: # Name of the user that should own the file/directory, as would be fed to `chown'. mode: # Mode the file or directory should be. group: # Name of the group that should own the file/directory, as would be fed to `chown'.Copy the code

** Example 1: ** Specify the contents of a file with content and copy to the destination host (no wrapping without \n)

[root@nfs ~]# ansible np2.lxk.com -m copy -a 'dest=/tmp/textfile.txt content="hello,brother! \n"' np2.lxk.com | SUCCESS => { "changed": true, "checksum": "8634ff795ad950aa9c762c45cc8b07137248002a", "dest": "/tmp/textfile.txt", "gid": 0, "group": "root", "md5sum": "2252b10979e37d2884855832666fd811", "mode": "0644", "owner": "root", "size": 15, "src": "~ None /. Ansible/TMP/ansible TMP - 1528471338.21-89043902941123 / source", # ansible will place a given source to generate a temporary source as the source file is copied to the target location. "state": "file", "uid": 0 }Copy the code

Target host View file content:

[root@np2 ~]# cat /tmp/textfile.txt 
hello,brother!
Copy the code

** Example 2: ** Copy the local /etc/fstab directory to the/TMP directory of np1.lxk.com, change the name to fstab. TXT, change the owner to user2, and grant 0600 permission.(User2 needs to be created first.)

[root@nfs ~]# np1.lxk.com all -m copy -a 'src=/etc/fstab dest=/tmp/fstab.txt owner=user2 mode=0600' np1.lxk.com | SUCCESS => { "changed": true, "checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", "dest": "/tmp/fstab.txt", "gid": 0, "group": "root", "md5sum": "5aee64ae648da49b3b16e2b9ea70d279", "mode": "0600", "owner": "user2", "size": 595, "src": "~ None /. Ansible/TMP/ansible TMP - 1528518314.71-128514426299583 / source", "state" : "file", "uid" : 1024}Copy the code

View files on the target host:

[root@np1 ~]# ll /tmp
total 4
-rw------- 1 user2 root 595 Jun  9 12:25 fstab.txt
Copy the code

6.7 the fetch module

[root@nfs ~]# ansible-doc-s fetch - name: Fetches a file from remote nodes # (required) A directory to save the file into. For example, if the `dest' directory is `/backup' a `src' file named `/etc/profile' on host `host.example.com', Whenever saved into ` / backup/host.example.com/etc/profile '# (must) to save the file directory. If the specified directory is/backup, the remote host host.example.com/etc/profile file will be stored in the local/backup/host.example.com/etc/profile SRC: # (required) The file on the remote system to fetch. This `must' be a file, Not a directory. Recursive fetching may be supported in a later release. # Fetch from the remote host must be a file, not a directory. Directories may be supported later.Copy the code

** Example 1: ** Copy /etc/fstab from np1.lxk.com to the local/TMP directory

[root@nfs ~]# ansible np1.lxk.com -m fetch -a 'src=/etc/fstab dest=/tmp/'
np1.lxk.com | SUCCESS => {
    "changed": true, 
    "checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", 
    "dest": "/tmp/np1.lxk.com/etc/fstab", 
    "md5sum": "5aee64ae648da49b3b16e2b9ea70d279", 
    "remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", 
    "remote_md5sum": null
}
Copy the code

** Example 2: ** Copy /etc/fstab from all controllable remote hosts to the local/TMP directory

[root@nfs ~]# ansible all -m fetch -a 'src=/etc/fstab dest=/tmp/'
np1.lxk.com | SUCCESS => {
    "changed": false, 
    "checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", 
    "dest": "/tmp/np1.lxk.com/etc/fstab", 
    "file": "/etc/fstab", 
    "md5sum": "5aee64ae648da49b3b16e2b9ea70d279"
}
np2.lxk.com | SUCCESS => {
    "changed": true, 
    "checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", 
    "dest": "/tmp/np2.lxk.com/etc/fstab", 
    "md5sum": "5aee64ae648da49b3b16e2b9ea70d279", 
    "remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", 
    "remote_md5sum": null
}
nfs.lxk.com | SUCCESS => {
    "changed": true, 
    "checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", 
    "dest": "/tmp/nfs.lxk.com/etc/fstab", 
    "md5sum": "5aee64ae648da49b3b16e2b9ea70d279", 
    "remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093", 
    "remote_md5sum": null
}
Copy the code

Check the local directory:

/ root @ NFS ~ # tree/TMP/TMP ├ ─ ─ issue. TXT ├ ─ ─ nfs.lxk.com │ └ ─ ─ etc │ └ ─ ─ fstab ├ ─ ─ np1.lxk.com │ └ ─ ─ etc │ └ ─ ─ fstab ├ ─ np4.lxk.com ├ ─ etc ├ ─ fstab 6 directories, 4 filesCopy the code

6.8 File module: Modifies file properties

[root@nfs ~]# ansible-doc -s file - name: Sets attributes of files file: force: # force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists and is a file (so, We need to unlink the "path" file and create symlink to the "SRC" file in place of it). The source file does not exist (will appear later) or the destination file does exist and is a file (will cancel the path specified file and create a link) # Name of the group that should own the file/directory, as would be fed to 'chown'. # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal Number (like '0644' or' 01777'). # Name of the user that should own the file/directory, as would be fed to 'chown'. # path to the file being managed. Aliases: 'dest',' name' # recursively excites the specified file attributes using a specified exciter # path of the file to link to (applies only to `state=link' and `state=hard'). Will accept absolute, Relative and nonExisting Paths. relative Paths are not expanded. # File path to link to (for state=link and state= Hard only). Absolute, relative, and nonexistent paths are accepted. Relative paths are not expanded. state: # If `directory', All intermediate subdirectories will be created if they do not exist. Since Ansible 1.7 they will be created with the supplied permissions. If `file', the file will NOT be created if it does not exist; see the `touch' value or the [copy] or [template] module if you want that behavior. If `link', the symbolic link will be created or changed. Use `hard' for hardlinks. If `absent', directories will be recursively deleted, and files or symlinks will be unlinked. Note that `absent' will not cause `file' to fail if the `path' does not exist as If 'touch' (new in 1.4), an empty file will be created If the' path' does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way `touch` works from the command line). If it is a directory, the parent directory is automatically created if it does not exist. If it is a file, it will not be created if the file does not exist. If it is a link, it will be created or changed. If absent, the directory will be deleted recursively and the file or link will be unlinked. If touch, a nonexistent file will be created. The directory will change access time and change time.Copy the code

** Example 1: ** Change the owner of np1.lxk.com/TMP /fstab. TXT to mygrp and permission to 660

[root@nfs ~]# ansible np1.lxk.com -m file -a 'path=/tmp/fstab.txt group=mygrp mode=0660'
np1.lxk.com | SUCCESS => {
    "changed": true, 
    "gid": 200, 
    "group": "mygrp", 
    "mode": "0660", 
    "owner": "user2", 
    "path": "/tmp/fstab.txt", 
    "size": 595, 
    "state": "file", 
    "uid": 1024
}
Copy the code

View the properties of the target host file:

[root@np1 ~]# ll -d /tmp/fstab.txt 
-rw-rw---- 1 user2 mygrp 595 Jun  9 12:25 /tmp/fstab.txt
Copy the code

** Example 2: ** Create a soft link/TMP /fstab. TXT on the np1.lxk.com host

[root@nfs ~]# ansible np1.lxk.com -m file -a 'path=/tmp/fstab.link src=/tmp/fstab.txt  state=link'
np1.lxk.com | SUCCESS => {
    "changed": true, 
    "dest": "/tmp/fstab.link", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 14, 
    "src": "/tmp/fstab.txt", 
    "state": "link", 
    "uid": 0
}
Copy the code

** Example 3: ** Create directory file.dir in/TMP of np1.lxk.com with permission 770

[root@nfs ~]# ansible np1.lxk.com -m file -a 'path=/tmp/file.dir mode=0770 state=directory'
np1.lxk.com | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0770", 
    "owner": "root", 
    "path": "/tmp/file.dir", 
    "size": 4096, 
    "state": "directory", 
    "uid": 0
}
Copy the code

6.9 GEt_URL: downloads files

** Example: ** Download a file to/TMP on np1.lxk.com

[root@nfs ~]# ansible np1.lxk.com -m get_url -a 'dest=/tmp/ url=https://mirrors.aliyun.com/centos/7.5.1804/paas/x86_64/openshift-origin36/jq-devel-1.5-1.el7.x86_64.rpm 'np1.lxk.com  | SUCCESS => { "changed": true, "checksum_dest": null, "checksum_src": "C566cb3df854f4551da1ab7f642e96889b77439c", the "dest" : "/ TMP/jq - devel - 1.5-1. El7. X86_64. RPM", "gid" : 0, "group" : "root", "md5sum": "43f5092eadb4855fb780e67244d997df", "mode": "0644", "msg": "OK (6472 bytes)", "owner": "root", "size": 6472, "src": "/tmp/tmpwix52V", "state": "file", "status_code": 200, "uid": 0, "url": "Https://mirrors.aliyun.com/centos/7.5.1804/paas/x86_64/openshift-origin36/jq-devel-1.5-1.el7.x86_64.rpm"}Copy the code

View files on the target host/TMP:

[root@np1 ~]# ls/TMP file.dir fstab.link fstab.txt jq-vel -1.5-1.el7.x86_64.rpmCopy the code

6.10 CRon module: Creates periodically scheduled tasks

** Example 1: ** Create a time synchronization task that runs every 5 minutes.

[root@nfs ~]# ansible np1.lxk.com -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 192.168.200.254 &> /dev/null' name=timesync"
np1.lxk.com | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "timesync"
    ]
}
Copy the code

View the task on the target host:

[root@np1 ~]# crontab -l
#Ansible: timesync          # indicates that this is generated by ansible and the identifier is called timesync*/5 * * * * /usr/sbin/ntpdate 192.168.200.254&> /dev/nullCopy the code

** Example 2: ** Delete the previously created scheduled task. Ansible deletes a scheduled task according to the name defined by name.

[root@nfs ~]# ansible np1.lxk.com -m cron -a "state=absent name=timesync"
np1.lxk.com | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
Copy the code

The task list of the target host is empty.

6.11 Yum modules: Manage software with the YUM package manager

[root@nfs ~]# ansible-doc -s yum - name: Manages packages with the `yum' package manager yum: conf_file: # The remote yum configuration file to use for The transaction. # The remote yum configuration file to use for The transaction. # Install (' present' or 'installed',' latest'), or remove (' absent' or 'removed') a package. Presetn: Latest, installed, latest # (required) A package name, or package specifier with version, like 'name-1.0'. Specify the software name skip_BROKEN: # Resolve depsolve problems by removing packages that are causing problems from the transaction. # When using latest, Only update installed packages. Do not install packages. Has an effect only if state is' latest'Copy the code

** Example 1: ** Install or check whether the Nginx software is installed

[root@nfs ~]# ansible all -m yum -a "name=nginx state=installed" nfs.lxk.com | SUCCESS => { "changed": false, "msg": "", "rc": 0, "results": [" 1: nginx - 1.12.2-2. El7. X86_64 providing nginx is already installed "]} np1.lxk.com | SUCCESS = > {" changed ": false, "msg": "", "rc": 0, "results": [" 1: nginx - 1.12.2-2. El7. X86_64 providing nginx is already installed "]} np2.lxk.com | SUCCESS = > {" changed ": False, "MSG ": "", "rc": 0, "results": ["1:nginx-1.12.2-2.el7.x86_64 Providing Nginx is already installed"]}Copy the code

** Example 2: ** Uninstall nginx

[root@nfs ~]# ansible all -m yum -a "name=nginx state=absent" nfs.lxk.com | SUCCESS => { "changed": true, "msg": ""," rc ": 0,..................... It's too long, don't stick it. You can see Erasing in the return, …………Copy the code

Example 3: * * * * using np1.lxk.com hosts/etc /. Yum repos. D/repobak/base. Repo HTTPD installed software

[root@nfs ~]# ansible np1.lxk.com -m yum -a "name=httpd state=installed conf_file=/etc/yum.repos.d/repobak/base.repo" np1.lxk.com | SUCCESS => { "changed": true, "msg": "", "rc": 0, "results": ["Resolving Dependencies\n--> Running transaction check\n-- > Package httpD.x86_64 0:2.4.6-80.el7. Centos will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n httpd X86_64 2.4.6-80.el7. Centos Base 2.7m \n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal Download size: 2.7m \nInstalled size: 9.4m \nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test Succeeded \nRunning Transaction \n Installing: HTTPD-2.6.6-80.el7.centos.x86_64 1/1 \n Verifying: Httpd-2.4.6-80.el7.centos.x86_64 1/1 \n\nInstalled:\n httpD.x86_64 0:2.4.6-80.el7.centos \n\nComplete!\n"]} This is how it actually looks. A little ugly. But the installation worked.Copy the code

** Example 4: ** Update cache and install HTTPD

[root@nfs ~]# ansible np2.lxk.com -m yum -a "name=httpd state=installed update_cache=yes" np2.lxk.com | SUCCESS => { "changed": false, "msg": "", "rc": 0, "results": [" HTTPD-2.1.6-80.el7.centos. X86_64 Providing HTTPD is already installed"]}Copy the code

6.12 hostname module: manages host names. Usually, only one hostname can be set at a time.

[root@nfs ~]# ansible-doc -s hostname
- name: Manage hostname
  hostname:
      name:                  # (required) Name of the host
Copy the code

Example:

[root@nfs ~]# ansible np1.lxk.com -m hostname -a "name=np1"
np1.lxk.com | SUCCESS => {
    "ansible_facts": {
        "ansible_domain": "lxk.com", 
        "ansible_fqdn": "np1.lxk.com", 
        "ansible_hostname": "np1", 
        "ansible_nodename": "np1"
    }, 
    "changed": true, 
    "name": "np1"
}
Copy the code

6.12 the git module

[root@nfs ~]# ansible-doc -s git - name: Deploy software (or files) from git checkouts git: clone: # If `no', do not clone the repository if it does not exist locally dest: # (required) The path of where the repository should be checked out. This parameter is required, unless `clone' is set to `no'. repo: # (required) git, SSH, or HTTP(S) protocol address of the git repository version: # What version of the repository to check out. # Specify the version to clone.Copy the code

Example: download kubernetes to/TMP /kubernetes/

[root@nfs ~]# ansible np1.lxk.com -m git -a 'repo="https://github.com/kubernetes/kubernetes.git" dest=/tmp/kubernetes'
#Wait for the download
Copy the code

Check the download status of the target host:

[root@np1 ~]# move ├── branches ├── Config ├── description ├─ HEAD ├── Hooks │ ├── applypatch-msg. Sample │ ├── up-up-.sample │ ├─ Up-up-.sample │ ├─ Pre-applypatch.sample │ ├─ Sample │ ├── exercises │ ├─ exercises │ ├─ exercises │ ├─ exercises │ ├─ exercises │ ├─ exercises │ ├─ exercises Info │ ├── ─ Objects │ ├── Info │ ├── Pack │ ├── Heads │ ├── tags 10 directories, 13 files [root@np1 ~]# du -sh /tmp/kubernetes 100K /tmp/kubernetes#You can see that the directory has been created, but the file is still small due to slow download.
Copy the code

Manages Python Library Dependencies

[root@nfs ~]# ansible-doc -s pip - name: Manages Python library dependencies pip: name: # The name of a Python library to install or The URL of The remote package. As of 2.2 you can supply a list of names. # specifies the name, which can also be specified as a URL. The name list is supported after version 2.2. state: # The state of module The 'forcereinstall' option is only available in Ansible 2.1 and above. The version number to install of The Python library specified in The 'name' parameterCopy the code

6.14 NPM module: Manage Node.js Packages with NPM

[root@nfs ~]# ansible-doc -s npm - name: Manage node.js packages with npm npm: name: # The name of a node.js library to install # The name of a node.js library to install State: # The state of The node.js library version: # The version to be installedCopy the code

6.15 Service module: Manages services

[root@nfs ~]# ansible-doc -s service - name: Manage services service: arguments: # Additional arguments provided on the command line enabled: # Whether the service should start on boot. *At least one of state and enabled are required. # (required) Name of the service. Service name pattern: # If the service does not respond to the status command, name a substring to look for as would be found in the output of the `ps' command as a stand- in for a status result. If the string is found, the service will be assumed to be running. runlevel: # For OpenRC init scripts (ex: Gentoo) only The runlevel that this service belongs to. # runlevel sleep: # If the service is being `restarted' then sleep this many seconds between the stop and start command. This helps to Workaround badly behaving init scripts that exit immediately after signaling a process to stop. This option sets how long you sleep before restarting the service after it is turned off. state: # `started'/`stopped' are idempotent actions that will not run commands unless necessary. `restarted' will always bounce  the service. `reloaded' will always reload. *At least one of state and enabled are required.* Note that reloaded will start the service if it is not already started, Even if your feature init system wouldn 't normally. # started: open service # stoped: close the service # restarted: # reloaded restart service: When reloaded the service #reloaded, it is started if the service is not started.Copy the code

** Example: ** Start the HTTPD service and set it to start on startup

[root@nfs ~]# ansible all -m service -a "name=httpd state=started enabled=yes" nfs.lxk.com | SUCCESS => { "changed": true, "enabled": true, "name": "httpd", "state": "started", "status": { "ActiveEnterTimestampMonotonic": "0", "ActiveExitTimestampMonotonic": "0", "ActiveState": "inactive", "After": "remote-fs.target basic.target network.target nss-lookup.target tmp.mount system.slice -.mount systemd-journald.socket", "AllowIsolate": "no", "AmbientCapabilities": "0", ………… Too long to copy …………Copy the code

Check the service status of all nodes:

/ root @ NFS ~ # ansible all -m shell - a "ss - TNLP | grep 80" np1.lxk.com | SUCCESS | rc = 0 > > LISTEN 0 127.0.0.1 128:6379 *:* users:(("redis-server",pid=8077,fd=4)) LISTEN 0 128 :::80 :::* users:(("httpd",pid=14265,fd=4),("httpd",pid=14264,fd=4),("httpd",pid=14263,fd=4),("httpd",pid=14262,fd=4),("httpd",pid= 14261,fd=4),("httpd",pid=14260,fd=4)) np2.lxk.com | SUCCESS | rc=0 >> LISTEN 0 128 :::80 :::* users:(("httpd",pid=14845,fd=4),("httpd",pid=14844,fd=4),("httpd",pid=14842,fd=4),("httpd",pid=14841,fd=4),("httpd",pid= 14840,fd=4),("httpd",pid=14838,fd=4)) nfs.lxk.com | SUCCESS | rc=0 >> LISTEN 0 128 :::80 :::* users:(("httpd",pid=6953,fd=4),("httpd",pid=6952,fd=4),("httpd",pid=6951,fd=4),("httpd",pid=6950,fd=4),("httpd",pid=6949 ,fd=4),("httpd",pid=6948,fd=4)) [root@nfs ~]# ansible all -m shell -a "systemctl is-enabled httpd" np2.lxk.com | SUCCESS  | rc=0 >> enabled np1.lxk.com | SUCCESS | rc=0 >> enabled nfs.lxk.com | SUCCESS | rc=0 >> enabled#The HTTPD service on all nodes starts upon startup
Copy the code

6.16 Setup module: Get the facts of the target host

Usage:

[root@nfs ansible_workshop]# ansible np1.lxk.com -m setup 
Copy the code

All host facts obtained using the Setup module can be called directly as variables in the YAML file, and references can be separated by a dot if fatCs are nested.

6.17 Template:

Similar to the copy module

[root@nfs ansible_workshop]# ansible-doc -s template - name: Templates a file out to a remote server template: src: # (required) Path of a Jinja2 formatted template on the Ansible controller. This can be a relative or absolute path. # Must, source Jinja2 format template dest: # (required) Location to render the template to the remote machine. # (required) Location to render the template to the remote machine. # Name of the group that should own the file/directory, as would be fed to 'chown'. The name specified here will be sent to "chown". owner: # Name of the user that should own the file/directory, as would be fed to 'chown'. The name specified here will be sent to "chown". mode: # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal Numbers (like '0644' or' 01777'). Format: '0644' or' 01777'Copy the code