如何使用Ansible自动执行简单的重复任务
介绍
我们将使用ASSIBE进行一些简单的重复任务,例如创建新的Linux用户和复制文件。
示例1 - 使用Ansible的远程系统上安装/删除软件包
要在远程系统上安装软件包,请使用适用于Ansible支持的所有系统的包模块。
此模块实际上调用了每个系统(APT,YUM等)的相关包模块。
也可以使用OS的特定模块,APT也可以使用。
---
- hosts: all
remote_user: tech
become: true
become_method: sudo
tasks:
- name: Install Single Package using package module
package:
name: vim
state: present
- name: Install Multiple packages using package module
package:
name: ['vim','wget','bash-completion','curl']
state: present
- name: Install package for Specific distro - apache on Debian or Ubuntu
package:
name: apache2
state: present
when: ansible_os_family == "Debian"
- name: Install package for Specific distro - apache on CentOS/RHEL/Fedora
package:
name: httpd
state: present
when: ansible_os_family == "RedHat"
要删除包,应将状态值设置为不存在。
示例2 - 使用Ansible的远程系统上启动/停止服务
对于服务管理,我们将使用服务模块。
我们在步骤1中安装了Apache Web服务器,我们将在此处启动该服务并将其设置为在启动时启动。
由于Debian和Redhat系列的服务名称不一样,因此我们必须存在缺陷状态。
---
- hosts: all
remote_user: tech
become: true
become_method: sudo
tasks:
- name: Install Single Package using package module
package:
name: vim
state: present
- name: Start apache service on Debian or Ubuntu
service:
name: apache2
state: started
enabled: yes
when: ansible_os_family == "Debian"
- name: Start apache service on CentOS/RHEL/Fedora
service:
name: httpd
state: started
enabled: yes
when: ansible_os_family == "RedHat"
请参阅Ansible Service Module文档页面上的所有支持的参数。
示例3 - 使用Ansible执行shell命令/脚本
此示例将演示如何在远程系统上执行shell命令和shell脚本。
---
- hosts: all
remote_user: tech
become: true
become_method: sudo
tasks:
- name: Get Top 5 CPU consuming processes
shell: ps aux | sort -nrk 3,3 | head -n 5
register: top
- name: Get Disk partitioning
shell: df -hT
register: df
- debug: var=top.stdout_lines
- debug: var=df.stdout_lines
我们还可以将本地脚本复制到服务器并执行它。
--
- name: Copy and execute a script.
hosts: web-servers
remote_user: user1
become: yes
become_method: sudo
tasks:
- name: Copy local script to remote systems
copy:
src: myscript.sh
dest: /home/user1/myscript.sh
mode: 0777
- name: Execute a script on remote server
command: sh /home/user1/myscript.sh
请参阅下面的输出。
示例4:将多个目录与远程Linux系统同步到本地计算机
为此工作,由于Ansible模块同步使用它,请在远程服务器中安装Rsync。
如果我们敏锐,我们会注意到我们使用的"拉"模块的"拉动"模式来实现这一目标。
---
- hosts: portal
remote_user: tech
become: true
become_method: sudo
tasks:
- name: Fetch Log Files from portal server and save them to local
synchronize:
src: "{{ item.source }}"
dest: "{{ item.dest }}"
mode: pull
with_items:
- { source: '/var/log/apps/Database/2019-08-07', dest: '/home/jtech/Documents/test3/Database' }
- { source: '/var/log/apps/Exceptions/2019-08-07', dest: '/home/jtech/Documentss/test3/Exceptions' }
主机:门户是我们希望从源中拉出文件的远程服务器是我们打算将Andest的远程服务器的目录是本地目录,它将从远程服务器接收资源。
示例5:使用Ansible添加用户到远程服务器
以下是将用户添加到许多远程系统的YAML Playbook,将用户添加到相应的sudoers文件并将用户的公钥复制到远程服务器。
在过去,如果我们想要将新用户添加到几个服务器中,所有这些都将涉及许多痛苦的键盘冲压以获得完成的工作。
要使用此PlayBook,我们假设以下内容:在客户端CarmineAnother用户(Tech在此示例中)上安装的Ansible已在远程系统中使用来自客户端计算机的公钥,并且可以有效地与远程服务器进行通信。
打开/etc/ansible/hosts文件,并在文件末尾添加远程服务器的列表。
一个例子如下所示。
如果默认情况下,远程系统上的SSH端口不是22,请使用完整的冒号和SSH端口号,如图所示。
生成加密的用户密码:
$mkpasswd --method=SHA-512 StrongUserPassword
$w4LFQ39hZz5$l9Uv3rMCJGqHuU1MbXFpJohY/zuDXNxQJhI3Y5wKvgxnaXnnQ/HnqHWhbgwr1w.7Xo.1yOAZ4AJuKAhUNvqhi.
$mkpasswd --method=SHA-512
Password:
$rz9Cx4SvxntT7pQp$VyWqxxkp4GNYml3t8Jlfo/DUXP4ELtfnLGq42GkhAIHq7VWuPRoFSl795rF1JOMycHmmYFTaYSRVO4/nZpWWm.
# With python passlib module
$sudo pip install passlib
$python -c "from passlib.hash import sha512_crypt; print sha512_crypt.encrypt('StrongUserPassword')"
PlayBook:Users.yml
vim /etc/ansible/hosts [web-servers] 192.168.10.20 192.168.10.31:2023 192.168.10.50
创建PlayBook。
--
- hosts: "web-servers"
remote_user: tech
become: true
become_method: sudo
vars:
users:
- "harry"
tasks:
- name: "Create user Harry in the remote web-servers"
user:
name: "{{ item }}"
password: <encrypted-password>
groups: "wheel"
update_password: always
register: user_created
with_items: "{{ users }}"
- name: "Add authorized keys"
authorized_key:
user: "{{ item }}"
key: "{{ lookup('file', '/home/harry/.ssh/id_rsa.pub') }}"
# key: "{{ lookup('file', 'files/'+ item + '.key.pub') }}"
with_items: "{{ users }}"
- name: Add user "harry" to sudo
lineinfile:
path: /etc/sudoers.d/harry
line: 'harry ALL=(ALL) NOPASSWD: ALL'
state: present
mode: 0440
create: yes
validate: 'visudo -cf %s'
- name: Force user to change password
shell: chage -d 0 {{ item }}
when: user_created.changed
将此文件保存在我们选择的目录中,然后运行:
# ansible-playbook users.yml -u tech -K
它会要求我们成为密码。
输入系统中远程用户的密码。
示例6:自动创建本地计算机上的目录,并从远程服务器复制其中文件。
假设我们经常需要将文件从远程服务器复制到本地计算机,我们终于厌倦了手动复制它们,现在我们希望使用Ansible的效率。
可以位于远程服务器中的文件:
/var/log/applications/web/20-08-08/, /var/log/applications/frontend/20-08-08/, /var/log/applications/backend/20-08-08/, /var/log/applications/frontend1/20-08-08/and /var/log/applications/sockets/20-08-08/ /var/log/applications/others/20-08-08/
要在整理本地计算机上的相应目录中的20-08-08子目录中复制文件,我们需要创建相应的目录以匹配远程服务器上存在的内容。
一个例子是创建文件,例如:
/home/tech/logs/web/20-08-08/, /home/tech/logs/frontend/20-08-08/, /home/tech/logs/backend/20-08-08/, /home/tech/logs/frontend1/20-08-08/and /home/tech/logs/sockets/20-08-08/ /home/tech/logs/others/20-08-08/
除了手动创建这些分配器时,Ansible可以在本教程中描述为我们提供。
首先,Ansible将自动创建/home/tech/logs/parent目录,然后自动创建各种子目录(Web,Frontend,beftend,Frontend1,套接字)。
最后,20-08-08子目录将与远程服务器的子目录同步。
我们将找到20-08-08目录和其所有文件在本地计算机上整齐地复制。
让我们创建戏剧来完成这项工作。
步骤一:在任何目录中创建变量文件并输入所有变量。
vim vars.yml -- LOCAL_PROJECT_DIRECTORY: "/home/tech/logs" REMOTE_PROJECT_DIRECTORY: "/var/log/applications"
第二步:将远程服务器添加到主机文件。这可以在默认文件中或者我们创建的任何主机文件中。
vim /etc/ansible/hosts #Add your host [remoteserver] 192.168.20.23
第三步:创建PlayBook以为我们复制目录和文件
vim playbook.yml
--
- hosts: 127.0.0.1 # Create directories and sub-directories in local machine in this play
vars_files:
./variables1/vars.yaml
tasks:
- name: Auto-Create Local parent project directory {{ LOCAL_PROJECT_DIRECTORY }} and sub-directories
file: path={{ LOCAL_PROJECT_DIRECTORY }}/{{ item }} state=directory
with_items:
- web
- frontend
- backend
- Database
- frontend1
- sockets
- others
- hosts: remoteserver # Copy directories and files in local machine from remoteserver in this play
vars_files:
./variables1/vars.yaml
become: true
tasks:
- name: Fetch stuff from your remote server and save to locally autocreated directorie
become: yes
synchronize:
src: "{{ REMOTE_PROJECT_DIRECTORY }}/{{ item }}/20-08-08"
dest: "{{ LOCAL_PROJECT_DIRECTORY }}/{{ item }}/"
mode: pull
with_items: web
- frontend
- backend
- Database
- frontend1
- sockets
- others
完成此操作后,是时候运行剧本了,
# ansible-playbook playbook.yaml -u tech -K
在远程服务器上输入Sudo密码并按Enter键。
示例7:删除系统中的旧用户
--
- hosts: servers
remote_user: tech
become: true
become_method: sudo
vars:
users:
- "Hyman"
- "tom"
- "sharon"
- "tech"
- "pench"
tasks:
name: "Remove old users out of the system"
user:
name: "{{ item }}"
state: "absent"
with_items: "{{ users }}"
示例8:从SVN服务器结帐文件并将它们复制到远程服务器
如果我们希望从Subversion Server中提取文件,并且可以将它们复制到远程服务器上的其他位置,其中包含一个ansible命令,然后本教程显示它是如何完成的。
请跟进。
步骤一:在任何目录中创建变量文件并输入所有变量。
$vim vars.yml -- LOCAL_PROJECT: "/home/tech/svn" REMOTE_PROJECT: "/var/log/applications"
第二步:将远程服务器添加到主机文件。这可以在默认文件中或者我们创建的任何主机文件中。
vim /etc/ansible/hosts [remoteserver] 192.168.20.27
第三步:创建一个PlayBook以将文件从Subversion Server签出到本地计算机,并自动将它们复制到远程服务器。
$vim playbook.yml
--
- hosts: 127.0.0.1
vars_files:
- ./variables1/vars.yaml
tasks:
- name: Auto-Create Local project directory
file: path={{ LOCAL_PROJECT }}/{{ item }} state=directory
with_items:
- App
- name: Checkout subversion repository to the created directory/folder
subversion:
repo: https://path/to/your/subversion/
username: user1
password: strongpassword
checkout: yes
update: yes
in_place: yes
dest: "{{ LOCAL_PROJECT }}/{{ item }}"
with_items:
- App
- hosts: worker1
vars_files:
- ./variables1/vars.yaml
tasks:
- name: Auto-Create Remote project directory
become: yes
file: path={{ REMOTE_PROJECT }}/{{ item }} state=directory
with_items:
- Application
- name: Copy the checked-out files to remote server via Synchronize
become: yes
synchronize:
src: "{{ LOCAL_PROJECT }}/{{ item.local }}/"
dest: "{{ REMOTE_PROJECT }}/{{ item.remote }}"
with_items:
- { local: 'App', remote: 'Application' }
第四步:由于Playbook具有敏感的数据,即用户名和密码,让我们使用Ansible-Vault加密它,以便没有人可以查看东西。
加密PlayBook文件,如下所示。
输入密码,我们将很好。
$ansible-vault encrypt playbook.yml New Vault password: Confirm New Vault password: Encryption successful
完成后,继续使用所示选项运行PlayBook。
它将提示user1的sudo密码和我们刚刚输入的ansible-vault密码。
$ansible-playbook playbook.yml --ask-vault-pass -u user1 -K BECOME password: Vault password:
PLAY [127.0.0.1] ** **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** ***** TASK [Gathering Facts] ** **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** **** ***** ok: [127.0.0.1]

