Asible study notes - common module (a)

Ansible common module

From ansible-doc -l | grep module_nameto find the module you want to. Then use ansible-doc -s module_nameto view this module usage.

Official module list and description: https://docs.ansible.com/ansible/latest/modules_by_category.html

On how to use the module, to note that state. Many modules will have the option and its value almost all contain presentand absentindicate positive and negative meaning.

The vast majority of natural ansible module idempotent characteristics, only a few modules, such as shell and command module does not have idempotent. The so-called Idempotence refers repeatedly perform the same operation will not affect the final result. For example, ansible's yum install rpm package modules, to be installed if the package has been installed, and then again perform the installation or operation many times will not be truly implemented.

As another example, when the copy module copies the file, if you already have the exact same files on the target host, then repeatedly executed copy module does not actually copy. ansible idempotent module, when executed, determines whether to execute automatically.

and command shell

Ansible using default module commandthat can perform some shell commands. usage command shell and substantially the same way to actually execute the command module shell is remotely / bin / sh performed, such as / bin / sh ping.

command can not be resolved, such as variables $HOMEand some operators "<", ">", "|", ";"以及"&", the use of these so clear to unresolvable operator, instead of using the shell command module.

shell - Ansible official use of documentation

command - Ansible official use of documentation

ansible-doc -s shell
- name: Execute commands in nodes.
       action: shell
    chdir          # 在执行命令前,先cd到指定的目录下
    creates        # 用于判断命令是否要执行。如果指定的文件(可以使用通配符)存在,则不执行。
    removes        # 用于判断命令是否要执行。如果指定的文件(可以使用通配符)不存在,则不执行。
    executable     # 不再使用默认的/bin/sh解析并执行命令,而是使用此处指定的命令解析。
                   # 例如使用expect解析expect脚本。必须为绝对路径。

Use shell or command module ansible must pay attention, they are not satisfied with the default idempotency, many operations will be performed repeatedly, but some operations are not allowed to repeat execution. For example mysql initialization commands mys ql_ins t all_db, it can only be initialized once during the first configuration, at any other time if not required, are not allowed. This time to achieve idempotency, through the module createsand removesto judge options, but in any case, in the implementation of these two modules will need to consider whether the command to be executed should be implemented idempotency.

Examples are as follows:

tasks:
  - shell: touch helloworld.txt creates=/tmp/hello.txt

But suggested that, in the case of possible ambiguous parameters, the use of args to pass parameters ansible. 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

Copy copy module

copy - Ansible official use of documentation

ansible-doc -l |grep copy

Instructions:

ansible-doc -s copy

ansible-doc -s copy
- name: Copy files to remote locations
  copy:
      backup=[yes|no]:   # 拷贝的同时也创建一个包含时间戳信息的备份文件,默认为no
      dest:              # 目标路径,只能是绝对路径,如果拷贝的文件是目录,则目标路径必须也是目录
      content:           # 直接以content给定的字符串或变量值作为文件内容保存到远程主机上,它会替代src选项
      directory_mode:    # 当对目录做递归拷贝时,设置了directory_mode将会使得只拷贝新建文件,
                         # 旧文件不会被拷贝。默认未设置
      follow=[yes|no]:   # 是否追踪到链接的源文件。
      force=[yes|no]:    # 设置为yes(默认)时,将覆盖远程同名文件。设置为no时,忽略同名文件的拷贝
      group:             # 设置远程文件的所属组
      owner:             # 设置远程文件的所有者
      mode:              # 设置远程文件的权限。使用数值表示时不能省略第一位,如0644。
                         # 也可以使用'u+rwx'或'u=rw,g=r,o=r'等方式设置。
      src:               # 拷贝本地源文件到远程,可使用绝对路径或相对路径。如果路径是目录,且目录后加了
                         # 斜杠"/",则只会拷贝目录中的内容到远程,如果目录后不加斜杠,则拷贝目录本身和
                         # 目录内的内容到远程。

By default, ansible copy will check to see if you need to copy files md5, the same will not copy, otherwise it will be copied. If the set force = yes, then when the file is not the same (i.e. the contents of different files) covers only MD5 copy, set force = no, not only other copy of the file.

About copy module backupherein using several examples below:

(1) when the file is not to be copy on the target machine, even if the set backup=yesis not useful, such as:

ansible test -m copy -a "src=/tmp/temp/test.pub dest=/tmp backup=yes" -o -f 6

After execution, the next target machine / tmp directory is only one copy of test.pub file past, did not like test.pub.3286.2019-11-14@11:22:34~such a backup file appears ~

(2) when the target has to be copy of the file, but the server end and the target file is the same (ie the server end of the file has not changed), even if the set backup=yesis of little use.

(3) when the file on the target machine has to be copy, but the files on the server end and the target is not the same (ie, server end of the document made changes), set up backup=yes, the backup file will appear on the target machine at the destination file path ,Such as:

# 我们更改下server端 test.pub 文件的内容,然后执行ansible
ansible test -m copy -a "src=/tmp/temp/test.pub dest=/tmp backup=yes" -o -f 6

# 我们登入到目标机上 /tmp 目录下查看,会发现有一个备份文件出现,即 test.pub.3286.2019-11-14@11:22:34~ ,它的内容就是上次 server 端copy过来的文件内容~

If you copy a directory, the target path must be a directory path. If you use the ending "/", then copy the files in the directory is, if you do not end with a slash, plus a copy of the directory files in the directory. For example as follows:

(1) Case 1: Use the end of "/"

## server端

# pwd
/tmp/temp
# ll
-rw-r--r-- 1 root root    0 11月 13 11:18 a.log
-rwxr-xr-x 1 root root  338 11月 13 11:31 auto_sshcopyid.exp
-rw------- 1 root root 1679 11月 13 10:31 id_rsa
-rw-r--r-- 1 root root  395 11月 13 10:31 id_rsa.pub
-rw-r--r-- 1 root root  416 11月 13 11:27 sshkey.sh
-rw------- 1 root root 1679 11月 13 10:34 test
-rw-r--r-- 1 root root  342 11月  5 10:48 test01.py
-rw-r--r-- 1 root root   75 11月  5 14:23 test02.py
-rw-r--r-- 1 root root  299 11月  5 16:18 test03.py
-rw-r--r-- 1 root root  371 11月  5 18:52 test04.py
-rw-r--r-- 1 root root  217 11月  5 22:26 test05.py
-rw-r--r-- 1 root root   60 11月  5 22:26 test06.py
-rw-r--r-- 1 root root  406 11月 14 11:22 test.pub

Performed using the end of "/", then copy the files in the directory are:

ansible test -m copy -a "src=/tmp/temp/ dest=/tmp/test" -o -f 6

View the target machine / tmp / test directory contents:

# pwd
/tmp/test
# ll
总用量 48
-rw-r--r-- 1 root root    0 11月 14 11:39 a.log
-rw-r--r-- 1 root root  338 11月 14 11:39 auto_sshcopyid.exp
-rw-r--r-- 1 root root 1679 11月 14 11:39 id_rsa
-rw-r--r-- 1 root root  395 11月 14 11:39 id_rsa.pub
-rw-r--r-- 1 root root  416 11月 14 11:39 sshkey.sh
-rw-r--r-- 1 root root 1679 11月 14 11:39 test
-rw-r--r-- 1 root root  342 11月 14 11:39 test01.py
-rw-r--r-- 1 root root   75 11月 14 11:39 test02.py
-rw-r--r-- 1 root root  299 11月 14 11:39 test03.py
-rw-r--r-- 1 root root  371 11月 14 11:39 test04.py
-rw-r--r-- 1 root root  217 11月 14 11:39 test05.py
-rw-r--r-- 1 root root   60 11月 14 11:39 test06.py
-rw-r--r-- 1 root root  406 11月 14 11:39 test.pub

(2) Case 2: no ending slash

It does not end with a slash "/", the copy is added to the directory files in the directory:

ansible test -m copy -a "src=/tmp/temp dest=/tmp/test01 backup=yes" -o -f 6

View the target machine / tmp / directory content test01:

# pwd
/tmp/test01
# ll
总用量 0
drwxr-xr-x 2 root root 224 11月 14 11:40 temp
# cd temp
# pwd
/tmp/test01/temp
# ll
总用量 48
-rw-r--r-- 1 root root    0 11月 14 11:40 a.log
-rw-r--r-- 1 root root  338 11月 14 11:40 auto_sshcopyid.exp
-rw-r--r-- 1 root root 1679 11月 14 11:40 id_rsa
-rw-r--r-- 1 root root  395 11月 14 11:40 id_rsa.pub
-rw-r--r-- 1 root root  416 11月 14 11:40 sshkey.sh
-rw-r--r-- 1 root root 1679 11月 14 11:40 test
-rw-r--r-- 1 root root  342 11月 14 11:40 test01.py
-rw-r--r-- 1 root root   75 11月 14 11:40 test02.py
-rw-r--r-- 1 root root  299 11月 14 11:40 test03.py
-rw-r--r-- 1 root root  371 11月 14 11:40 test04.py
-rw-r--r-- 1 root root  217 11月 14 11:40 test05.py
-rw-r--r-- 1 root root   60 11月 14 11:40 test06.py
-rw-r--r-- 1 root root  406 11月 14 11:40 test.pub

template module

template module usage and copy module uses basically the same, it is mainly used to copy the configuration file. template - Ansible official use of documentation

ansible-doc -s template
- name: Template a file out to a remote server
  template:
      backup:   # 拷贝的同时也创建一个包含时间戳信息的备份文件,默认为no
      dest:     # 目标路径
      force:    # 设置为yes (默认)时,将覆盖远程同名文件。设置为no时,忽略同名文件的拷贝
      group:    # 设置远程文件的所属组
      owner:    # 设置远程文件的所有者
      mode:     # 设置远程文件的权限。使用数值表示时不能省略第一位,如0644。
                # 也可以使用'u+rwx' or 'u=rw,g=r,o=r'等方式设置
      src:      # ansible控制器上Jinja2格式的模板所在位置,可以是相对或绝对路径
      validate: # 在复制到目标主机后但放到目标位置之前,执行此选项指定的命令。
                # 一般用于检查配置文件语法,语法正确则保存到目标位置。
                # 如果要引用目标文件名,则使用%s,下面的示例中的%s即表示目标机器上的/etc/nginx/nginx.conf。

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 configuration file can be modified according to the needs of content to copy the template to the accused on the host, but there is a situation which can not be solved: Different charged with large differences in the required node configuration file is not modified to meet several variables . In the example 6 and by centos yum. 7 mounted on centos nginx, their content profiles a very large difference, and the default nginx on centos 6 there is a /etc/nginx/conf.d/default.conf. If nginx configuration files directly copy the same template to the centos 6 and centos 7, it is likely to lead to a version of nginx will not start.

At this point it is necessary to choose the corresponding release template file copying when copying the template matching, for example, you want to copy to the source template on 6 centos is nginx6.conf.j2, copied to the source template on 7 centos is nginx7.conf. j2. This behavior can be called "variable selection based on file or template."

---
 - 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 alternative variable jinja2 in the content of the document, the first will be rendered in accordance with the implementation of variable content in ansible, and then render the implementation of the relevant module. For example, template module here, a copy of the yum-based release number of the source profile. The following is a repo file template base.repo.j2 content.

[epel]
name=epel
baseurl=http://mirrors.aliyun.com/epel/{{ ansible_distribution_major_version }}Server/x86_64/ enable=1
gpgcheck=0

And then copy it.

---
 - tasks:
     - template: src=my.repo.j2 dest=/etc/yum.repos.d/my.repo

File module file

File management, directory attributes can also create a file or directory. file - Ansible official use of documentation

ansible-doc -s file
- name: Manage files and file properties
  file:
      group:   # file/directory的所属组
      owner:   # file/directory的所有者
      mode:    # 修改权限,格式可以是0644、'u+rwx'或'u=rw,g=r,o=r'等
      path:    # 指定待操作的文件,可使用别名'dest'或'name'来替代path
      recurse: # (默认no)递归修改文件的属性信息,要求state=directory
      src:     # 要链接到的文件的路径。
               # 这只适用于state=link和state=hard。
               # 对于state=link,这也将接受一个不存在的路径。
               # 相对路径相对于正在创建的文件(路径),这是Unix命令ln -s SRC DEST处理相对路径的方式。
      state:   # directory:如果目录不存在则递归创建
               # file:文件不存在时,不会被创建(默认值)
               # touch:touch由path指定的文件,即创建一个新文件,或修改其mtime和atime
               # link:修改或创建软链接
               # hard:修改或创建硬链接
               # absent:目录和其中的文件会被递归删除,文件或链接将取消链接状态

It should be noted, file module can recursively create directories, but can not create files in the directory does not exist, you can only create a directory, then create a file in this directory. We have to be verified under test:

# 被控制机上并不存在/root/test这个目录
# 使用ansible在被控制机上/root/test目录下创建foo.conf
ansible test -m file -a "path=/root/test/foo.conf owner=duser group=duser mode='0644' state=touch"

ansible execution result is:

192.168.246.187 | FAILED! => {
    "changed": false,    ## 失败
    "msg": "Error, could not touch target: [Errno 2] 没有那个文件或目录: b'/root/test/foo.conf'",
    "path": "/root/test/foo.conf"
}
# 现在我们在被控制机上创建/root/test目录
# 再次执行ansible
ansible test -m file -a "path=/root/test/foo.conf owner=duser group=duser mode='0644' state=touch"

ansible execution result is:

192.168.246.187 | CHANGED => {
    "changed": true,  ## 成功
    "dest": "/root/test/foo.conf",
    "gid": 1009,
    "group": "duser",
    "mode": "0644",
    "owner": "duser",
    "size": 0,
    "state": "file",
    "uid": 1009
}

Create a directory and recursively modifying directory attributes.

ansible test -m file -a "path=/tmp/xyz/test state=directory owner=root group=root mode='0755' recurse=yes"

Modify the directory / tmp / xyz / test in the test authority

ansible test -m file -a "path=/tmp/xyz/test state=directory mode='0777'"

Create or modify file attributes / permissions

ansible test -m file -a "path=/tmp/xyz/test/wtf.txt state=touch mode='0644'"

Pulling fetch file module

And works like a copy, simply file from a remote host will pull to the local side, use the host name as the directory tree when stored, and only pull files can not be pulled directory!

fetch - Ansible official use of documentation

ansible-doc -s fetch
- name: Fetch files from remote nodes
  fetch:
      dest:              # 本地存储拉取文件的目录。例如dest=/data,src=/etc/fstab,
                         # 远程主机名host.exp.com,则保存的路径为/data/host.exp.com/etc/fstab。
      fail_on_missing:   # 当设置为yes时,如果拉取的源文件不存在,则此任务失败。默认为no。
      flat:              # 改变拉取后的路径存储方式。如果设置为yes,且当dest以"/"结尾时,将直接把源文件
                         # 的basename存储在dest下。显然,应该考虑多个主机拉取时的文件覆盖情况。
      src:               # 远程主机上的源文件。只能是文件,不支持目录。在未来的版本中可能会支持目录递归拉取。
      validate_checksum: # fetch到文件后,检查其md5和源文件是否相同。

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 to point out:

The {{inventory_hostname}} The above refers to a host alias / etc / ansible / hosts in, such as:

# /etc/ansible/hosts如下定义:
[test]
192.168.246.187
[test:vars]
ansible_ssh_private_key_file=/root/.ssh/rsa_back/id_rsa
ansible_python_interpreter=/usr/local/python3/bin/python3

Control terminal generated in this case the file name is /tmp/fstab-192.168.246.187.

# /etc/ansible/hosts如下定义:
[test]
nginx ansible_ssh_host=192.168.246.187
[test:vars]
ansible_ssh_private_key_file=/root/.ssh/rsa_back/id_rsa
ansible_python_interpreter=/usr/local/python3/bin/python3

Generating a control terminal in this case is the file name / tmp / fstab-nginx.

rsync module synchronize

synchronize means for implementing a simple version of rsync common functions, it can not realize the full version of rsync, rsync, after all, too many features too detailed. If you are using rsync, or you should use command or shell module to invoke the rsync command.

See the complete functionality rsync rsync command Chinese manual .

ansible-doc -s synchronize
- name: A wrapper around rsync to make common tasks in your playbooks quick and easy
  synchronize:
      src:           # 指定待传输的源文件。可以是相对路径,也可以是绝对路径。
      dest:          # 目标路径。可以是绝对路径,也可以是相对路径。
      mode:          # 指定推(push)还是拉(pull)的传输模式。
                     # push时,本地为sender端,pull时,远程为sender端。默认为push。
      archive:       # 等价于rsync的"-a"选项,即使用归档模式。它等价于rsync的"-rtopgDl"选项。值为yes/no。
      times:         # 保留mtime属性,值为yes/no。
      group:         # 保留所属组属性,值为yes/no。
      owner:         # 保留所有者属性,值为yes/no。
      links:         # 拷贝链接文件自身,值为yes/no。
      perms:         # 保留权限属性,值为yes/no。
      recursive:     # 递归到目录中的文件,值为yes/no。
      compress:      # 传输过程中压缩传输。应该总是开启,除非遇到问题。即rsync的"-z"选项。值为yes/no,默认是yes。
      copy_links:   # 拷贝软链接的文件名和其指向的文件的内容。即a指向b文件时,将在目标端生成a普通
                     # 文件,但此文件中的内容是b中的内容。
      dirs:         # 非递归方式传输目录。
      delete:       # 目标端如果比源端文件多,则删除这些多出来的文件,要求recursive=yes。
      checksum:     # 等价于"-c"选项,将基于文件的checksum来判断是否同步,而不是默认的quick check
                     # 算法,该算法基于文件大小和最近的mtime来判断是否要同步。该选项会大幅降低效率,
                     # 应谨慎使用。注意,它无法影响archive,即archive仍会启用。
      existing_only:# receiver端没有的文件不同步。但仍会传输,只是临时文件重组后不重命名而已。
      partial:      # 等价于"--partial"选项。默认rsync在传输中断时会删除传输了一半的文件,指定该选
                     # 项将保留这部分不完整的文件,使得下次传输时可以直接从未完成的数据块开始传输。
      dest_port:    # ssh的连接端口。
      rsync_opts:   # 指定额外的rsync选项。使用数组的方式传递这些选项。
      rsync_path:   # 等价于"--rsync-path"选项,目的是启动远程rsync。
                     # 例如可以指定[--rsync-path=rsync],甚至[--rsync-path=cd /tmp/c && rsync]。
                     # 当不指定rsync路径时,默认为/usr/bin/rysnc。
      rsync_timeout:# 指定rsync在多久时间内还没有数据传输就超时退出。
      verify_host:  # 对目标主机进行ssh的host key验证。

Explanation

Bowen is a reference Malone handsome big brother article finishing generation, belonging to the blogger study notes, if infringement, please contact me big brother, Li deleted!

Finally, thanks to open source, open source embrace ~

Guess you like

Origin blog.51cto.com/wutengfei/2450346