模塊是Ansible執行的最小單位,能夠是由Python編寫,也能夠是Shell編寫,也能夠是由其餘語言編寫。html
測試鏈接可通性,沒有參數。通的話返回pong。node
ansible all -m ping
主要用於獲取主機信息,在playbooks裏常常會用到的一個參數gather_facts就與該模塊相關。setup模塊下常用的一個參數是filter參數,具體使用示例以下(因爲輸出結果較多,這裏只列命令不寫結果)python
每一個被管理節點在接收並運行管理命令以前,會將本身主機相關信息(如系統版本,主機IP地址)告知ansible管理主機mysql
--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
關鍵字 | 說明 | 返回值例子 |
---|---|---|
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 |
ansible web -m setup
執行結果linux
command 命令模塊,默認模塊(可省略),用於在遠程執行命令(不能使用變量)nginx
1 creates:一個文件名,當該文件存在,則該命令不執行 2 free_form:要執行的linux指令 3 chdir:在執行指令以前,先切換到該指定的目錄 4 removes:一個文件名,當該文件不存在,則該選項不執行 5 executable:切換shell來執行指令,該執行路徑必須是一個絕對路徑
# ansible all -a 'date'
cron 定時任務模塊git
# 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:以哪一個用戶的身份執行
ansible db -m cron -a 'minute="" hour="" day="" month="" weekday="" job="" name="(必須填寫)" state=
一、定時設置指定值的寫入便可,沒有設置的能夠不寫(默認是*)web
二、name必須寫redis
三、state有兩個狀態:present(添加(默認值))or absent(移除)sql
ansible db -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state="present"' ansible db -a "crontab -l"
結果以下圖
ansible db -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state="absent"' ansible db -a "crontab -l"
結果以下圖
user模塊是請求的是useradd, userdel, usermod三個指令,goup模塊請求的是groupadd, groupdel, groupmod 三個指令。
# 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.
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:設置用戶的過時時間,值是一個時間戳
注:指定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
批量建立用戶並設置密碼:https://cloud.tencent.com/info/c23babde3ad9ff6bde07c532a6afa1d0.html
yum -y install python-pip pip install --upgrade pip pip install passlib
# 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.
ansible db -m user -a 'name="testops" password="$6$0lwTSmqKOkL.ktgl$OnBexXC7haBf0FRHVMIZM2edDeFWBbpKJ2r9cxVwNvY.vh3IIUzwFz8n7jFglc0CrtQSY12ziDonVL6e71Og2."'
咱們能夠看到被管理主機已建立用戶"testops",而且密碼爲密文已寫入"/etc/shadow"用戶文件中,嘗試用ssh命令使用testops用戶登陸被管理主機,登陸成功!
ansible db -m shell -a "cat /etc/shadow|grep testops" ssh testops@10.0.0.13
ansible db -m user -a 'name="testops" password="$6$0lwTSmqKOkL.ktgl$OnBexXC7haBf0FRHVMIZM2edDeFWBbpKJ2r9cxVwNvY.vh3IIUzwFz8n7jFglc0CrtQSY12ziDonVL6e71Og2."'
結果以下圖
ansible db -m user -a 'name="testops" state="absent" remove="yes"'
注意該用戶下不能有任何進程,不然會報錯以下紅色部分
複製文件
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.
ansible db -m copy -a 'src=/etc/hosts dest=/tmp/ owner=root mode=640 backup=no'
結果以下圖
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'
管理機操做結果以下圖
目標主機結果以下圖
設定文件屬性和建立文件的符號連接
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:刪除目錄、文件或者取消連接文件
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"
安裝程序包
1 config_file:yum的配置文件 2 disable_gpg_check:關閉gpg_check 3 disablerepo:不啓用某個源 4 enablerepo:啓用某個源 5 name:要進行操做的軟件包的名字,也能夠傳遞一個url或者一個本地的rpm包的路徑 6 state:狀態(present安裝,absent卸載,latest最新)
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
ansible web -m yum -a 'name=zsh state=absent'
目標主機驗證
# rpm -q zsh
package zsh is not installed
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)
ansible web -m service -a 'enabled=yes name=httpd state=started'
ansible web -a 'service httpd status' #centOS7.x以前 ansible web -a 'chkconfig --list httpd' #centOS7.x ansible web -a 'systemctl is-enabled httpd'
尤爲是用到複雜命令時(如帶管道符等等)
# 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.
使用command模塊會報錯,沒法獲得想要的結果。
ansible web -m shell -a "ps -ef|grep httpd"
將本地腳本複製到遠程主機,並執行。
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.
#!/bin/bash echo "test ansible script">>/tmp/scripts.ansible
ansible db -m script -a '/tmp/script.sh'
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 模式用於從遠程主機上取文件
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
1 dump fstype:必選項,掛載文件的類型 2 name:必選項,掛載點 3 opts:傳遞給mount命令的參數 4 src:必選項,要掛載的文件 5 state:必選項 present:只處理fstab中的配置 absent:刪除掛載點 mounted:自動建立掛載點並掛載之 umounted:卸載
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'
1 sha256sum:下載完成後進行sha256 check; 2 timeout:下載超時時間,默認10s 3 url:下載的URL 4 url_password、url_username:主要用於須要用戶名密碼進行驗證的狀況 5 use_proxy:是事使用代理,代理需事先在環境變動中定義
- 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