ansible基本應用

永遠十八歲 2021-08-15 20:52:22 阅读数:822

本文一共[544]字,预计阅读时长:1分钟~
ansible 基本

1. ansible特性:

  • ansible糅合了眾多老牌運維工具的優點,基本上pubbet和saltstack能實現的功能全部能實現。
  • 部署簡單:不需要在被管控主機上安裝任何客戶端,操作客戶端時直接運行命令。
  • 基於python語言實現,有Paramiko, PyYAML和Jinja2三個關鍵模塊。
  • 模塊化:調用特定模塊完成特定任務。可使用任意語言開發模塊,且支持自定義模塊。
  • 使用yaml語言定制劇本playbook。
  • 基於SSH作

2. ansible的模塊

  • connection plugins:連接插件,通過ssh方式
  • host inventory:主機清單,要管理的主機
  • playbooks:劇本,yaml格式的配置文件
  • core modules:核心模塊
  • custom modules:自定義模塊
  • plugins:插件 - email:發送郵件。 - loggings:記錄日志

3. 安裝

ansible放置比特置:

  • 外網主機:可通過VPN連接為內網主機進行管理
  • 內網主機:直接管理

ansible的安裝: 配置好epel源,直接通過yum安裝

~]# yum -y install ansible
複制代碼

ansible的配置文件:/etc/ansible/ansible.cfg ansible的主機清單:/etc/ansible/hosts **ansible的主程序:**ansible、ansible-playbos、ansible-doc

4. ansible命令的使用:

[[email protected] ~]# ansible -h
Usage: ansible <host-pattern> [options]
Options:
-a MODULE_ARGS, --args=MODULE_ARGS
module arguments 模塊參數
-C, --check don't make any changes; instead, try to predict some
of the changes that may occur 幹跑模式
-m MODULE_NAME, --module-name=MODULE_NAME
module name to execute (default=command) 指定模塊名稱
--syntax-check perform a syntax check on the playbook, but do not execute it
語法檢測
-f FORKS, --forks=FORKS
specify number of parallel processes to use (default=5)
同時啟用多少個線程,默認5個
-u REMOTE_USER, --user=REMOTE_USER
connect as this user (default=None)
-c CONNECTION, --connection=CONNECTION
connection type to use (default=smart)
--list-hosts outputs a list of matching hosts; does not execute anything else
列出主機列錶,不做其他任何處理。
-b, --become run operations with become (does not imply password prompting)
複制代碼

5. 定義主機列錶:

示例1. 通過直接指定主機名或IP地址定義主機列錶。

# Ex 1: Ungrouped hosts, specify before any group headers.
 ## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10
複制代碼

示例2. 先定義組名,再在組下填入主機名或IP地址

# Ex 2: A collection of hosts belonging to the 'webservers' group
 ## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110
 # If you have multiple hosts following a pattern you can specify
# them like this:
# 如果有多個連續主機,也可用如下方法指定主機。
 ## www[001:006].example.com
複制代碼

示例3.

# Ex 3: A collection of database servers in the 'dbservers' group
 ## [dbservers]
##
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57
 # Here's another example of host ranges, this time there are no
# leading 0s:
 ## db-[99:101]-node.example.com
## 以上寫法可擴展為如下主機:
## db-99-nod.example.com
## db-100-nod.example.com
## db-101-nod.example.com
複制代碼

定義主機列錶示例1:

[[email protected] ~]# tail -2 /etc/ansible/hosts
np[1:2].lxk.com
nfs.lxk.com
複制代碼

獲取主機列錶:

[[email protected] ~]# ansible all --list-hosts
hosts (3):
np1.lxk.com
np2.lxk.com
nfs.lxk.com
複制代碼

定義主機列錶2:

[[email protected] ansible_workshop]# tail -8 /etc/ansible/hosts
[db]
node1.lxk.com
node2.lxk.com
[web]
np1.lxk.com
np2.lxk.com
[nfs]
nfs.lxk.com
複制代碼

獲取主機列錶:

[[email protected] ansible_workshop]# ansible all --list-hosts
hosts (5):
node1.lxk.com
node2.lxk.com
np1.lxk.com
np2.lxk.com
nfs.lxk.com
[[email protected] ansible_workshop]# ansible db --list-hosts
hosts (2):
node1.lxk.com
node2.lxk.com
[[email protected] ansible_workshop]# ansible web --list-hosts
hosts (2):
np1.lxk.com
np2.lxk.com
複制代碼

6. ansible的常用模塊:

獲取模塊幫助信息:

[[email protected] ~]# ansible-doc --help
Usage: ansible-doc [-l|-F|-s] [options] [plugin]
plugin documentation tool
Options:
-a, --all **For internal testing only** Show documentation for
all plugins. #內測使用
-h, --help show this help message and exit
-l, --list List available plugins 顯示可用插件
-s, --snippet Show playbook snippet for specified plugin(s)
## 顯示指定插件用法
複制代碼

獲取模塊列錶:

~]# ansible-doc -l
複制代碼

6.1 ping模塊:探測遠程主機

[[email protected] ~]# ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
# 嘗試連接主機,若目標主機可用,就回應一個'pong'
ping:
data: # Data to return for the `ping' return value. If this parameter is set to `crash', the module will cause an exception.
複制代碼

**示例1:**向所有可控主機發起ping操作

[[email protected] ~]# ansible all -m ping
np2.lxk.com | SUCCESS => {
"changed": false,
"ping": "pong"
}
nfs.lxk.com | SUCCESS => {
"changed": false,
"ping": "pong"
}
np1.lxk.com | SUCCESS => {
"changed": false,
"ping": "pong"
}
複制代碼

**示例2:**data自定義回顯內容為abc

[[email protected] ~]# ansible all -m ping -a data='abc'
np1.lxk.com | SUCCESS => {
"changed": false,
"ping": "abc"
}
np2.lxk.com | SUCCESS => {
"changed": false,
"ping": "abc"
}
nfs.lxk.com | SUCCESS => {
"changed": false,
"ping": "abc"
}
複制代碼

**示例3:*data為crash時,顯示結果為false

[[email protected] ~]# ansible all -m ping -a data='crash'
np1.lxk.com | FAILED! => {
"changed": false,
"module_stderr": "Shared connection to np1.lxk.com closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n File \"/tmp/ansible_2DLaM3/ansible_module_ping.py\", line 84, in <module>\r\n main()\r\n File \"/tmp/ansible_2DLaM3/ansible_module_ping.py\", line 74, in main\r\n raise Exception(\"boom\")\r\nException: boom\r\n",
"msg": "MODULE FAILURE",
"rc": 1
}
nfs.lxk.com | FAILED! => {
"changed": false,
"module_stderr": "Shared connection to nfs.lxk.com closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n File \"/tmp/ansible_imV6B2/ansible_module_ping.py\", line 84, in <module>\r\n main()\r\n File \"/tmp/ansible_imV6B2/ansible_module_ping.py\", line 74, in main\r\n raise Exception(\"boom\")\r\nException: boom\r\n",
"msg": "MODULE FAILURE",
"rc": 1
}
np2.lxk.com | FAILED! => {
"changed": false,
"module_stderr": "Shared connection to np2.lxk.com closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n File \"/tmp/ansible_iocg2P/ansible_module_ping.py\", line 84, in <module>\r\n main()\r\n File \"/tmp/ansible_iocg2P/ansible_module_ping.py\", line 74, in main\r\n raise Exception(\"boom\")\r\nException: boom\r\n",
"msg": "MODULE FAILURE",
"rc": 1
}
複制代碼

6.2 command模塊:在遠程主機上運行命令

模塊用法: 對於command來說,要使用哪個命令,使用-a選項,直接給出命令本身即可。

例1:創建臨時文件

[[email protected] ~]# ansible all -m command -a "mktemp /tmp/abc.XXXX"
nfs.lxk.com | SUCCESS | rc=0 >>
/tmp/abc.Xyz7
np2.lxk.com | SUCCESS | rc=0 >>
/tmp/abc.lwqo
np1.lxk.com | SUCCESS | rc=0 >>
/tmp/abc.jjHW
複制代碼

例2:創建用戶

[[email protected] ~]# ansible all -m command -a "useradd user1" # 第一次創建成功
nfs.lxk.com | SUCCESS | rc=0 >>
np1.lxk.com | SUCCESS | rc=0 >>
np2.lxk.com | SUCCESS | rc=0 >>
[[email protected] ~]# ansible all -m command -a "useradd user1" #第二次創建相同用戶失敗
nfs.lxk.com | FAILED | rc=9 >>
useradd: user 'user1' already existsnon-zero return code
np1.lxk.com | FAILED | rc=9 >>
useradd: user 'user1' already existsnon-zero return code
np2.lxk.com | FAILED | rc=9 >>
useradd: user 'user1' already existsnon-zero return code
複制代碼

用加條件判斷創建用戶失敗,因||是直接發給目標主機內核運行,不是經由shell運行,而||是shell的內置命令。

[[email protected] ~]# ansible all -m command -a "id user1 || useradd user1"
nfs.lxk.com | FAILED | rc=1 >>
id: extra operand ‘||’
Try 'id --help' for more information.non-zero return code
np1.lxk.com | FAILED | rc=1 >>
id: extra operand ‘||’
Try 'id --help' for more information.non-zero return code
np2.lxk.com | FAILED | rc=1 >>
id: extra operand ‘||’
Try 'id --help' for more information.non-zero return code
複制代碼

6.3 shell模塊:在節點中執行命令

與command模塊很相似,所不同處是它是在shell下運行的。還可使用executable切換至指定node下運行命令。 **例:**加條件判斷創建用戶

[[email protected] ~]# ansible all -m shell -a "id user1 || useradd user1"
np2.lxk.com | SUCCESS | rc=0 >>
uid=1001(user1) gid=1001(user1) groups=1001(user1)
nfs.lxk.com | SUCCESS | rc=0 >>
uid=1000(user1) gid=1000(user1) groups=1000(user1)
np1.lxk.com | SUCCESS | rc=0 >>
uid=1000(user1) gid=1000(user1) groups=1000(user1)
複制代碼

6.4 group模塊:添加或删除組

group模塊用法:

[[email protected] ~]# ansible-doc -s group
- name: Add or remove groups
group:
gid: # Optional `GID' to set for the group.是否使用自定義的id號
name: # (required) Name of the group to manage. 要管理的組名,必須要定義的。
state: # Whether the group should be present or not on the remote host. 狀態信息,决定是删除還是添加。創建:present,删除:absent
system: # If `yes', indicates that the group created is a system group. 是否創建系統用戶
複制代碼

**示例:**創建一個系統組

[[email protected] ~]# ansible np1.lxk.com -m group -a 'name=mygrp gid=200 system=yes'
np1.lxk.com | SUCCESS => {
"changed": true, #變更:成功
"gid": 200, #自定義組ID:200
"name": "mygrp", #組名:mygrp
"state": "present", #狀態:添加
"system": true #是否為系統用戶:是
}
複制代碼

**示例:**删除組

[[email protected] ~]# ansible np1.lxk.com -m group -a 'name=mygrp state=absent'
np1.lxk.com | SUCCESS => {
"changed": true,
"name": "mygrp",
"state": "absent"
}
複制代碼

上面命令重複執行時,changed狀態為false。

[[email protected] ~]# ansible np1.lxk.com -m group -a 'name=mygrp state=absent'
np1.lxk.com | SUCCESS => {
"changed": false,
"name": "mygrp",
"state": "absent"
}
複制代碼

6.5 user模塊:管理用戶帳戶

模塊內置命令一堆,請自行查看,基本見名知意。 **示例:**創建一個用戶,名字為tom,用戶ID為2000,組名為mygrp,shell類型為/bin/bash,狀態為添加。

[[email protected] ~]# ansible np1.lxk.com -m user -a 'name=tom state=present uid=2000 groups=mygrp shell=/bin/bash'
np1.lxk.com | SUCCESS => {
"changed": true,
"comment": "",
"create_home": true,
"group": 2000,
"groups": "mygrp",
"home": "/home/tom",
"name": "tom",
"shell": "/bin/bash",
"state": "present",
"system": false,
"uid": 2000
}
複制代碼

**示例:**修改tom用戶的ID為2020,shell類型為/bin/tcsh

[[email protected] ~]# ansible np1.lxk.com -m user -a 'name=tom state=present uid=2020 groups=mygrp shell=/bin/tcsh'
np1.lxk.com | SUCCESS => {
"append": false,
"changed": true,
"comment": "",
"group": 2000,
"groups": "mygrp",
"home": "/home/tom",
"move_home": false,
"name": "tom",
"shell": "/bin/tcsh",
"state": "present",
"uid": 2020
}
複制代碼

6.6 copy模塊

[[email protected] ~]# ansible-doc -s copy
- name: Copies files to remote locations #複制一個或多個文件至遠程主機
copy:
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 nonexistent path and if either `dest' ends with "/" or `src' is a directory, `dest' is created. If `src' and `dest' are files, the parent directory of `dest' isn't created: the task fails if it doesn't already exist.
#複制指定文件至目標遠程需要是絕對路徑。如果src是目錄,dest也必須是目錄。如果dest是一個不存在的路徑,並且dest不以/結尾或者src是個目錄,dest會自動創建。如果src和dest都是多個文件,dest的父目錄沒創建,複制就會失敗。
src: # Local path to a file to copy to the remote server; 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 with all contents is copied. This behavior is similar to Rsync.
#本地需要複制到遠程主機的文件的路徑。可以是絕對路徑,也可以是相對路徑。如果路徑是個目錄,則遞歸複制。如果路徑以/結尾,只複制目錄下的文件至目標路徑。如果不以/結尾,則會把目錄以及其下的內容都複制至目標主機。這種行為類似於rsync。
content: # When used instead of `src', sets the contents of a file directly to the specified value. For anything advanced or with formatting also look at the template module.
#如果不使用src而使用content,把文件內容直接指定為content所指定的內容。然後剩下的懶得翻譯了。
owner: # Name of the user that should own the file/directory, as would be fed to `chown'.
mode: # Mode the file or directory should be.
group: # Name of the group that should own the file/directory, as would be fed to `chown'.
複制代碼

**示例1:**通過content指定文件內容並複制至目標主機(若不帶\n,不會自動換行)

[[email protected] ~]# ansible np2.lxk.com -m copy -a 'dest=/tmp/textfile.txt content="hello,brother!\n"'
np2.lxk.com | SUCCESS => {
"changed": true,
"checksum": "8634ff795ad950aa9c762c45cc8b07137248002a",
"dest": "/tmp/textfile.txt",
"gid": 0,
"group": "root",
"md5sum": "2252b10979e37d2884855832666fd811",
"mode": "0644",
"owner": "root",
"size": 15,
"src": "~None/.ansible/tmp/ansible-tmp-1528471338.21-89043902941123/source", #ansible會把給定的源生成一個臨時源當做源文件複制至目標比特置。
"state": "file",
"uid": 0
}
複制代碼

目標主機查看文件內容:

[[email protected] ~]# cat /tmp/textfile.txt
hello,brother!
複制代碼

**示例2:**複制本地/etc/fstab至np1.lxk.com的/tmp目錄下,改名為fstab.txt,屬主改為user2,權限0600.(user2需先創建)

[[email protected] ~]# np1.lxk.com all -m copy -a 'src=/etc/fstab dest=/tmp/fstab.txt owner=user2 mode=0600'
np1.lxk.com | SUCCESS => {
"changed": true,
"checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"dest": "/tmp/fstab.txt",
"gid": 0,
"group": "root",
"md5sum": "5aee64ae648da49b3b16e2b9ea70d279",
"mode": "0600",
"owner": "user2",
"size": 595,
"src": "~None/.ansible/tmp/ansible-tmp-1528518314.71-128514426299583/source",
"state": "file",
"uid": 1024
}
複制代碼

查看目標主機上的文件:

[[email protected] ~]# ll /tmp
total 4
-rw------- 1 user2 root 595 Jun 9 12:25 fstab.txt
複制代碼

6.7 fetch模塊

[[email protected] ~]# ansible-doc -s fetch
- name: Fetches a file from remote nodes #從遠程主機取來文件
fetch:
dest: # (required) A directory to save the file into. For example, if the `dest' directory is `/backup' a `src' file named `/etc/profile' on host `host.example.com', would be saved into `/backup/host.example.com/etc/profile'
#(必須項)要保存文件的目錄。如指定的目錄為/backup,遠程主機host.example.com上的/etc/profile文件會保存在本地/backup/host.example.com/etc/profile
src: # (required) The file on the remote system to fetch. This `must' be a file, not a directory. Recursive fetching may be supported in a later release.
#遠程主機需要fetch的文件,必須是文件,不能是目錄。以後可能會支持目錄。
複制代碼

**示例1:**從遠程主機np1.lxk.com上複制/etc/fstab至本地/tmp目錄下

[[email protected] ~]# ansible np1.lxk.com -m fetch -a 'src=/etc/fstab dest=/tmp/'
np1.lxk.com | SUCCESS => {
"changed": true,
"checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"dest": "/tmp/np1.lxk.com/etc/fstab",
"md5sum": "5aee64ae648da49b3b16e2b9ea70d279",
"remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"remote_md5sum": null
}
複制代碼

**示例2:**從所有可控的遠程主機上複制/etc/fstab至本地/tmp目錄下

[[email protected] ~]# ansible all -m fetch -a 'src=/etc/fstab dest=/tmp/'
np1.lxk.com | SUCCESS => {
"changed": false,
"checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"dest": "/tmp/np1.lxk.com/etc/fstab",
"file": "/etc/fstab",
"md5sum": "5aee64ae648da49b3b16e2b9ea70d279"
}
np2.lxk.com | SUCCESS => {
"changed": true,
"checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"dest": "/tmp/np2.lxk.com/etc/fstab",
"md5sum": "5aee64ae648da49b3b16e2b9ea70d279",
"remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"remote_md5sum": null
}
nfs.lxk.com | SUCCESS => {
"changed": true,
"checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"dest": "/tmp/nfs.lxk.com/etc/fstab",
"md5sum": "5aee64ae648da49b3b16e2b9ea70d279",
"remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"remote_md5sum": null
}
複制代碼

查看本地目錄:

[[email protected] ~]# tree /tmp
/tmp
├── issue.txt
├── nfs.lxk.com
│   └── etc
│   └── fstab
├── np1.lxk.com
│   └── etc
│   └── fstab
└── np2.lxk.com
└── etc
└── fstab
6 directories, 4 files
複制代碼

6.8 file模塊:修改文件的屬性信息

[[email protected] ~]# ansible-doc -s file
- name: Sets attributes of files
file:
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). #在兩種情况下强制創建鏈接:源文件不存在(隨後會出現)或目標存在且是文件(將會取消path指定的文件並創建鏈接)
group: # Name of the group that should own the file/directory, as would be fed to `chown'. #改變文件的屬組
mode: # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers (like `0644' or `01777'). #改變文件或目錄的權限
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. Aliases: `dest', `name' #必須項。要修改的文件的路徑
recurse: # recursively set the specified file attributes (applies only to directories) #遞歸地設置文件屬性
src: # path of the file to link to (applies only to `state=link' and `state=hard'). Will accept absolute, relative and nonexisting paths. Relative paths are not expanded.
#要鏈接到的文件路徑(只適用於“state=link”和“state=hard”)。將接受絕對路徑、相對路徑和不存在路徑。相對路徑沒有展開。
state: # 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', the file 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 `link', the symbolic link will be created or changed. Use `hard' for hardlinks. If `absent', directories will be recursively deleted, and files or symlinks will be unlinked. Note that `absent' will not cause `file' to fail if the `path' does not exist as the state did not change. 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).
如果是目錄,父目錄不存在時會自動創建。
如果是文件,文件不存在時不會創建。
如果是鏈接,將會創建或者改變。
如果是absent,目錄將會被遞歸删除,文件或鏈接會被取消鏈接。
如果是touch,不存在的文件將會被創建。目錄將會更改訪問時間和改變時間。
複制代碼

**示例1:**修改np1.lxk.com主機/tmp/fstab.txt的屬主為mygrp,權限為660

[[email protected] ~]# ansible np1.lxk.com -m file -a 'path=/tmp/fstab.txt group=mygrp mode=0660'
np1.lxk.com | SUCCESS => {
"changed": true,
"gid": 200,
"group": "mygrp",
"mode": "0660",
"owner": "user2",
"path": "/tmp/fstab.txt",
"size": 595,
"state": "file",
"uid": 1024
}
複制代碼

查看目標主機文件屬性:

[[email protected] ~]# ll -d /tmp/fstab.txt
-rw-rw---- 1 user2 mygrp 595 Jun 9 12:25 /tmp/fstab.txt
複制代碼

**示例2:**為np1.lxk.com主機的/tmp/fstab.txt創建軟鏈接/tmp/fstab.link

[[email protected] ~]# ansible np1.lxk.com -m file -a 'path=/tmp/fstab.link src=/tmp/fstab.txt state=link'
np1.lxk.com | SUCCESS => {
"changed": true,
"dest": "/tmp/fstab.link",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"size": 14,
"src": "/tmp/fstab.txt",
"state": "link",
"uid": 0
}
複制代碼

**示例3:**在np1.lxk.com的/tmp目錄下創建目錄file.dir,權限為770

[[email protected] ~]# ansible np1.lxk.com -m file -a 'path=/tmp/file.dir mode=0770 state=directory'
np1.lxk.com | SUCCESS => {
"changed": true,
"gid": 0,
"group": "root",
"mode": "0770",
"owner": "root",
"path": "/tmp/file.dir",
"size": 4096,
"state": "directory",
"uid": 0
}
複制代碼

6.9 get_url模塊:下載文件

**示例:**下載一個文件至np1.lxk.com的/tmp目錄下

[[email protected] ~]# ansible np1.lxk.com -m get_url -a 'dest=/tmp/ url=https://mirrors.aliyun.com/centos/7.5.1804/paas/x86_64/openshift-origin36/jq-devel-1.5-1.el7.x86_64.rpm'
np1.lxk.com | SUCCESS => {
"changed": true,
"checksum_dest": null,
"checksum_src": "c566cb3df854f4551da1ab7f642e96889b77439c",
"dest": "/tmp/jq-devel-1.5-1.el7.x86_64.rpm",
"gid": 0,
"group": "root",
"md5sum": "43f5092eadb4855fb780e67244d997df",
"mode": "0644",
"msg": "OK (6472 bytes)",
"owner": "root",
"size": 6472,
"src": "/tmp/tmpwix52V",
"state": "file",
"status_code": 200,
"uid": 0,
"url": "https://mirrors.aliyun.com/centos/7.5.1804/paas/x86_64/openshift-origin36/jq-devel-1.5-1.el7.x86_64.rpm"
}
複制代碼

查看目標主機/tmp下的文件:

[[email protected] ~]# ls /tmp
file.dir fstab.link fstab.txt jq-devel-1.5-1.el7.x86_64.rpm
複制代碼

6.10 cron模塊:創建周期性計劃任務

**示例1:**創建一個時間同步的任務,每5分鐘運行一次。

[[email protected] ~]# ansible np1.lxk.com -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 192.168.200.254 &> /dev/null' name=timesync"
np1.lxk.com | SUCCESS => {
"changed": true,
"envs": [],
"jobs": [
"timesync"
]
}
複制代碼

目標主機上查看任務:

[[email protected] ~]# crontab -l
#Ansible: timesync #注明是由ansible生成的,標識名為timesync
*/5 * * * * /usr/sbin/ntpdate 192.168.200.254 &> /dev/null
複制代碼

**示例2:**删除剛才創建的計劃任務 ansible删除計劃任務是根據name所定義的名字來標識的。

[[email protected] ~]# ansible np1.lxk.com -m cron -a "state=absent name=timesync"
np1.lxk.com | SUCCESS => {
"changed": true,
"envs": [],
"jobs": []
}
複制代碼

查看目標主機計劃任務列錶為空。

6.11 yum模塊:用yum包管理器管理軟件

[[email protected] ~]# ansible-doc -s yum
- name: Manages packages with the `yum' package manager
yum:
conf_file: # The remote yum configuration file to use for the transaction.
#指明當前事務使用哪個repo文件
state: # Whether to install (`present' or `installed', `latest'), or remove (`absent' or `removed') a package.
#安裝選項:presetn、installed、latest
#卸載選項:absent、removed
name: # (required) A package name , or package specifier with version, like `name-1.0'.
#必須項。指定軟件名
skip_broken: # Resolve depsolve problems by removing packages that are causing problems from the transaction.
#跳過錯誤信息
update_only: # When using latest, only update installed packages. Do not install packages. Has an effect only if state is `latest'
#只昇級,如果軟件包未安裝則不安裝。
複制代碼

**示例1:**安裝或者查看nginx軟件是否已安裝

[[email protected] ~]# ansible all -m yum -a "name=nginx state=installed"
nfs.lxk.com | SUCCESS => {
"changed": false,
"msg": "",
"rc": 0,
"results": [
"1:nginx-1.12.2-2.el7.x86_64 providing nginx is already installed"
]
}
np1.lxk.com | SUCCESS => {
"changed": false,
"msg": "",
"rc": 0,
"results": [
"1:nginx-1.12.2-2.el7.x86_64 providing nginx is already installed"
]
}
np2.lxk.com | SUCCESS => {
"changed": false,
"msg": "",
"rc": 0,
"results": [
"1:nginx-1.12.2-2.el7.x86_64 providing nginx is already installed"
]
}
複制代碼

**示例2:**卸載nginx

[[email protected] ~]# ansible all -m yum -a "name=nginx state=absent"
nfs.lxk.com | SUCCESS => {
"changed": true,
"msg": "",
"rc": 0,
…………
太長,不貼了。在命令返回中可以看到Erasing字樣,
…………
複制代碼

**示例3:**使用np1.lxk.com主機的/etc/yum.repos.d/repobak/base.repo安裝httpd軟件

[[email protected] ~]# ansible np1.lxk.com -m yum -a "name=httpd state=installed conf_file=/etc/yum.repos.d/repobak/base.repo"
np1.lxk.com | SUCCESS => {
"changed": true,
"msg": "",
"rc": 0,
"results": [
"Resolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-80.el7.centos will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n httpd x86_64 2.4.6-80.el7.centos base 2.7 M\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 2.7 M\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : httpd-2.4.6-80.el7.centos.x86_64 1/1 \n Verifying : httpd-2.4.6-80.el7.centos.x86_64 1/1 \n\nInstalled:\n httpd.x86_64 0:2.4.6-80.el7.centos \n\nComplete!\n"
]
}
實際顯示效果就是這樣。有點醜。但是安裝成功了。
複制代碼

**示例4:**更新緩存並安裝httpd

[[email protected] ~]# ansible np2.lxk.com -m yum -a "name=httpd state=installed update_cache=yes"
np2.lxk.com | SUCCESS => {
"changed": false,
"msg": "",
"rc": 0,
"results": [
"httpd-2.4.6-80.el7.centos.x86_64 providing httpd is already installed"
]
}
複制代碼

6.12 hostname模塊:管理主機名,通常一次只能設置一個。

[[email protected] ~]# ansible-doc -s hostname
- name: Manage hostname
hostname:
name: # (required) Name of the host
複制代碼

示例:

[[email protected] ~]# ansible np1.lxk.com -m hostname -a "name=np1"
np1.lxk.com | SUCCESS => {
"ansible_facts": {
"ansible_domain": "lxk.com",
"ansible_fqdn": "np1.lxk.com",
"ansible_hostname": "np1",
"ansible_nodename": "np1"
},
"changed": true,
"name": "np1"
}
複制代碼

6.12 git模塊

[[email protected] ~]# ansible-doc -s git
- name: Deploy software (or files) from git checkouts
git:
clone: # If `no', do not clone the repository if it does not exist locally
dest: # (required) The path of where the repository should be checked out. This parameter is required, unless `clone' is set to `no'.
repo: # (required) git, SSH, or HTTP(S) protocol address of the git repository
version: # What version of the repository to check out.
#指定要clone的版本,如果不指,默認為最新版本。
複制代碼

示例: 下載kubernetes至/tmp/kubernetes/

[[email protected] ~]# ansible np1.lxk.com -m git -a 'repo="https://github.com/kubernetes/kubernetes.git" dest=/tmp/kubernetes'
#下載需要等待
複制代碼

查看目標主機下載情况:

[[email protected] ~]# tree -a /tmp/kubernetes
/tmp/kubernetes
└── .git
├── branches
├── config
├── description
├── HEAD
├── hooks
│   ├── applypatch-msg.sample
│   ├── commit-msg.sample
│   ├── post-update.sample
│   ├── pre-applypatch.sample
│   ├── pre-commit.sample
│   ├── prepare-commit-msg.sample
│   ├── pre-push.sample
│   ├── pre-rebase.sample
│   └── update.sample
├── info
│   └── exclude
├── objects
│   ├── info
│   └── pack
└── refs
├── heads
└── tags
10 directories, 13 files
[[email protected] ~]# du -sh /tmp/kubernetes
100K /tmp/kubernetes
#可看到目錄已創建,因下載速度慢,文件還是這麼小。
複制代碼

6.13 pip模塊:Manages Python library dependencies

[[email protected] ~]# ansible-doc -s pip
- name: Manages Python library dependencies
pip:
name: # The name of a Python library to install or the url of the remote package. As of 2.2 you can supply a list of names.
#指定名稱,也可以以URL指定。2.2版本後支持名稱列錶。
state: # The state of module The 'forcereinstall' option is only available in Ansible 2.1 and above.
#同yum的state
version: # The version number to install of the Python library specified in the `name' parameter.
#指定要安裝的版本
複制代碼

6.14 npm模塊:Manage node.js packages with npm

[[email protected] ~]# ansible-doc -s npm
- name: Manage node.js packages with npm
npm:
name: # The name of a node.js library to install
#要安裝的node.js名稱
path: # The base path where to install the node.js libraries
#指明安裝源地址
state: # The state of the node.js library
version: # The version to be installed
複制代碼

6.15 service模塊:管理服務

[[email protected] ~]# ansible-doc -s service
- name: Manage services
service:
arguments: # Additional arguments provided on the command line
enabled: # Whether the service should start on boot. *At least one of state and enabled are required.*
#設置服務是否開機自啟
name: # (required) Name of the service.
#必須項。服務的名稱
pattern: # If the service does not respond to the status command, name a substring to look for as would be found in the output of the `ps' command as a stand- in for a status result. If the string is found, the service will be assumed to be running.
runlevel: # For OpenRC init scripts (ex: Gentoo) only. The runlevel that this service belongs to.
#運行級別
sleep: # If the service is being `restarted' then sleep this many seconds between the stop and start command. This helps to workaround badly behaving init scripts that exit immediately after signaling a process to stop.
#如果服務是重啟,這個選項設置服務關閉後睡眠多長時間再重新開啟服務。
state: # `started'/`stopped' are idempotent actions that will not run commands unless necessary. `restarted' will always bounce the service. `reloaded' will always reload. *At least one of state and enabled are required.* Note that reloaded will start the service if it is not already started, even if your chosen init system wouldn't normally.
#started:開啟服務
#stoped:關閉服務
#restarted:重啟服務
#reloaded:重載服務
#reloaded時,如果服務未啟動會啟動它。
複制代碼

**示例:**啟動httpd服務,並設置開機自啟

[[email protected] ~]# ansible all -m service -a "name=httpd state=started enabled=yes"
nfs.lxk.com | SUCCESS => {
"changed": true,
"enabled": true,
"name": "httpd",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"After": "remote-fs.target basic.target network.target nss-lookup.target tmp.mount system.slice -.mount systemd-journald.socket",
"AllowIsolate": "no",
"AmbientCapabilities": "0",
…………
太長,不複制了
…………
複制代碼

查看所有節點服務狀態:

[[email protected] ~]# ansible all -m shell -a "ss -tnlp | grep 80"
np1.lxk.com | SUCCESS | rc=0 >>
LISTEN 0 128 127.0.0.1:6379 *:* users:(("redis-server",pid=8077,fd=4))
LISTEN 0 128 :::80 :::* users:(("httpd",pid=14265,fd=4),("httpd",pid=14264,fd=4),("httpd",pid=14263,fd=4),("httpd",pid=14262,fd=4),("httpd",pid=14261,fd=4),("httpd",pid=14260,fd=4))
np2.lxk.com | SUCCESS | rc=0 >>
LISTEN 0 128 :::80 :::* users:(("httpd",pid=14845,fd=4),("httpd",pid=14844,fd=4),("httpd",pid=14842,fd=4),("httpd",pid=14841,fd=4),("httpd",pid=14840,fd=4),("httpd",pid=14838,fd=4))
nfs.lxk.com | SUCCESS | rc=0 >>
LISTEN 0 128 :::80 :::* users:(("httpd",pid=6953,fd=4),("httpd",pid=6952,fd=4),("httpd",pid=6951,fd=4),("httpd",pid=6950,fd=4),("httpd",pid=6949,fd=4),("httpd",pid=6948,fd=4))
[[email protected] ~]# ansible all -m shell -a "systemctl is-enabled httpd"
np2.lxk.com | SUCCESS | rc=0 >>
enabled
np1.lxk.com | SUCCESS | rc=0 >>
enabled
nfs.lxk.com | SUCCESS | rc=0 >>
enabled
#所有節點httpd服務都是開機自啟
複制代碼

6.16 setup模塊:獲得目標主機的facts

用法:

[[email protected] ansible_workshop]# ansible np1.lxk.com -m setup
複制代碼

使用setup模塊獲取到的所有主機的facts都可在yaml文件中當作variables直接調用,若fatcs是嵌套的,可以用點號隔開引用。

6.17 template模板:

類似於copy模塊

[[email protected] ansible_workshop]# ansible-doc -s template
- name: Templates a file out to a remote server
template:
src: # (required) Path of a Jinja2 formatted template on the Ansible controller. This can be a relative or absolute path.
# 必須項,源為Jinja2格式的模板
dest: # (required) Location to render the template to on the remote machine. # 必須項,遠程主機上存放模板的比特置
group: # Name of the group that should own the file/directory, as would be fed to `chown'.
# 應該擁有文件/目錄的組的名稱,此處指定的名稱將被發送到“chown”。
owner: # Name of the user that should own the file/directory, as would be fed to `chown'.
#應該擁有該文件/目錄的用戶的名稱,此處指定的名稱將被發送到“chown”。
mode: # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers (like `0644' or `01777'). # 文件或目錄的權限。格式為`0644' 或 `01777'
複制代碼
版权声明:本文为[永遠十八歲]所创,转载请带上原文链接,感谢。 https://gsmany.com/2021/08/20210815205202548v.html