In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/03 Report--
Common modules of Ansible
The modules included in this section:
(1) shell and command
(2) copy module copy
(3) template module
(4) File module file
(5) pull file module fetch
(6) rsync module synchronize
You can find the desired module from ansible-doc-l | grep module_name. Then use ansible-doc-s module_name to see the usage of this module.
Official module list and description: https://docs.ansible.com/ansible/latest/modules_by_category.html
With regard to the use of the module, it is important to note that state. Many modules have this option, and almost all of their values contain present and absent, which means yes and no.
Most modules of ansible are idempotent naturally, and only a few modules such as shell and command modules are not idempotent. The so-called idempotency means that performing the same operation multiple times does not affect the final result. For example, when the yum module of ansible installs the rpm package, if the package to be installed has already been installed, performing the installation operation again or multiple times will not actually be performed.
"for example, when the copy module copies a file, if the exact same file already exists on the target host, executing the copy module multiple times will not actually copy it." Ansible idempotent modules will automatically determine whether to execute or not when they are executed.
Shell and command
The module used by the default ansible is command, which means you can execute some shell commands. The use of shell is basically the same as that of command. In fact, the shell module executes commands remotely using / bin/sh, such as / bin/sh ping.
Command cannot parse variables such as $HOME and some operators "," | ","; "and" & ", so use the shell module instead of command when it is clear that you want to use these unresolvable operators.
Shell--Ansible official instruction document
Command--Ansible official instruction document
Ansible-doc-s shell- name: Execute commands in nodes. Action: shell chdir # before executing the command, cd to the specified directory creates # to determine whether the command is to be executed. If the specified file (which can use wildcards) exists, it is not executed. Removes # is used to determine whether the command is to be executed. If the specified file (which can use wildcards) does not exist, it is not executed. Instead of parsing and executing commands using the default / bin/sh, executable # parses using the commands specified here. # for example, use expect to parse expect scripts. Must be an absolute path.
When using shell or command modules in ansible, it is important to note that they are not idempotent by default, and many operations are repeated, but some operations are not allowed to be repeated. For example, mysql's initialization command mysql _ ins t all_db, which can only be initialized once during the first configuration, is not allowed to be executed at any other time if it is not necessary. To achieve idempotency at this time, you can judge by the creates and removes options of the module, but in any case, you need to consider whether the command to be executed should be idempotent or not.
Examples are as follows:
Tasks:-shell: touch helloworld.txt creates=/tmp/hello.txt
However, it is recommended that you use args to pass the parameters of ansible in cases where the parameters may be ambiguous. Such as:
-shell: touch helloworld.txt args: creates: / tmp/hello.txt# You can use shell to run other executables to perform actions inline- name: Run expect to wait for a successful PXE boot via out-of-band CIMC shell: | set timeout 300 spawn ssh admin@ {{cimc_host}} expect "password:" send "{cimc_password}}\ n" expect "\ n {{cimc_name}}" send "connect host\ n" expect "pxeboot.n12 "send"\ n "exit 0 args: executable: / usr/bin/expect delegate_to: localhost replication module copy
Copy--Ansible official instruction document
Ansible-doc-l | grep copy
How to use it:
Ansible-doc-s copy
Ansible-doc-s copy- name: Copy files to remote locations copy: backup= [yes | no]: # the copy also creates a backup file containing timestamp information. The default is no dest: # destination path, which can only be absolute. If the copied file is a directory, Then the target path must also be the directory content: # directly save to the remote host the string or variable value given by content as the file content, it will replace the src option directory_mode: # when you make a recursive copy of the directory, setting directory_mode will make only new files copied, # old files will not be copied. Follow= [yes | no]: # whether to trace the linked source file is not set by default. When force= [yes | no]: # is set to yes (default), the remote file with the same name will be overwritten. When set to no, ignore the copy of the file with the same name group: # set the group to which the remote file belongs, owner: # set the owner of the remote file mode: # set the permissions of the remote file. The first place cannot be omitted when using a numeric representation, such as 0644. # can also be set by using 'uprirwx' or 'uprirwrec', such as glossary, glossary, obsession, etc. Src: # copy local source files to the remote, using either absolute or relative paths. If the path is a directory and the directory is followed by a # slash "/", only the contents of the directory are copied to the remote, and if the directory is not followed by a slash, the contents of the directory itself and the contents of the # directory are copied to the remote.
By default, ansible copy checks the file md5 to see if it needs to be copied, and if it is the same, it will not copy, otherwise it will copy. If force=yes is set, the copy is overwritten when the file md5 is different (that is, the file content is different), and when force=no is set, only the files that are not available to the other party are copied.
Here are several examples to illustrate the backup of the copy module:
(1) when there is no file waiting for copy on the target machine, it is useless to set backup=yes, such as:
Ansible test-m copy-a "src=/tmp/temp/test.pub dest=/tmp backup=yes"-o-f 6
After execution, there is only one copy past test.pub file in the target machine / tmp directory, and there is no backup file like test.pub.3286.2019-11-14-11-14-11-22-22-34 ~.
(2) when the file on the target machine is waiting for copy, but the file on the server side is the same as the file on the target machine (that is, the file on the server side has not changed), it is useless even if backup=yes is set.
(3) when the file on the target machine is waiting for copy, but the file on the server is different from that on the server (that is, the file on the server has been changed). If backup=yes is set, the backup file will appear under the path of the target file on the target machine, such as:
# We change the contents of the test.pub file on the server side, and then execute ansibleansible test-m copy-a "src=/tmp/temp/test.pub dest=/tmp backup=yes"-o-f file. We log in to the target machine / tmp directory to check, and we will find that a backup file appears, that is, test.pub.3286.2019-11-14: 1122 tmp. Its content is the content of the file from the last copy on the server.
If you are copying a directory, the destination path must be a directory path. If you use a "/" ending, the files in the directory are copied, and if they do not end with a slash, the files in the directory plus directory are copied. Examples are as follows:
(1) case 1: end with "/"
# # server end # pwd/tmp/temp# ll-rw-r--r-- 1 root root 0 November 13 11:18 a.log-rwxr-xr-x 1 root root 338 November 13 11:31 auto_sshcopyid.exp-rw- 1 root root 1679 November 13 10:31 id_rsa-rw-r--r-- 1 root root 395 November 13 10:31 id_rsa.pub-rw-r--r-- 1 root root 416 November 13 11: 27 sshkey.sh-rw- 1 root root 1679 November 13 10:34 test-rw-r--r-- 1 root root 342 November 5 10:48 test01.py-rw-r--r-- 1 root root 75 November 5 14:23 test02.py-rw-r--r-- 1 root root 299 November 5 16:18 test03.py-rw-r--r-- 1 root root 371 November 5 18:52 test04.py-rw- Rmuri root root-1 root root 217 November 5 22:26 test05.py-rw-r--r-- 1 root root 60 November 5 22:26 test06.py-rw-r--r-- 1 root root 406 November 14 11:22 test.pub
If execution ends with "/", the files in the directory are copied:
Ansible test-m copy-a "src=/tmp/temp/ dest=/tmp/test"-o-f 6
Check the contents of the target machine / tmp/test directory:
# pwd/tmp/test# ll total usage: 48 pwd/tmp/test# ll RW pwd/tmp/test# ll-1 root root 0 November 14 11:39. LogMurray Rwhaq pwd/tmp/test# ll-1 root root 338 November 14 11:39 auto_sshcopyid.exp-rw-r--r-- 1 root root 1679 November 14 11:39 id_rsa-rw-r--r-- 1 root root 395 November 14 11:39 id_rsa.pub-rw-r--r-- 1 root root 416 November 14 11:39 sshkey.sh-rw-r--r-- 1 root root 1679 November 14 11:39 test-rw-r--r-- 1 root root 342 November 14 11:39 test01.py-rw-r--r-- 1 root root 75 November 14 11:39 test02.py-rw-r--r-- 1 root root 299 November 14 11:39 test03.py-rw-r--r-- 1 root root 371 November 14 11:39 test04.py-rw-r -- r root root-1 root root 217 November 14 11:39 test05.py-rw-r--r-- 1 root root 60 November 14 11:39 test06.py-rw-r--r-- 1 root root 406 November 14 11:39 test.pub
(2) case II: do not end with a slash
If execution does not end with a slash "/", the files in the directory plus directory are copied:
Ansible test-m copy-a "src=/tmp/temp dest=/tmp/test01 backup=yes"-o-f 6
Check the contents of the target machine / tmp/test01 directory:
# total amount of pwd/tmp/test01# ll 0drwxr-xr-x 2 root root 224 November 14 11:40 temp# cd temp# pwd/tmp/test01/temp# ll total amount 48 root root RW pwd/tmp/test01# ll-1 root root 0 November 14 11:40 a. Log RWMui RML-1 root root 338 November 14 11:40 auto_sshcopyid.exp-rw-r--r-- 1 root root 1679 November 14 11:40 id_rsa-rw-r--r -- 1 root root 395 November 14 11:40 id_rsa.pub-rw-r--r-- 1 root root 416 November 14 11:40 sshkey.sh-rw-r--r-- 1 root root 1679 November 14 11:40 test-rw-r--r-- 1 root root 342November 14 11:40 test01.py-rw-r--r-- 1 root root 75 November 14 11:40 test02.py-rw-r--r-- 1 root root 299 November 14 11:40 test03.py-rw-r--r-- 1 root root 371 November 14 11:40 test04.py-rw-r--r-- 1 root root 217 November 14 11:40 test05.py-rw-r--r-- 1 root root 60 November 14 11:40 test06.py-rw-r--r-- 1 root root 406 November 14 11:40 test.pubtemplate module
The usage of the template module is basically the same as that of the copy module, which is mainly used to copy configuration files. Template--Ansible official instruction document
The copy of ansible-doc-s template- name: Template a file out to a remote server template: backup: # also creates a backup file containing timestamp information. If the default is no dest: # destination path force: # set to yes (default), the remote file with the same name will be overwritten. When set to no, ignore the copy of the file with the same name group: # set the group to which the remote file belongs, owner: # set the owner of the remote file mode: # set the permissions of the remote file. The first place cannot be omitted when using a numeric representation, such as 0644. # you can also set the location of the template in Jinja2 format on the src: # ansible controller, such as' uprirwx'or 'upright rwx', etc., which can be a relative or absolute path validate: # execute the command specified by this option after copying to the target host but before placing it in the target location # is generally used to check the syntax of the configuration file. If the syntax is correct, it is saved to the target location. # if you want to reference the target file name, use% s, which in the following example represents / etc/nginx/nginx.conf on the target machine.
Examples are as follows:
Ansible centos-m template-a "src=/tmp/nginx.conf.j2 dest=/etc/nginx/nginx.conf mode=0770 owner=root group=root backup=yes validate='nginx-t-c% s'"-o-f 6
Although the template module can modify the contents of the configuration file as needed to copy the template to the controlled host, there is one situation that it cannot solve: the configuration files required by different controlled nodes are very different, which can not be satisfied by modifying a few variables. For example, nginx installed through yum on centos 6 and centos 7 has very different profile contents, and nginx on centos 6 has a / etc/nginx/conf.d/default.conf by default. If you copy the nginx configuration file of the same template directly to centos 6 and centos 7, it is likely that a certain version of nginx cannot be started.
At this point, it is necessary to copy the template files of the corresponding distribution in pairs when copying the template. For example, the source template to be copied to centos 6 is nginx6.conf.j2, and the source template copied to centos 7 is nginx7.conf.j2. This behavior can be called "selecting a file or template based on variables".
-tasks:-name: template file based var template: src=/templates/nginx {{ansible_distribution_major_version}}. Conf.j2 dest=/etc/nginx/nginx.conf validate= "/ usr/sbin/nginx-t-c% s"
You can also specify an alternative variable for jinja2 in the file content. When ansible executes, it will first render according to the variable content, and then execute the relevant module after rendering. For example, the template module here copies a yum source configuration file based on the release number. The following is the content of a repo file template base.repo.j2.
[epel] name=epelbaseurl= http://mirrors.aliyun.com/epel/{{ ansible_distribution_major_version}} Server/x86_64/ enable=1gpgcheck=0
Just copy it again.
-tasks:-template: src=my.repo.j2 dest=/etc/yum.repos.d/my.repo file module file
Manage the properties of files or directories, or you can create files or directories. File--Ansible official instruction document
Ansible-doc-s file- name: Manage files and file properties file: group: # file/directory belongs to the group owner: # owner of file/directory mode: # modify permission. The format can be 0644, 'uprirwx' or 'uprirwwx', or 'uprirwjournal', such as path: # specify the files to be operated You can use the alias' dest' or 'name' instead of path recurse: # (the default no) to recursively modify the attribute information of the file, requiring the path of the file to be linked to by state=directory src: #. # this only applies to state=link and state=hard. For state=link, this will also accept a path that does not exist. The # relative path is relative to the file (path) being created, which is how the Unix command ln-s SRC DEST handles the relative path. State: # directory: recursively create if the directory does not exist # file: if the file does not exist, it will not be created (default) # touch:touch the file specified by path, that is, create a new file Or modify its mtime and atime # link: modify or create soft links # hard: modify or create hard links # absent: directories and files in them will be deleted recursively, and files or links will be unlinked
It is important to note that the file module can recursively create directories, but cannot create files in directories that do not exist. Instead, you can only create directories and then files in this directory. Let's do a test to verify:
# the directory / root/test does not exist on the controlled machine # use ansible to create foo.confansible test-m file-a "path=/root/test/foo.conf owner=duser group=duser mode='0644' state=touch" under the / root/test directory on the controlled machine
The result of ansible execution is:
192.168.246.187 | FAILED! = > {"changed": false, # # failed "msg": "Error, could not touch target: [Errno 2] does not have that file or directory: baud * "path": "/ root/test/foo.conf"} # now let's create / root/test directory on the controlled machine # execute ansibleansible test-m file-a "path=/root/test/foo.conf owner=duser group=duser mode='0644' state=touch" again
The result of ansible execution is:
192.168.246.187 | CHANGED = > {"changed": true, # # successful "dest": "/ root/test/foo.conf", "gid": 1009, "group": "duser", "mode": "0644", "owner": "duser", "size": 0, "state": "file", "uid": 1009}
Create a directory and recursively modify the properties of the directory.
Ansible test-m file-a "path=/tmp/xyz/test state=directory owner=root group=root mode='0755' recurse=yes"
Modify the permissions of test in the directory / tmp/xyz/test
Ansible test-m file-a "path=/tmp/xyz/test state=directory mode='0777'"
Create or modify file properties / permissions
Ansible test-m file-a "path=/tmp/xyz/test/wtf.txt state=touch mode='0644'"
Pull file module fetch
It works similar to copy, except that files are pulled from a remote host to the local side, and the hostname is used as a directory tree when storing, and only files can be pulled, not directories!
Fetch--Ansible official instruction document
Ansible-doc-s fetch- name: Fetch files from remote nodes fetch: dest: # the directory where the pulled files are stored locally. For example, dest=/data,src=/etc/fstab, # remote hostname host.exp.com, the saved path is / data/host.exp.com/etc/fstab. Fail_on_missing: # when set to yes, this task fails if the pulled source file does not exist. The default is no. Flat: # change the path storage method after pulling. If set to yes, and when dest ends with "/", the basename of the source file # will be stored directly under dest. Obviously, file overwriting when pulled by multiple hosts should be considered. Src: # Source files on the remote host. Can only be files, directories are not supported. Directory recursive pull may be supported in future releases. Validate_checksum: # fetch to the file, check that its md5 is the same as the source file.
Stored as / tmp/192.168.246.187/etc/fstab:
Ansible test-m fetch-a "src=/etc/fstab dest=/tmp"
Stored as / tmp/fstab:
Ansible test-m fetch-a "src=/etc/fstab dest=/tmp/ flat=yes"
Stored as / tmp/fstab-192.168.246.187:
Ansible test-m fetch-a "src=/etc/fstab dest=/tmp/fstab- {{inventory_hostname}} flat=yes"
Here is a point:
The {{inventory_hostname}} above refers to the host alias in / etc/ansible/hosts, such as:
# / etc/ansible/hosts is defined as follows: [test] 192.168.246.187 [test: vars] ansible_ssh_private_key_file=/root/.ssh/rsa_back/id_rsaansible_python_interpreter=/usr/local/python3/bin/python3
In this case, the file name generated by the control side is / tmp/fstab-192.168.246.187.
# / etc/ansible/hosts is defined as follows: [test] nginx ansible_ssh_host= 192.168.246.187 [test: vars] ansible_ssh_private_key_file=/root/.ssh/rsa_back/id_rsaansible_python_interpreter=/usr/local/python3/bin/python3
In this case, the file name generated by the control side is / tmp/fstab-nginx.
Rsync module synchronize
The synchronize module is used to implement the common functions of the simple version of rsync, but it cannot achieve the full version of rsync. After all, rsync has too many functions and is too detailed. If you want to use rsync, you should still use the command or shell module to invoke the rsync command.
For the complete rsync function, see the rsync command manual in Chinese.
Ansible-doc-s synchronize- name: A wrapper around rsync to make common tasks in your playbooks quick and easy synchronize: src: # specifies the source file to be transferred. It can be a relative path or an absolute path. Dest: # destination path. It can be an absolute path or a relative path. Mode: # specifies the transmission mode of push or pull. In the case of # push, the local end is the sender side, and in the case of pull, the remote is the sender side. The default is push. Archive: # is equivalent to the "- a" option of rsync, even in archive mode. It is equivalent to the "- rtopgDl" option of rsync. The value is yes/no. Times: # retains the mtime attribute with a value of yes/no. Group: # retains the attribute of the group to which it belongs, with a value of yes/no. Owner: # retains the owner attribute with a value of yes/no. Links: # copy the linked file itself, with a value of yes/no. Perms: # preserves the permission attribute with a value of yes/no. Recursive: # A file recursively into the directory with a value of yes/no. Compress: # compress transmission during transmission. It should always be turned on unless there is a problem. This is the "- z" option of rsync. The value is yes/no and the default is yes. Copy_links: # copy the file name of the soft link and the contents of the file it points to. That is, when a points to a b file, a normal # file will be generated on the target side, but the contents of this file are the contents of b. Dirs: # non-recursive transfer of directories. Delete: # if there are more files on the destination side than on the source side, delete these extra files and require recursive=yes. Checksum: # is equivalent to the "- c" option and will determine whether to synchronize based on the checksum of the file, rather than the default quick check # algorithm, which determines whether to synchronize based on the file size and the most recent mtime. This option will greatly reduce efficiency and # should be used with caution. Note that it does not affect archive, that is, archive is still enabled. Files not available on the existing_only:# receiver side are out of sync. However, it will still be transferred, but the temporary files will not be renamed after reorganization. Partial: # is equivalent to the "--partial" option. The default rsync deletes half-transferred files when the transfer is interrupted, and specifying this option # will retain these incomplete files so that the next transfer can start directly with uncompleted blocks. Dest_port: the connection port of # ssh. Rsync_opts: # specifies additional rsync options. Use an array to pass these options. Rsync_path: # is equivalent to the "--rsync-path" option to start the remote rsync. # for example, you can specify [--rsync-path=rsync], or even [--rsync-path=cd / tmp/c & & rsync]. # when the rsync path is not specified, the default is / usr/bin/rysnc. Rsync_timeout:# specifies how long the rsync times out before data transmission occurs. Verify_host: # perform host key verification of ssh on the target host. Description
This blog is a reference to Ma long Shuai boss article collation and generation, belongs to the blogger reading notes, if there is infringement, please contact me, delete!
Finally, thank open source, embrace open source ~
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.