1. 程式人生 > >Ansible 常見模組介紹

Ansible 常見模組介紹

Ansible 常見模組介紹

ansible-doc 命令,可以檢視當前ansible有哪些已安裝的模組並且可以使用

ansible-doc -s MODULE_NAME 可以檢視該模組的使用說明

常用模組介紹

模組名 說明
at 定義at任務
cron 定義定時任務
copy 複製檔案
command 預設模組,執行命令
shell 執行復雜命令
yum 管理yum安裝解除安裝
user 管理使用者
group 管理組

Ansible 基本語法

基礎語法:ansible

  • hosts-pattern : 表示對那些主機生效的,可以使單個主機ip,也可以是在Inverteroy檔案中定義的組名。
  • -f fors : 表示一次性處理多少個主機,也就是併發數量
  • -m module_name : 指定使用哪個模組
  • -a args : 表示需要給使用的模組傳遞的引數

command 模組

在遠端的主機上執行特定的命令

首先檢視一下幫助

[[email protected]
ansible]# ansible-doc -s command - name: Executes a command on a remote node command: argv: # Allows the user to provide the command as a list vs. a string. 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. creates: # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run. free_form: # (required) The command module takes a free form command to run. There is no parameter actually named 'free form'. See the examples! 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. warn: # If command_warnings are on in ansible.cfg, do not warn about this particular line if set to `no'.

演示

直接操控某個主機
[[email protected] ansible]# ansible 10.0.0.65 -m command -a 'ls -ld /root'
10.0.0.65 | CHANGED | rc=0 >>
dr-xr-x---. 5 root root 168 Oct 15 13:28 /root

# 操控Inventory中定義的組名對應的主機
[[email protected] ansible]# ansible webservs -m command -a 'ls -ld /root'
10.0.0.65 | CHANGED | rc=0 >>
dr-xr-x---. 5 root root 168 Oct 15 13:28 /root

有一個預設的組all,Inventory中定義的所有主機都需要執行

[[email protected] ansible]# ansible all -m command -a 'ls -ld /root'
10.0.0.66 | CHANGED | rc=0 >>
dr-xr-x---. 5 root root 191 Oct 15 13:28 /root

10.0.0.65 | CHANGED | rc=0 >>
dr-xr-x---. 5 root root 168 Oct 15 13:28 /root

cron 模組

管理遠端主機的定時任務

首先檢視一下幫助

[[email protected] ansible]# 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.
      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.
      weekday:               # Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc )

特別說明:state引數,表示是增加present,還是刪除absent.

演示新增

下面在webservs組中,建立一個定時任務,每十分鐘,echo 一個 hello/tmp/test.ans.

[[email protected] ansible]# ansible webservs -m cron -a 'minute="*/10" job="/bin/echo hello >> /tmp/test.ans" name="test cron job" state=present' 
10.0.0.65 | CHANGED => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "test cron job"
    ]
}
[[email protected] ansible]# ansible webservs -m command -a 'crontab -l'
10.0.0.65 | CHANGED | rc=0 >>
#Ansible: test cron job
*/10 * * * * /bin/echo hello > /tmp/test.ans

說明:

  • name引數是給這個定時任務起一個名字,相當於是個註釋,解釋該定時任務的含義
  • 定時任務中分時日月周中,如果是*號,則可以不用增加引數
  • 如果是新增,state=present 引數可以不用新增,如果是刪除,則需要加入state=absent引數

演示刪除

[[email protected] ansible]# ansible webservs -m cron -a 'minute="*/10" job="/bin/echo hello >> /tmp/test.ans" name="test cron job" state=absent'
10.0.0.65 | CHANGED => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
[[email protected] ansible]# ansible webservs -m command -a 'crontab -l'
10.0.0.65 | CHANGED | rc=0 >>


[[email protected] ansible]#

user 模組

管理遠端主機的使用者

檢視幫助

[[email protected] ansible]# 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.
      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 version 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 version 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.
      generate_ssh_key:      # Whether to generate a SSH key for the user in question. This will *not* overwrite an existing SSH key.
      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 `''', `null', or `~', the user is removed from all groups except the primary group. (`~'
                               means `null' in YAML) Before version 2.3, the only input format allowed was a comma separated string. Now this parameter
                               accepts a list as well as a comma separated string.
      hidden:                # macOS only, optionally hide the user from the login window and system preferences. The default will be 'True' 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 requires that these commands exist on
                               the targeted host, otherwise it will be a fatal error.
      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. See
                               https://docs.ansible.com/ansible/faq.html#how-do-i-generate-crypted-passwords-for-the-user-module for details on various ways
                               to generate these password values.
      password_lock:         # Lock the password (usermod -L, pw lock, usermod -C). BUT implementation differs on different platforms, this option does not always mean the user cannot
                               login via other methods. This option does not disable the user, only lock the password. Do not change the password in the same
                               task. Currently supported on Linux, FreeBSD, DragonFlyBSD, NetBSD.
      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.
      seuser:                # Optionally sets the seuser type (user_u) on selinux enabled systems.
      shell:                 # Optionally set the user's shell. On macOS, before version 2.5, the default shell for non-system users was /usr/bin/false. Since 2.5, the default shell for
                               non-system users on macOS is /bin/bash.
      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.
      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.

演示