一、ansible常用模塊
模塊是Ansible執行的最小單位,可以是由Python編寫,也可以是Shell編寫,也可以是由其他語言編寫。
一、ping模塊
測試連接可通性,沒有參數。通的話返回pong。
1、使用示例
ansible all -m ping
1、可通,返回pong如下圖
2、不通,返回如下圖
二、setup模塊
主要用於獲取主機信息,在playbooks里經常會用到的一個參數gather_facts就與該模塊相關。setup模塊下經常使用的一個參數是filter參數,具體使用示例如下(由於輸出結果較多,這里只列命令不寫結果)
每個被管理節點在接收並運行管理命令之前,會將自己主機相關信息(如系統版本,主機IP地址)告知ansible管理主機
1、幫助信息

--tree :將所有主機的輸出信息保存到/tmp/目錄下,以/etc/ansible/hosts里的主機名為文件名 ansible all -m setup -a 'filter=ansible_distribution_version' --tree /tmp/ filter :過濾關鍵字 #ansible db -m setup -a 'filter=ansible_distribution_version' gather_subset:按子集收集信息,值有all, min, hardware, network, virtual, ohai, facter。不包含請使用!號,如,!network
2、經常獲取的信息,統計表格如下
關鍵字 | 說明 | 返回值例子 |
---|---|---|
ansible_nodename | 節點名 | "6-dns-1.hunk.tech" |
ansible_fqdn | FQDN名 | "6-dns-1.hunk.tech" |
ansible_hostname | 主機短名稱 | "6-dns-1" |
ansible_domain | 主機域名后綴 | "hunk.teh" |
ansible_memtotal_mb | 總物理內存 | "ansible_memtotal_mb": 222 |
ansible_swaptotal_mb | SWAP總大小 | "1023" |
ansible_processor | CPU信息 | Intel(R) Core(TM) i5-5200U CPU @ 2.20GHz |
ansible_processor_cores | CPU核心數量 | 4 |
ansible_processor_vcpus | CPU邏輯核心數量 | 2 |
ansible_all_ipv4_addresses | 有所IPV4地址 | 192.168.0.200 |
ansible_all_ipv6_addresses | 所有IPV6地址 | |
ansible_default_ipv4 | 默認網關的網卡配置信息 | |
ansible_eth2 | 具體某張網卡信息 | 不同系統名稱需要變化 |
ansible_dns | DNS設置信 | |
ansible_architecture | 系統架構 | x86_64 |
ansible_machine | 主機類型 | x86_64 |
ansible_kernel | 內核版本 | "2.6.32-696.el6.x86_64" |
ansible_distribution | 發行版本 | "CentOS" |
ansible_distribution_major_version | 操作系統主版本號 | "6" |
ansible_distribution_release | 發行版名稱 | "Final" |
ansible_distribution_version | 完整版本號 | "7.4.1708" |
ansible_pkg_mgr | 軟件包管理方式 | "yum" |
ansible_service_mgr | 進行服務方式 | "systemd" |
ansible_os_family | 家族系列 | "RedHat" |
ansible_cmdline | 內核啟動參數 | |
ansible_selinux | SElinux狀態 | "disabled" |
ansible_env | 當前環境變量參數 | |
ansible_date_time | 時間相關 | |
ansible_python_version | python版本 | "2.6.6" |
ansible_lvm | LVM卷相關信息 | |
ansible_mounts | 所有掛載點 | |
ansible_device_links | 所有掛載的設備的UUID和卷標名 | |
ansible_devices | 所有/dev/下的正在使用的設備的信息 | |
ansible_user_dir | 執行用戶的家目錄 | "/root" |
ansible_user_gecos | 執行用戶的描述信息 | "The root " |
ansible_user_gid | 執行用戶的的GID | 0 |
ansible_user_id | 執行用戶的的用戶名 | "root" |
ansible_user_shell | 執行用戶的shell類型 | "/bin/bash" |
ansible_user_uid | 執行用戶的UID | 0 |
3、使用范例
ansible web -m setup
執行結果

三、command模塊
command 命令模塊,默認模塊(可省略),用於在遠程執行命令(不能使用變量)
1、幫助信息
1 creates:一個文件名,當該文件存在,則該命令不執行 2 free_form:要執行的linux指令 3 chdir:在執行指令之前,先切換到該指定的目錄 4 removes:一個文件名,當該文件不存在,則該選項不執行 5 executable:切換shell來執行指令,該執行路徑必須是一個絕對路徑
2、使用范例
# ansible all -a 'date'
四、cron模塊
cron 定時任務模塊
1、幫助信息

# 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 )
1 backup:對遠程主機上的原任務計划內容修改之前做備份 2 cron_file:如果指定該選項,則用該文件替換遠程主機上的cron.d目錄下的用戶的任務計划 3 day:日(1-31,*,*/2,……) 4 hour:小時(0-23,*,*/2,……) 5 minute:分鍾(0-59,*,*/2,……) 6 month:月(1-12,*,*/2,……) 7 weekday:周(0-7,*,……) 8 job:要執行的任務,依賴於state=present 9 name:該任務的描述 10 special_time:指定什么時候執行,參數:reboot,yearly,annually,monthly,weekly,daily,hourly 11 state:確認該任務計划是創建還是刪除 12 user:以哪個用戶的身份執行
2、使用說明
ansible db -m cron -a 'minute="" hour="" day="" month="" weekday="" job="" name="(必須填寫)" state=
1、定時設置指定值的寫入即可,沒有設置的可以不寫(默認是*)
2、name必須寫
3、state有兩個狀態:present(添加(默認值))or absent(移除)
3、使用范例
1、添加定時任務
ansible db -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state="present"' ansible db -a "crontab -l"
結果如下圖
2、移除定時任務
ansible db -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state="absent"' ansible db -a "crontab -l"
結果如下圖
五、user/group模塊
user模塊是請求的是useradd, userdel, usermod三個指令,goup模塊請求的是groupadd, groupdel, groupmod 三個指令。
1、幫助信息
1、英文

# 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: # Darwin/OS X 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 Darwin/OS X 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 Mac OS X, 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 Mac OS X 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.
2、中文
groups:指定用戶的屬組 uid:指定用的uid password:為用戶設置登陸密碼,此密碼是明文密碼加密后的密碼 update_password:always/on_create always:只有當密碼不相同時才會更新密碼(默認) on_create:只為新用戶設置密碼 name:指定用戶名 createhome:是否創建家目錄 yes|no(默認是yes) system:是否為系統用戶 remove:當state=absent時,remove=yes則表示連同家目錄一起刪除,等價於userdel -r(默認是no) state:是創建還是刪除 present(添加(默認值))or absent(移除) shell:指定用戶的shell環境 append:yes/no yes:增量添加group no:全量變更group,只設置groups指定的group組(默認) expires:設置用戶的過期時間,值是一個時間戳
3、注意事項
注:指定password參數時,不能使用后面這一串密碼會被直接傳送到被管理主機的/etc/shadow文件中,所以需要先將密碼字符串進行加密處理。然后將得到的字符串放到password中即可。
范例
- user: name=johnd comment="John Doe" uid=1040 group=admin - user: name=james shell=/bin/bash groups=admins,developers append=yes - user: name=johnd state=absent remove=yes - user: name=james18 shell=/bin/zsh groups=developers expires=1422403387 #生成密鑰時,只會生成公鑰文件和私鑰文件,和直接使用ssh-keygen指令效果相同,不會生成authorized_keys文件。 - user: name=test generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa
2、生成加密的密碼
批量創建用戶並設置密碼:https://cloud.tencent.com/info/c23babde3ad9ff6bde07c532a6afa1d0.html
1、安裝python-pip,並安裝加密函數庫-passlib
yum -y install python-pip pip install --upgrade pip pip install passlib
2、使用加密函數庫,獲取密文密碼
# python -c "from passlib.hash import sha512_crypt; import getpass; print(sha512_crypt.using(rounds=5000).hash(getpass.getpass()))" Password: $6$0lwTSmqKOkL.ktgl$OnBexXC7haBf0FRHVMIZM2edDeFWBbpKJ2r9cxVwNvY.vh3IIUzwFz8n7jFglc0CrtQSY12ziDonVL6e71Og2.
3、創建一個系統用戶,指定用戶密碼
ansible db -m user -a 'name="testops" password="$6$0lwTSmqKOkL.ktgl$OnBexXC7haBf0FRHVMIZM2edDeFWBbpKJ2r9cxVwNvY.vh3IIUzwFz8n7jFglc0CrtQSY12ziDonVL6e71Og2."'
4、查看測試
我們可以看到被管理主機已創建用戶"testops",並且密碼為密文已寫入"/etc/shadow"用戶文件中,嘗試用ssh命令使用testops用戶登錄被管理主機,登錄成功!
ansible db -m shell -a "cat /etc/shadow|grep testops" ssh testops@10.0.0.13
3、使用范例
1、添加用戶並設置密碼(加密過程如上)
ansible db -m user -a 'name="testops" password="$6$0lwTSmqKOkL.ktgl$OnBexXC7haBf0FRHVMIZM2edDeFWBbpKJ2r9cxVwNvY.vh3IIUzwFz8n7jFglc0CrtQSY12ziDonVL6e71Og2."'
結果如下圖
2、刪除用戶(連通家目錄一並刪除)
ansible db -m user -a 'name="testops" state="absent" remove="yes"'
注意該用戶下不能有任何進程,否則會報錯如下紅色部分
六、copy模塊
復制文件
1、幫助信息
1 backup:在覆蓋之前將原文件備份,備份文件包含時間信息。有兩個選項:yes|no 2 content:用於替代"src",可以直接設定指定文件的值 3 dest:必選項。要將源文件復制到的遠程主機的絕對路徑,如果源文件是一個目錄,那么該路徑也必須是個目錄 4 directory_mode:遞歸的設定目錄的權限,默認為系統默認權限 5 force:如果目標主機包含該文件,但內容不同,如果設置為yes,則強制覆蓋,如果為no,則只有當目標主機的目標位置不存在該文件時,才復制。默認為yes 6 others:所有的file模塊里的選項都可以在這里使用 7 src:要復制到遠程主機的文件在本地的地址,可以是絕對路徑,也可以是相對路徑。如果路徑是一個目錄,它將遞歸復制。在這種情況下,如果路徑使用"/"來結尾,則只復制目錄里的內容,如果沒有使用"/"來結尾,則包含目錄在內的整個內容全部復制,類似於rsync。 8 validate :The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the visudo example below.
2、使用范例
1、使用src
ansible db -m copy -a 'src=/etc/hosts dest=/tmp/ owner=root mode=640 backup=no'
結果如下圖
2、使用content
ansible db -m copy -a 'content="Hello ansible\n you are clever!\n" dest=/tmp/ansile.txt owner=root mode=640 backup=no' ansible db -m copy -a 'content="Hello ansible\nyou are clever!\n" dest=/tmp/ansile.txt force=yes owner=root mode=640 backup=no'
管理機操作結果如下圖
目標主機結果如下圖
七、file模塊
設定文件屬性和創建文件的符號鏈接
1、幫助信息
1 force:需要在兩種情況下強制創建軟鏈接,一種是源文件不存在但之后會建立的情況下;另一種是目標軟鏈接已存在,需要先取消之前的軟鏈,然后創建新的軟鏈,有兩個選項:yes|no 2 group:定義文件/目錄的屬組 3 mode:定義文件/目錄的權限 4 owner:定義文件/目錄的屬主 5 path:必選項,定義文件/目錄的路徑 6 recurse:遞歸的設置文件的屬性,只對目錄有效 7 src:要被鏈接的源文件的路徑,只應用於state=link的情況 8 dest:被鏈接到的路徑,只應用於state=link的情況 9 state: directory:如果目錄不存在,創建目錄 file:即使文件不存在,也不會被創建 link:創建軟鏈接 hard:創建硬鏈接 touch:如果文件不存在,則會創建一個新的文件,如果文件或目錄已存在,則更新其最后修改時間 absent:刪除目錄、文件或者取消鏈接文件
2、使用范例
ansible db -m file -a "src=/etc/fstab dest=/tmp/fstab state=link" ansible db -m file -a "path=/tmp/fstab state=absent" ansible db -m file -a "path=/tmp/test state=touch"
八、yum模塊
安裝程序包
1、幫助信息
1 config_file:yum的配置文件 2 disable_gpg_check:關閉gpg_check 3 disablerepo:不啟用某個源 4 enablerepo:啟用某個源 5 name:要進行操作的軟件包的名字,也可以傳遞一個url或者一個本地的rpm包的路徑 6 state:狀態(present安裝,absent卸載,latest最新)
2、使用示例
1、安裝zsh
ansible web -m yum -a 'name=httpd state=latest' ansible web -m yum -a 'name="@Development tools" state=present' ansible web -m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present'
目標主機驗證
# rpm -q zsh zsh-5.0.2-28.el7.x86_64
2、卸載
ansible web -m yum -a 'name=zsh state=absent'
目標主機驗證
# rpm -q zsh
package zsh is not installed
九、service模塊
1、幫助信息
1 arguments:給命令行提供一些選項 2 enabled:是否開機啟動 yes|no 3 name:必選項,服務名稱 4 pattern:定義一個模式,如果通過status指令來查看服務的狀態時,沒有響應,就會通過ps指令在進程中根據該模式進行查找,如果匹配到,則認為該服務依然在運行 5 runlevel:運行級別 6 sleep:如果執行了restarted,在則stop和start之間沉睡幾秒鍾 7 state:對當前服務執行啟動,停止、重啟、重新加載等操作(started,stopped,restarted,reloaded)
2、使用示例
1、保持服務啟動並設置為開機自啟
ansible web -m service -a 'enabled=yes name=httpd state=started'
2、查看服務狀態
ansible web -a 'service httpd status' #centOS7.x之前 ansible web -a 'chkconfig --list httpd' #centOS7.x ansible web -a 'systemctl is-enabled httpd'
十、shell模塊
尤其是用到復雜命令時(如帶管道符等等)
1、幫助信息

# ansible-doc -s shell - name: Execute commands in nodes. shell: chdir: # cd into this directory before running the command creates: # a filename, when it already exists, this step will *not* be run. executable: # change the shell used to execute the command. Should be an absolute path to the executable. free_form: # (required) The shell module takes a free form command to run, as a string. There's not an actual option named "free form". See the examples! 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. warn: # if command warnings are on in ansible.cfg, do not warn about this particular line if set to no/false.
2、使用范例
使用command模塊會報錯,無法得到想要的結果。
ansible web -m shell -a "ps -ef|grep httpd"
十一、script模塊
將本地腳本復制到遠程主機,並執行。
1、幫助信息

ansible-doc -s script - name: Runs a local script on a remote node after transferring it script: chdir: # cd into this directory on the remote node before running the script creates: # a filename, 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: # (required) Path to the local script file followed by optional arguments. There is no parameter actually named 'free form'; see the examples! removes: # a filename, when it does not exist, this step will *not* be run.
2、使用范例
1、實驗腳本

#!/bin/bash echo "test ansible script">>/tmp/scripts.ansible
2、執行
ansible db -m script -a '/tmp/script.sh'
3、驗證結果
十一、synchronize模塊
1、幫助信息
1 archive: 歸檔,相當於同時開啟recursive(遞歸)、links、perms、times、owner、group、-D選項都為yes ,默認該項為開啟 2 checksum: 跳過檢測sum值,默認關閉 3 compress:是否開啟壓縮 4 copy_links:復制鏈接文件,默認為no ,注意后面還有一個links參數 5 delete: 刪除不存在的文件,默認no 6 dest:目錄路徑 7 dest_port:默認目錄主機上的端口 ,默認是22,走的ssh協議 8 dirs:傳速目錄不進行遞歸,默認為no,即進行目錄遞歸 9 rsync_opts:rsync參數部分 10 set_remote_user:主要用於/etc/ansible/hosts中定義或默認使用的用戶與rsync使用的用戶不同的情況 11 mode: push或pull 模塊,push模的話,一般用於從本機向遠程主機上傳文件,pull 模式用於從遠程主機上取文件
2、使用范例
src=some/relative/path dest=/some/absolute/path rsync_path="sudo rsync" src=some/relative/path dest=/some/absolute/path archive=no links=yes src=some/relative/path dest=/some/absolute/path checksum=yes times=no src=/tmp/helloworld dest=/var/www/helloword rsync_opts=--no-motd,--exclude=.git mode=pull
十二、mount模塊
1、幫助信息
1 dump fstype:必選項,掛載文件的類型 2 name:必選項,掛載點 3 opts:傳遞給mount命令的參數 4 src:必選項,要掛載的文件 5 state:必選項 present:只處理fstab中的配置 absent:刪除掛載點 mounted:自動創建掛載點並掛載之 umounted:卸載
2、使用范例
name=/mnt/dvd src=/dev/sr0 fstype=iso9660 opts=ro state=present name=/srv/disk src='LABEL=SOME_LABEL' state=present name=/home src='UUID=b3e48f45-f933-4c8e-a700-22a159ec9077' opts=noatime state=present ansible test -a 'dd if=/dev/zero of=/disk.img bs=4k count=1024' ansible test -a 'losetup /dev/loop0 /disk.img' ansible test -m filesystem 'fstype=ext4 force=yes opts=-F dev=/dev/loop0' ansible test -m mount 'name=/mnt src=/dev/loop0 fstype=ext4 state=mounted opts=rw'
十三、get_url
1、幫助信息
1 sha256sum:下載完成后進行sha256 check; 2 timeout:下載超時時間,默認10s 3 url:下載的URL 4 url_password、url_username:主要用於需要用戶名密碼進行驗證的情況 5 use_proxy:是事使用代理,代理需事先在環境變更中定義
2、使用示例
- name: download foo.conf get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440 - name: download file with sha256 check get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf sha256sum=b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c
十四、其他模塊見鏈接
官方提供的可能用到模塊有git、svn版本控制模塊,sysctl 、authorized_key_module系統模塊,apt、zypper、pip、gem包管理模塊,find、template文件模塊,mysql_db、redis數據庫模塊,url 網絡模塊
https://docs.ansible.com/ansible/latest/modules/modules_by_category.html
ansible暫停模塊:https://www.cnblogs.com/Csir/p/8653114.html