尝试在Ansible中多次执行Shell命令

准备好

请使用适合的软件包管理器安装 Ansible 软件包。

cygwin環境の場合は gcc-core, openssh, python, python-setuptools を
インストールした上で easy_install pip; pip install ansible を実行

~/.bashrc に export ANSIBLE_SSH_ARGS="-o ControlMaster=no" を追記し反映

SSH连接设置可以在~/.ssh/config文件中按照以下方式进行配置。

Host server1
 HostName nnn.nnn.nnn.nnn
 IdentityFile ~/.ssh/keys/server1.pem
 User user1

当您创建配置文件 ~/.ansible.cfg 时,Ansible会自动加载配置。因此,您可以预先设置目标主机和主机组的配置文件路径等,如下所示。

[defaults]
hostfile = ~/.ansible_hosts

在 ansible_hosts 文件中,所指定的目标主机和主机组将变为可操作的状态。

#対象ホスト記述
server1

#ホストグループ記述
[group1]
server1
server2
server3

#対象ホスト記述には sshの接続パラメータなども指定可能
server1 ansible_ssh_user=xxx ansible_ssh_pass=xxx ansible_ssh_port=nnnn

尝试一下

在group1中的所有主机上运行uname -a命令并获取结果
% ansible -a “uname -a” group1

使用默认的command模块无法使用管道重定向,所以要使用shell模块。
% ansible -m shell -a “uname -a | cut -d’ ‘ -f 3″ group1
可能最好预先定义一个别名。

使用”-o”选项,将输出结果按主机分行输出。
% ansible -m shell -a “uname -a | cut -d’ ‘ -f 3” group1 -o

使用-t选项创建目录,并将输出写入主机名文件
% ansible -m shell -a “uname -a | cut -d’ ‘ -f 3” group1 -t dir
由于是JSON格式,所以可以使用jq命令等自行处理。

如果需要其他用户指定或并行度选项等,请参考此处。

对于目标主机的指定可以使用通配符或者使用“:”进行多条件指定。
% ansible –list-hosts server*
% ansible –list-hosts group1:group2
% ansible –list-hosts group1:!excluded:&required
* 注意:使用–list-hosts选项时,不会执行任何操作,只会输出目标主机的列表。

模块不仅有上述几个,还有许多其他的选项可供选择,如果能熟练使用它们,可以提高系统管理工作的效率。
% ansible -m ping group1
% ansible -m copy -a “src=~/hoge.conf dest=/etc/httpd/conf.d/hoge.conf” group1
% ansible -m service -a “name=httpd state=restarted” group1

以下是中文的翻译:
除了上述模块外,还有很多其他准备好的模块可供使用,如果能熟练掌握,系统管理工作等都会变得更加顺利。
% ansible -m ping group1
% ansible -m copy -a “src=~/hoge.conf dest=/etc/httpd/conf.d/hoge.conf” group1
% ansible -m service -a “name=httpd state=restarted” group1

赠品

使用命令行选择主机和参数进行执行 playbook 模板。

--- # usage: ansible-playbook hoge.yml -e "hosts=server1 param1=aaa"
- hosts: "{{ hosts }}"
  tasks:
    - action: "hoge param1={{ param1 }}"

如果想要进行一些更高级的条件判断和处理的结构化,学习一下playbook的语法会很有帮助。

广告
将在 10 秒后关闭
bannerAds