ansible简单教程(2):ad-hoc命令与常用模块

一、何为Ad-Hoc

Ad-Hoc,就是所谓的“交互式临时命令”,Ad-Hoc是Ansible对Ansible命令的一种执行方式。

解释:

  • 1、从功能上讲,Ad-Hoc是相对于Ansible-playbook而言的,Ansible提供两种完成任务方式:一种是Ad-Hoc命令集,即ansible,另一种就是Ansible-playbook了,即命令Ansible-playbook。
  • 2、前者更注重于解决一些简单的或者平时工作中临时遇到的任务,相当于Linux系统命令行下的Shell命令, 后者更适合与解决复杂或需固化下来的任务,相当于Linux系统的Shell Scripts。
  • 3、也可以类比于hive的-e 和 -f 参数。
    Hive -e "${HIVE_STATEMENT}",临时一次性使用查询hive;hive -f "${FIXED_HQL_TEMPLATE}",固化下来的hql执行语句。
  1. 需要使用Ad-Hoc的场景

情景1:

      节假日将至,我们需要关闭所有不必要的服务器,并对所有服务器进行节前健康检查。

情景2:

      临时更新Apache&Nginx的配置文件,且需同时将其分发至所有需更新该配置的Web服务器
  1. 需要使用ansible-playbook的场景

情景1:

      新购置的服务器安装完系统后需做一系列固化的初始化工作,诸如:定制防火墙策略、添加NTP时间同步配置、添加EPEL源等。

情景2:

      业务侧每周定期对生产环境发布更新程序代码。

总结:

[ansible任务执行模式]
有 ad-hoc 和 playbook 两种:

ad-hoc

ad-hoc模式使用单个模块,支持批量执行单条命令。ad-hoc命令是一种可以快速输入的命令,而且不需要保存起来的命令。相当于bash中的一句shell。

playbook

playbook模式是ansible主要管理方式,也是ansible功能强大的关键所在。playbook通过多个task集合完成一类功能,如web服务的安装部署、数据库服务器的批量备份等。可以简单地把playbook理解为通过组合多条ad-hoc操作的配置文件。

二、Ansible 模块帮助信息

1、显示 Ansible 所支持的模块信息

使用 ansible-doc -l 命令

[root@cdh-001 tmp]# ansible-doc -l
fortios_router_community_list                                 Configure community lists in Fortinet's FortiOS and FortiGate                                                                      
azure_rm_devtestlab_info                                      Get Azure DevTest Lab facts                                                                                                        
ecs_taskdefinition                                            register a task definition in ecs                                                                                                  
avi_alertscriptconfig                                         Module for setup of AlertScriptConfig Avi RESTful Object                                                                           
tower_receive                                                 Receive assets from Ansible Tower                                                                                                  
netapp_e_iscsi_target                                         NetApp E-Series manage iSCSI target configuration                                                                                  
azure_rm_acs                                                  Manage an Azure Container Service(ACS) instance                                                                                    
fortios_log_syslogd2_filter                                   Filters for remote system server in Fortinet's FortiOS and FortiGate                                                               
junos_rpc                                                     Runs an arbitrary RPC over NetConf on an Juniper JUNOS device                                                                      
na_elementsw_vlan                                             NetApp Element Software Manage VLAN                                                                                                
pn_ospf                                                       CLI command to add/remove ospf protocol to a vRouter                                                                               
pn_snmp_vacm                                                  CLI command to create/modify/delete snmp-vacm                                                                                      
cp_mgmt_service_sctp                                          Manages service-sctp objects on Check Point over Web Services API                                                                  
onyx_ospf                                                     Manage OSPF protocol on Mellanox ONYX network devices                                                                              
icx_command                                                   Run arbitrary commands on remote Ruckus ICX 7000 series switches                                                                   
cs_snapshot_policy                                            Manages volume snapshot policies on Apache CloudStack based clouds

2、查询指定模块的详细用法

使用 ansible-doc -s ${MODULE_NAME} 命令

=====================================  分割线  ping ========================================
[root@cdh-001 tmp]# ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
  ping:
      data:                  # Data to return for the `ping' return value. If this parameter is set to `crash', the module will cause an exception.

=====================================  分割线  copy ========================================
[root@cdh-001 tmp]# ansible-doc -s copy
- name: Copy files to remote locations
  copy:
      attributes:            # The attributes the resulting file or directory should have. To get supported flags look at the man page for `chattr' on the target system. This string should contain
                               the attributes in the same order as the one displayed by `lsattr'. The `=' operator is assumed as default, otherwise `+' or `-'
                               operators need to be included in the string.
      backup:                # Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
      checksum:              # SHA1 checksum of the file being transferred. Used to validate that the copy of the file was successful. If this is not provided, ansible will use the local calculated
                               checksum of the src file.
      content:               # When used instead of `src', sets the contents of a file directly to the specified value. Works only when `dest' is a file. Creates the file if it does not exist. For
                               advanced formatting or if `content' contains a variable, use the [template] module.
      decrypt:               # This option controls the autodecryption of source files using vault.
      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 non-existent path and if
                               either `dest' ends with "/" or `src' is a directory, `dest' is created. If `dest' is a relative path, the starting directory is
                               determined by the remote host. If `src' and `dest' are files, the parent directory of `dest' is not created and the task fails if it
                               does not already exist.
      directory_mode:        # When doing a recursive copy set the mode for the directories. If this is not set we will use the system defaults. The mode is only set on directories which are newly
                               created, and will not affect those that already existed.
      follow:                # This flag indicates that filesystem links in the destination, if they exist, should be followed.
      force:                 # Influence whether the remote file must always be replaced. If `yes', the remote file will be replaced when contents are different than the source. If `no', the file
                               will only be transferred if the destination does not exist. Alias `thirsty' has been deprecated and will be removed in 2.13.
      group:                 # Name of the group that should own the file/directory, as would be fed to `chown'.
      local_follow:          # This flag indicates that filesystem links in the source tree, if they exist, should be followed.
      mode:                  # The permissions of the destination file or directory. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers. You must either add a leading
                               zero so that Ansible's YAML parser knows it is an octal number (like `0644' or `01777')or quote it (like `'644'' or `'1777'') so
                               Ansible receives a string and can do its own conversion from string into number. Giving Ansible a number without following one of these
                               rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic
                               mode (for example, `u+rwx' or `u=rw,g=r,o=r'). As of Ansible 2.3, the mode may also be the special string `preserve'. `preserve' means
                               that the file will be given the same permissions as the source file.
      owner:                 # Name of the user that should own the file/directory, as would be fed to `chown'.
      remote_src:            # Influence whether `src' needs to be transferred or already is present remotely. If `no', it will search for `src' at originating/master machine. If `yes' it will go
                               to the remote/target machine for the `src'. `remote_src' supports recursive copying as of version 2.8. `remote_src' only works with
                               `mode=preserve' as of version 2.6.
      selevel:               # The level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. When set to `_default', it will use the `level' portion of
                               the policy if available.
      serole:                # The role part of the SELinux file context. When set to `_default', it will use the `role' portion of the policy if available.
      setype:                # The type part of the SELinux file context. When set to `_default', it will use the `type' portion of the policy if available.
      seuser:                # The user part of the SELinux file context. By default it uses the `system' policy, where applicable. When set to `_default', it will use the `user' portion of the
                               policy if available.
      src:                   # Local path to a file to copy to the remote server. This 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


=====================================  分割线  command ========================================
[root@cdh-001 tmp]# ansible-doc -s command
- name: Execute commands on targets
  command:
      argv:                  # Passes the command as a list rather than a string. Use `argv' to avoid quoting values that would otherwise be interpreted incorrectly (for example "user name"). Only
                               the string or the list form can be provided, not both.  One or the other must be provided.
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run.
      creates:               # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run.
      free_form:             # The command module takes a free form command to run. There is no actual parameter named 'free form'.
      removes:               # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # If set to `yes', append a newline to stdin data.
      strip_empty_ends:      # Strip empty lines from the end of stdout/stderr in result.
      warn:                  # Enable or disable task warnings.

=====================================  分割线  cron ========================================

[root@cdh-001 tmp]# ansible-doc -s cron
- name: Manage cron.d and crontab entries
  cron:
      backup:                # If set, create a backup of the crontab before it is modified. The location of the backup is returned in the `backup_file' variable by this module.
      cron_file:             # If specified, uses this file instead of an individual user's crontab. If this is a relative path, it is interpreted with respect to `/etc/cron.d'. If it is absolute,
                               it will typically be `/etc/crontab'. Many linux distros expect (and some require) the filename portion to consist solely of upper- and
                               lower-case letters, digits, underscores, and hyphens. To use the `cron_file' parameter you must specify the `user' as well.
      day:                   # Day of the month the job should run ( 1-31, *, */2, etc )
      disabled:              # If the job should be disabled (commented out) in the crontab. Only has effect if `state=present'.
      env:                   # If set, manages a crontab's environment variable. New variables are added on top of crontab. `name' and `value' parameters are the name and the value of environment
                               variable.
      hour:                  # Hour when the job should run ( 0-23, *, */2, etc )
      insertafter:           # Used with `state=present' and `env'. If specified, the environment variable will be inserted after the declaration of specified environment variable.
      insertbefore:          # Used with `state=present' and `env'. If specified, the environment variable will be inserted before the declaration of specified environment variable.
      job:                   # The command to execute or, if env is set, the value of environment variable. The command should not contain line breaks. Required if `state=present'.
      minute:                # Minute when the job should run ( 0-59, *, */2, etc )
      month:                 # Month of the year the job should run ( 1-12, *, */2, etc )
      name:                  # Description of a crontab entry or, if env is set, the name of environment variable. Required if `state=absent'. Note that if name is not set and `state=present', then
                               a new crontab entry will always be created, regardless of existing ones. This parameter will always be required in future releases.
      reboot:                # If the job should be run at reboot. This option is deprecated. Users should use special_time.
      special_time:          # Special time specification nickname.
      state:                 # Whether to ensure the job or environment variable is present or absent.
      user:                  # The specific user whose crontab should be modified. When unset, this parameter defaults to using `root'.
      weekday:               # Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc )

=====================================  分割线  shell user ========================================
[root@cdh-001 tmp]# ansible-doc -s user
- name: Manage user accounts
  user:
      append:                # If `yes', add the user to the groups specified in `groups'. If `no', user will only be added to the groups specified in `groups', removing them from all other groups.
                               Mutually exclusive with `local'
      authorization:         # Sets the authorization of the user. Does nothing when used with other platforms. Can set multiple authorizations using comma separation. To delete all authorizations,
                               use `authorization='''. Currently supported on Illumos/Solaris.
      comment:               # Optionally sets the description (aka `GECOS') of user account.
      create_home:           # Unless set to `no', a home directory will be made for the user when the account is created or if the home directory does not exist. Changed from `createhome' to
                               `create_home' in Ansible 2.5.
      expires:               # An expiry time for the user in epoch, it will be ignored on platforms that do not support this. Currently supported on GNU/Linux, FreeBSD, and DragonFlyBSD. Since
                               Ansible 2.6 you can remove the expiry time specify a negative value. Currently supported on GNU/Linux and FreeBSD.
      force:                 # This only affects `state=absent', it forces removal of the user and associated directories on supported platforms. The behavior is the same as `userdel --force',
                               check the man page for `userdel' on your system for details and support. When used with `generate_ssh_key=yes' this forces an existing
                               key to be overwritten.
      generate_ssh_key:      # Whether to generate a SSH key for the user in question. This will *not* overwrite an existing SSH key unless used with `force=yes'.
      group:                 # Optionally sets the user's primary group (takes a group name).
      groups:                # List of groups user will be added to. When set to an empty string `''', the user is removed from all groups except the primary group. Before Ansible 2.3, the only
                               input format allowed was a comma separated string. Mutually exclusive with `local'
      hidden:                # macOS only, optionally hide the user from the login window and system preferences. The default will be `yes' if the `system' option is used.
      home:                  # Optionally set the user's home directory.
      local:                 # Forces the use of "local" command alternatives on platforms that implement it. This is useful in environments that use centralized authentification when you want to
                               manipulate the local users (i.e. it uses `luseradd' instead of `useradd'). This will check `/etc/passwd' for an existing account before
                               invoking commands. If the local account database exists somewhere other than `/etc/passwd', this setting will not work properly. This
                               requires that the above commands as well as `/etc/passwd' must exist on the target host, otherwise it will be a fatal error. Mutually
                               exclusive with `groups' and `append'
      login_class:           # Optionally sets the user's login class, a feature of most BSD OSs.
      move_home:             # If set to `yes' when used with `home: ', attempt to move the user's old home directory to the specified directory if it isn't there already and the old home exists.
      name:                  # (required) Name of the user to create, remove or modify.
      non_unique:            # Optionally when used with the -u option, this option allows to change the user ID to a non-unique value.
      password:              # Optionally set the user's password to this crypted value. On macOS systems, this value has to be cleartext. Beware of security issues. To create a disabled account on
                               Linux systems, set this to `'!'' or `'*''. To create a disabled account on OpenBSD, set this to `'*************''. See
                               https://docs.ansible.com/ansible/faq.html#how-do-i-generate-encrypted-passwords-for-the-user-module for details on various ways to
                               generate these password values.
      password_lock:         # Lock the password (`usermod -L', `usermod -U', `pw lock'). Implementation differs by platform. This option does not always mean the user cannot login using other
                               methods. This option does not disable the user, only lock the password. This must be set to `False' in order to unlock a currently
                               locked password. The absence of this parameter will not unlock a password. Currently supported on Linux, FreeBSD, DragonFlyBSD, NetBSD,
                               OpenBSD.
      profile:               # Sets the profile of the user. Does nothing when used with other platforms. Can set multiple profiles using comma separation. To delete all the profiles, use
                               `profile='''. Currently supported on Illumos/Solaris.
      remove:                # This only affects `state=absent', it attempts to remove directories associated with the user. The behavior is the same as `userdel --remove', check the man page for
                               details and support.
      role:                  # Sets the role of the user. Does nothing when used with other platforms. Can set multiple roles using comma separation. To delete all roles, use `role='''. Currently
                               supported on Illumos/Solaris.
      seuser:                # Optionally sets the seuser type (user_u) on selinux enabled systems.
      shell:                 # Optionally set the user's shell. On macOS, before Ansible 2.5, the default shell for non-system users was `/usr/bin/false'. Since Ansible 2.5, the default shell for
                               non-system users on macOS is `/bin/bash'. On other operating systems, the default shell is determined by the underlying tool being
                               used. See Notes for details.
      skeleton:              # Optionally set a home skeleton directory. Requires `create_home' option!
      ssh_key_bits:          # Optionally specify number of bits in SSH key to create.
      ssh_key_comment:       # Optionally define the comment for the SSH key.
      ssh_key_file:          # Optionally specify the SSH key filename. If this is a relative filename then it will be relative to the user's home directory. This parameter defaults to
                               `.ssh/id_rsa'.
      ssh_key_passphrase:    # Set a passphrase for the SSH key. If no passphrase is provided, the SSH key will default to having no passphrase.
      ssh_key_type:          # Optionally specify the type of SSH key to generate. Available SSH key types will depend on implementation present on target host.
      state:                 # Whether the account should exist or not, taking action if the state is different from what is stated.
      system:                # When creating an account `state=present', setting this to `yes' makes the user a system account. This setting cannot be changed on existing users.
      uid:                   # Optionally sets the `UID' of the user.
      update_password:       # `always' will update passwords if they differ. `on_create' will only set the password for newly created users.

=====================================  分割线  shell file ========================================

[root@cdh-001 tmp]# ansible-doc -s file
- name: Manage files and file properties
  file:
      access_time:           # This parameter indicates the time the file's access time should be set to. Should be `preserve' when no modification is required, `YYYYMMDDHHMM.SS' when using default
                               time format, or `now'. Default is `None' meaning that `preserve' is the default for `state=[file,directory,link,hard]' and `now' is
                               default for `state=touch'.
      access_time_format:    # When used with `access_time', indicates the time format that must be used. Based on default Python format (see time.strftime doc).
      attributes:            # The attributes the resulting file or directory should have. To get supported flags look at the man page for `chattr' on the target system. This string should contain
                               the attributes in the same order as the one displayed by `lsattr'. The `=' operator is assumed as default, otherwise `+' or `-'
                               operators need to be included in the string.
      follow:                # This flag indicates that filesystem links, if they exist, should be followed. Previous to Ansible 2.5, this was `no' by default.
      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).
      group:                 # Name of the group that should own the file/directory, as would be fed to `chown'.
      mode:                  # The permissions the resulting file or directory should have. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers. You must either add a
                               leading zero so that Ansible's YAML parser knows it is an octal number (like `0644' or `01777') or quote it (like `'644'' or `'1777'')
                               so Ansible receives a string and can do its own conversion from string into number. Giving Ansible a number without following one of
                               these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a
                               symbolic mode (for example, `u+rwx' or `u=rw,g=r,o=r').
      modification_time:     # This parameter indicates the time the file's modification time should be set to. Should be `preserve' when no modification is required, `YYYYMMDDHHMM.SS' when using
                               default time format, or `now'. Default is None meaning that `preserve' is the default for `state=[file,directory,link,hard]' and `now'
                               is default for `state=touch'.
      modification_time_format:   # When used with `modification_time', indicates the time format that must be used. Based on default Python format (see time.strftime doc).
      owner:                 # Name of the user that should own the file/directory, as would be fed to `chown'.
      path:                  # (required) Path to the file being managed.
      recurse:               # Recursively set the specified file attributes on directory contents. This applies only when `state' is set to `directory'.
      selevel:               # The level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. When set to `_default', it will use the `level' portion of
                               the policy if available.
      serole:                # The role part of the SELinux file context. When set to `_default', it will use the `role' portion of the policy if available.
      setype:                # The type part of the SELinux file context. When set to `_default', it will use the `type' portion of the policy if available.
      seuser:                # The user part of the SELinux file context. By default it uses the `system' policy, where applicable. When set to `_default', it will use the `user' portion of the
                               policy if available.
      src:                   # Path of the file to link to. This applies only to `state=link' and `state=hard'. For `state=link', this will also accept a non-existing path. Relative paths are
                               relative to the file being created (`path') which is how the Unix command `ln -s SRC DEST' treats relative paths.
      state:                 # If `absent', directories will be recursively deleted, and files or symlinks will be unlinked. In the case of a directory, if `diff' is declared, you will see the
                               files and folders deleted listed under `path_contents'. Note that `absent' will not cause `file' to fail if the `path' does not exist
                               as the state did not change. 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', without any other options this works mostly as a 'stat' and will return
                               the current state of `path'. Even with other options (i.e `mode'), the file will be modified but 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 `hard', the hard link will be created or
                               changed. If `link', the symbolic link will be created or changed. 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).
      unsafe_writes:         # Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target file. By default this module uses atomic operations to prevent
                               data corruption or inconsistent reads from the target files, but sometimes systems are configured or just broken in ways that prevent
                               this. One example is docker mounted files, which cannot be updated atomically from inside the container and can only be written in an
                               unsafe manner. This option allows Ansible to fall back to unsafe methods of updating files when atomic operations fail (however, it
                               doesn't force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data
                               corruption.


=====================================  分割线  shell ========================================

[root@cdh-001 tmp]# ansible-doc -s shell
- name: Execute shell commands on targets
  shell:
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run followed by optional arguments.
      creates:               # A filename, when it already exists, this step will *not* be run.
      executable:            # Change the shell used to execute the command. This expects an absolute path to the executable.
      free_form:             # The shell module takes a free form command to run, as a string. There is no actual parameter named 'free form'. See the examples on how to use this module.
      removes:               # A filename, when it does not exist, this step will *not* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # Whether to append a newline to stdin data.
      warn:                  # Whether to enable task warnings.

=====================================  分割线  script ========================================

[root@cdh-001 tmp]# ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
  script:
      chdir:                 # Change into this directory on the remote node before running the script.
      cmd:                   # Path to the local script to run followed by optional arguments.
      creates:               # A filename on the remote node, when it already exists, this step will *not* be run.
      decrypt:               # This option controls the autodecryption of source files using vault.
      executable:            # Name or path of a executable to invoke the script with.
      free_form:             # Path to the local script file followed by optional arguments.
      removes:               # A filename on the remote node, when it does not exist, this step will *not* be run.

三、Ansible 模块使用实操

说明:
如下命令行中的webserver 为/etc/ansible/hosts中配置的[web]分组,包含已经实现ansible命令所在机器免密登录的多台其他机器。

[root@cdh-001 tmp]# cat /etc/ansible/hosts
[webserver]
111.111.113
111.111.114

3.1 ping模块

测试是否可以ping同远端主机

# ansible webserver -m ping

其中web为hosts中分组名称

3.2 command模块

xxx默认模块。让远端主机执行指定的命令,但不支持管道或者重定向。

ansible 111.111.111.111 -a 'date'

# ansible webserver -a 'ls ~'
# ansible webserver -a 'ls /'
# ansible webserver -a 'jps'
# ansible webserver -a 'jps -ml'
# ansible webserver -a 'date'

3.3 shell模块

xxx和command模块一样是用来运行命令,当命令中有变量或者管道符的时候要用shell模块,特殊符号需要转义,比如$

ansible webserver -m shell -a "echo david | passwd --stdin david"

3.4 script模块

xxx将本地的脚本复制到远端主机并执行,需要把脚本放在当前目录中并使用相对路径来指定

echo 'date' > test.sh

ansible webserver -m script -a "test.sh"

3.5 copy复制模块

xxx文件的复制

# ansible所在的主机上创建测试文件 david_test
cd /tmp
echo 'HelloDavid' > david_test 
chown cloudera-scm david_test

# 复制到远端
ansible webserver -m copy -a 'src=/tmp/david_test dest=/tmp/david_test owner=cloudera-scm mode=777'
ansible webserver -m copy -a 'src=/tmp/david_test dest=/tmp/david_test owner=cloudera-scm mode=640'
ansible webserver -m copy -a 'content="HelloDavid" dest=/tmp/david_test owner=root mode=666 backup=yes'

3.6 file模块

xxx设置文件的属性,如所属主、文件权限等

# 修改远程文件的读写执行权限
ansible webserver -m file -a 'owner=david group=david mode=644 path=/tmp/test'

# 为远程主机文件创建软链接
ansible webserver -m file -a 'path=/tmp/test.link src=/tmp/test state=link'

# 在远程主机上创建目录
ansible webserver -m file -a 'path=/tmp/david_test state=directory'

# 在远程主机上删除文件
ansible webserver -m file -a 'path=/tmp/david_test state=absent'

# 在远程主机上构建文件
ansible webserver -m file -a 'path=/tmp/david_test state=touch'

3.7 cron定时调度模块

xxx设置定时任务,其中有个state选项包含present、absent两个参数,分别代表增加和移除

ansible webserver -m cron -a 'minute="*/10" job="/bin/echo test" name="test cron job" '
ansible webserver -m cron -a 'hour="*/1" job="/usr/sbin/ntpdate cdh-001" name="crontab from ansible" state="present" '

输出为:

[root@cdh-002 bigdata_admin]# crontab -l
#Ansible: test cron job
*/10 * * * * /bin/echo test
#Ansible: crontab from ansible
* */1 * * * /usr/sbin/ntpdate cdh-001

3.8 service模块

xxx控制Linux服务程序运行,状态的更新

ansible cdh-dn5 -m service -a "enabled=true name=maxwell_qianyi_edu_etl.service state=restarted"
ansible cdh-dn5 -m service -a "enabled=true name=maxwell_qianyi_edu_etl.service state=stopped"

3.9 yum模块

xxx执行CentOS或RedHat操作系统的程序包安装、删除,远端主机需要先配置好正确的yum源

# 远程主机安装git
ansible webserver  -m yum -a "name=git state=present"

# 远程主机删除git
ansible cdh-003 -m yum -a "name=git state=absent"

3.10 setup模块

xxx收集被管理主机的信息,包含系统版本、IP地址、CPU核心数。
在Ansible高级操作中可以通过该模块先收集信息,然后根据不同主机的不同信息做响应操作,类似grafana、zabbix中的低级别发现自动获取磁盘信息一样

# ansible webserver -m setup

3.11 user模块

xxx用户管理模块,此外还有一个group模块用于管理组

# 创建系统级用户david,属于root组
ansible webserver -m user -a "name=david system=yes"

引用列表:


-

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1、Ansible ad-hoc常用命令包括: - `ansible`:用于执行命令或任务的基本命令。 - `ansible-playbook`:用于执行Playbook的命令。 - `ansible-doc`:用于查看Ansible模块的文档。 - `ansible-galaxy`:用于管理Ansible角色的命令。 - `ansible-vault`:用于加密和解密Ansible变量文件的命令。 2、YAML文件格式是一种轻量级的数据序列化格式,常用于配置文件和数据交换。它使用缩进和冒号来表示数据的层级关系。以下是一些常用的YAML语法: - 使用缩进表示层级关系,缩进可以使用空格或制表符,但不能混用。 - 使用冒号表示键值对,冒号后面的值可以是字符串、数字、布尔值、列表或字典。 - 使用短横线表示列表项,列表项可以是字符串、数字、布尔值、列表或字典。 - 使用井号表示注释,井号后面的内容将被忽略。 3、编写简单的Playbook可以按照以下格式: ```yaml --- - name: Playbook示例 hosts: all # 指定执行任务的主机组 become: true # 使用sudo执行任务 tasks: - name: 安装Nginx apt: name: nginx state: present - name: 启动Nginx服务 service: name: nginx state: started ``` 以上是一个简单的Playbook,它包含两个任务:安装Nginx和启动Nginx服务。`name`字段用于描述任务的名称,`apt`和`service`是Ansible提供的模块,用于安装软件包和管理服务。`hosts`字段指定了要在哪些主机上执行任务,`become`字段指定使用sudo权限执行任务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值