ansible备忘录

资料

Ansible中文权威指南

安装

源码

$ git clone git://github.com/ansible/ansible.git --recursive
$ cd ./ansible
$ source ./hacking/env-setup

如果没有安装pip, 请先安装对应于你的Python版本的pip:
$ sudo easy_install pip
以下的Python模块也需要安装:
$ sudo pip install paramiko PyYAML Jinja2 httplib2 six

注意,当更新ansible版本时,不只要更新git的源码树,也要更新git中指向Ansible自身模块的 “submodules” (不是同一种模块)
$ git pull --rebase
$ git submodule update --init --recursive

一旦运行env-setup脚本,就意味着Ansible从源码中运行起来了。
默认的inventory文件是 /etc/ansible/hosts.inventory 文件也可以另行指定 :
$ echo "127.0.0.1" > ~/ansible_hosts
$ export ANSIBLE_HOSTS=~/ansible_hosts

你可以在手册的后续章节阅读更多关于 inventory 文件的使用,现在让我们测试一条ping命令:
$ ansible all -m ping --ask-pass
你也可以使用命令 “sudo make install”
#rpm
$ git clone git://github.com/ansible/ansible.git
$ cd ./ansible
$ make rpm
$ sudo rpm -Uvh ~/rpmbuild/ansible-*.noarch.rpm

#yum
yum install epel-release -y
yum install ansible –y

#apt
$ sudo apt-get install software-properties-common
$ sudo apt-add-repository ppa:ansible/ansible
$ sudo apt-get update
$ sudo apt-get install ansible
通过 Pip 安装最新发布版本
Ansible可通过 “pip” 安装(安装和管理Python包的工具),若你还没有安装 pip,可执行如下命令安装:

$ sudo easy_install pip
然后安装Ansible:

$ sudo pip install ansible
如果你是在 OS X Mavericks 上安装,编译器可能或告警或报错,可通过如下设置避免这种情况:

$ sudo CFLAGS=-Qunused-arguments CPPFLAGS=-Qunused-arguments pip install ansible

命令

编辑(或创建)/etc/ansible/hosts 并在其中加入一个或多个远程系统.
你的public SSH key必须在这些系统`authorized_keys`中:
192.168.1.50
aserver.example.org
bserver.example.org
这里有个节点设置文件(inventory file)将会在 Inventory文件 中得到深入说明.

我们假定你使用SSH Key来授权.为了避免在建立SSH连接时,重复输入密码你可以这么做:
$ ssh-agent bash
$ ssh-add ~/.ssh/id_rsa
(根据你的建立方式,你也许希望使用Ansible的 --private-key 选项,通过指定pem文件来代替SSH Key来授权) 

现在ping 你的所有节点:
$ ansible all -m ping
Ansible会像SSH那样试图用你的当前用户名来连接你的远程机器.要覆写远程用户名,只需使用’-u’参数.

如果你想访问 sudo模式,这里也有标识(flags)来实现:
# as bruce
$ ansible all -m ping -u bruce
# as bruce, sudoing to root
$ ansible all -m ping -u bruce --sudo
# as bruce, sudoing to batman
$ ansible all -m ping -u bruce --sudo --sudo-user batman
(如果你碰巧想要使用其他sudo的实现方式,你可以通过修改Ansible的配置文件来实现.也可以通过传递标识给sudo(如-H)来设置.)

现在对你的所有节点运行一个命令:
$ ansible all -a "/bin/echo hello"

Inventory文件

参数

ANSIBLE_CONFIG (一个环境变量)
ansible.cfg (位于当前目录中)
.ansible.cfg (位于家目录中)
/etc/ansible/ansible.cfg

/etc/ansible/hosts

mail.example.com

[webservers]
foo.example.com
bar.example.com

[dbservers]
one.example.com
two.example.com
three.example.com
方括号[]中是组名,用于对系统进行分类,便于对不同系统进行个别的管理.

一个系统可以属于不同的组,比如一台服务器可以同时属于 webserver组 和 dbserver组.
这时属于两个组的变量都可以为这台主机所用,至于变量的优先级关系将于以后的章节中讨论.

如果有主机的SSH端口不是标准的22端口,可在主机名之后加上端口号,用冒号分隔.
SSH 配置文件中列出的端口号不会在 paramiko 连接中使用,会在 openssh 连接中使用.

端口号不是默认设置时,可明确的表示为:
badwolf.example.com:5309

假设你有一些静态IP地址,希望设置一些别名,但不是在系统的 host 文件中设置,又或者你是通过隧道在连接,那么可以设置如下:
jumper ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50

在这个例子中,通过 “jumper” 别名,会连接 192.168.1.50:5555.
记住,这是通过 inventory 文件的特性功能设置的变量. 一般而言,这不是设置变量(描述你的系统策略的变量)的最好方式.

一组相似的 hostname , 可简写如下:
[webservers]
www[01:50].example.com

数字的简写模式中,01:50 也可写为 1:50,意义相同.你还可以定义字母范围的简写模式:
[databases]
db-[a:f].example.com

对于每一个 host,你还可以选择连接类型和连接用户名:
[targets]

localhost              ansible_connection=local
other1.example.com     ansible_connection=ssh        ansible_ssh_user=mpdehaan
other2.example.com     ansible_connection=ssh        ansible_ssh_user=mdehaan

Ansible的配置文件

被读取的顺序如下:

  • ANSIBLE_CONFIG (一个环境变量)
  • ansible.cfg (位于当前目录中)
  • .ansible.cfg (位于家目录中)
  • /etc/ansible/ansible.cfg

ansible.cfg

    [defaults]
    # some basic default values...
    hostfile       = /etc/ansible/hosts   \\指定默认hosts配置的位置
    # library_path = /usr/share/my_modules/
    remote_tmp     = $HOME/.ansible/tmp
    pattern        = *
    forks          = 5
    poll_interval  = 15
    sudo_user      = root  \\远程sudo用户
    #ask_sudo_pass = True  \\每次执行ansible命令是否询问ssh密码
    #ask_pass      = True  \\每次执行ansible命令时是否询问sudo密码
    transport      = smart
    remote_port    = 22
    module_lang    = C
    gathering = implicit
    host_key_checking = False    \\关闭第一次使用ansible连接客户端是输入命令提示
    log_path    = /var/log/ansible.log \\需要时可以自行添加。chown -R root:root ansible.log
    system_warnings = False    \\关闭运行ansible时系统的提示信息,一般为提示升级
    # set plugin path directories here, separate with colons
    action_plugins     = /usr/share/ansible_plugins/action_plugins
    callback_plugins   = /usr/share/ansible_plugins/callback_plugins
    connection_plugins = /usr/share/ansible_plugins/connection_plugins
    lookup_plugins     = /usr/share/ansible_plugins/lookup_plugins
    vars_plugins       = /usr/share/ansible_plugins/vars_plugins
    filter_plugins     = /usr/share/ansible_plugins/filter_plugins
    fact_caching = memory
    [accelerate]
    accelerate_port = 5099
    accelerate_timeout = 30
    accelerate_connect_timeout = 5.0
    # The daemon timeout is measured in minutes. This time is measured
    # from the last activity to the accelerate daemon.
    accelerate_daemon_timeout = 30
inventory = /etc/ansible/hosts #这个参数表示资源清单 inventory 文件的位置
library = /usr/share/ansible #指向存放 Ansible 模块的目录,支持多个目录方式,只要用冒号(:)隔开就可以
forks = 5 #并发连接数,默认为 5
sudo_user = root #设置默认执行命令的用户
remote_port = 22 #指定连接被管节点的管理端口,默认为 22 端口,建议修改,能够更加安全
host_key_checking = False #设置是否检查 SSH 主机的密钥,值为 True/False。关闭后第一次连接不会提示配置实例
timeout = 60 #设置 SSH 连接的超时时间,单位为秒
log_path = /var/log/ansible.log #指定一个存储 ansible 日志的文件(默认不记录日志)

常用配置

# This is the configuration file for ansible.
# The default inventory file used by ansible is located at /etc/ansible/hosts.
# You can specify a different inventory file by using the -i option on the command line.
inventory      = /etc/ansible/hosts
# By default, ansible will use the SSH protocol to connect to remote hosts.
# You can specify a different connection type by using the -c option on the command line.
connection     = ssh
# By default, ansible will use the Python interpreter to execute remote commands.
# You can specify a different interpreter by using the -e option on the command line.
executable     = /usr/bin/python
# By default, ansible will use the 'sudo' command to execute commands as root.
# You can specify a different privilege escalation method by using the -b or -u options on the command line.
become         = True
become_method  = sudo
# By default, ansible will use the 'ansible' user to connect to remote hosts.
# You can specify a different remote user by using the -u option on the command line.
remote_user    = ansible
# You can specify a different private key file by using the -i option on the command line.
private_key_file = /home/ansible/.ssh/id_rsa
# By default, ansible will try to use ControlPersist to reuse SSH connections.
# If you don't want to use ControlPersist, you can disable it by setting this option to 0.
ssh_control_path = /tmp/ansible-ssh-%%h-%%p-%%r
# By default, ansible will display colored output.
# If you don't want to use colored output, you can disable it by setting this option to 0.
color          = True
# By default, ansible will display a warning message if it encounters SSH host key changes.
# If you don't want to display this message, you can disable it by setting this option to 0.
host_key_checking = True
# By default, ansible will display a warning message if it encounters SSH authentication errors.
# If you don't want to display this message, you can disable it by setting this option to 0.
ssh_args = -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no
# By default, ansible will display a warning message if it encounters any undefined variables in your playbooks.
# If you don't want to display this message, you can disable it by setting this option to 0.
display_skipped_hosts = False
以下是一些常见的`ansible.cfg`配置项及其注释和翻译:
# This is the main configuration file for ansible.
# 这是ansible的主配置文件。

# The default inventory file used by ansible is located at /etc/ansible/hosts.
# You can specify a different inventory file by using the -i option on the command line.
# ansible默认使用的清单文件位于/etc/ansible/hosts。
您可以使用命令行上的-i选项指定不同的清单文件。

# By default, ansible will use the SSH protocol to connect to remote hosts.
# You can specify a different connection type by using the -c option on the command line.
默认情况下,ansible将使用SSH协议连接到远程主机。
您可以使用命令行上的-c选项指定不同的连接类型。

# By default, ansible will use the Python interpreter to execute remote commands.
# You can specify a different interpreter by using the -e option on the command line.
默认情况下,ansible将使用Python解释器执行远程命令。
您可以使用命令行上的-e选项指定不同的解释器。

# By default, ansible will use the 'sudo' command to execute commands as root.
# You can specify a different privilege escalation method by using the -b or -u options on the command line.
默认情况下,ansible将使用'sudo'命令以root身份执行命令。
您可以使用命令行上的-b或-u选项指定不同的特权升级方法。

# By default, ansible will use the 'ansible' user to connect to remote hosts.
# You can specify a different remote user by using the -u option on the command line.
默认情况下,ansible将使用“ ansible”用户连接到远程主机。
您可以使用命令行上的-u选项指定不同的远程用户。

# By default, ansible will try to use ControlPersist to reuse SSH connections.
# If you don't want to use ControlPersist, you can disable it by setting this option to 0.
默认情况下,ansible将尝试使用ControlPersist重用SSH连接。
如果您不想使用ControlPersist,则可以通过将此选项设置为0来禁用它。

# By default, ansible will display colored output.
# If you don't want to use colored output, you can disable it by setting this option to 0.
默认情况下,ansible将显示彩色输出。
如果您不想使用彩色输出,则可以通过将此选项设置为0来禁用它。

# By default, ansible will display a warning message if it encounters SSH host key changes.
# If you don't want to display this message, you can disable it by setting this option to 0.
默认情况下,ansible将在遇到SSH主机密钥更改时显示警告消息。
如果您不想显示此消息,则可以通过将此选项设置为0来禁用它。

# By default, ansible will display a warning message if it encounters SSH authentication errors.
# If you don't want to display this message, you can disable it by setting this option to 0.
默认情况下,ansible将在遇到SSH身份验证错误时显示警告消息。
如果您不想显示此消息,则可以通过将此选项设置为0来禁用它。

# By default, ansible will display a warning message if it encounters any undefined variables in your playbooks.
# If you don't want to display this message, you can disable it by setting this option to 0.
默认情况下,ansible将在playbook中遇到任何未定义的变量时显示警告消息。
如果您不想显示此消息,则可以通过将此选项设置为0来禁用它。

常用命令

ansible 附加 11 个常用命令使用方法:
1,查看所有机器时间信息
[root@CentOS7 .ssh]# ansible all -m shell -a "date"

10.211.55.75 | CHANGED | rc=0 >>
Tue Nov 30 01:14:55 EST 2021

2, 指定节点上的权限,属主和数组为 root
ansible '*' -m file -a "dest=/tmp/t.sh mode=755 owner=root group=root"

3, 在节点上安装 httpd
ansible all -m yum -a "state=present name=httpd"

4, 在节点上启动服务,并开机自启动
ansible all -m service -a 'name=httpd state=started enabled=yes'

5, 检查主机连接
ansible '*' -m ping

6, 执行远程命令
ansible '*' -m command -a 'uptime'

7, 执行主控端脚本
ansible '*' -m script -a '/root/test.sh'

8, 执行远程主机的脚本
ansible '*' -m shell -a 'ps aux|grep zabbix'

9, 复制文件到远程服务器
ansible '*' -m copy -a "src=/etc/ansible/ansible.cfg dest=/tmp/ansible.cfg
owner=root group=root mode=0644"

10, 在节点上运行 hostname
ansible all -m raw -a 'hostname|tee'

11, 将指定 url 上的文件下载到/tmp 下
ansible all -m get_url -a 'url=http://10.211.55.75/index.html dest=/tmp'

Playbook

#创建一个用户,设置密码

[root@ansibleansible]#vim user1.yml
 ---
 - hosts:"{{hostname}}"
    remote_user:root
  tasks:
  - user:
     name: "{{username}}"
     group:root
     password:"{{'password' | password_hash('sha512')}}"
  - shell:chage -d 0

[root@ansible ansible]# ansible-playbook user1.yml

- `hosts:"{{hostname}}"`:这个Playbook将会在的主机上运行。这个参数可以是一个主机组的名称,也可以是一个主机的名称,多个主机可以用逗号分隔。
- `remote_user: root`:在远程主机上运行任务时,使用`root`用户来执行任务。
- `tasks:`:这个关键字标志着以下的任务列表。
- `- user:`:使用Ansible的`user`模块来创建一个新的用户。
  - `name: "{{username}}"`:这个参数指定新用户的用户名,它的值将会来自于在执行Playbook时传递给Ansible的`username`变量。
  - `group: root`:这个参数指定新用户所属的用户组,默认为`root`。
  - `password: "{{'password' | password_hash('sha512')}}"`:这个参数指定新用户的密码,使用了Ansible的`password_hash`过滤器将明文密码转换为哈希密码。在这个例子中,密码的值为`password`,您可以将其替换为您想要设置的密码。
- `- shell: chage -d 0`:使用`chage`命令来强制新用户在第一次登录时更改密码。`chage`命令的`-d`选项指定了上次更改密码的日期,`0`表示当前日期,这将会强制新用户在第一次登录时更改密码。
#ping命令检测

[root@ansibleansible]#vim ping.yml
 ---
 - hosts:all
  remote_user:root
  tasks:
   - ping:

[root@ansible ansible]# ansible-playbook ping.yml
#安装Apache,修改端口,配置ServerName和主页,开机自启

[root@ansibleansible]#vimhttp.yml
 ---
 - hosts:"{{hostname}}"
  remote_user:root
  tasks:
   - name:install one specific version of Apache
       yum:
		name:httpd //安装 Apache
		state:installed
	- lineinfile:
		path:/etc/httpd/conf/httpd.conf
		regexp:'^Listen '
		line: 'Listen 8080' //修改端口为 8080
	- replace:
		path:/etc/httpd/conf/httpd.conf
		regexp:'^#(ServerName).*' //配置 ServerName
		replace:'\1 localhost'
	- service:
		name:httpd
		enabled: yes //开机自启
		state:restarted
	- copy:
		src:/root/index.html //修改主页,可以自己写个页面
 		dest:/var/www/html/index.html

 [root@ansible ansible]# curl "{{主机IP地址}}":8080
hello world
[root@ansible ansible]# ssh "{{hostname}}" 
Last login:Fri Sep 7 09:32:05 2018 from "{{主机IP地址}}"
[root@cache~]# apachectl -t
Syntax OK

- `- hosts: "{{hostname}}"`: 这个 Playbook 将在特定的主机上运行,这个主机将由在执行 Playbook 时传递给 Ansible 的 `hostname` 变量决定。
- `remote_user: root`: 在远程主机上运行任务时,使用 `root` 用户来执行任务。
- `tasks:`:这个关键字标志着以下的任务列表。
- `- name: install one specific version of Apache`:使用 `yum` 模块来安装 Apache。
  - `yum:`:使用 `yum` 模块来安装指定的软件包。
    - `name: httpd`:这个参数指定了要安装的软件包名称,这里指定的是 Apache。
    - `state: installed`:这个参数指定了安装软件包的状态,这里指定的是已安装。
- `- lineinfile:`:使用 `lineinfile` 模块来修改 Apache 端口号。
  - `path: /etc/httpd/conf/httpd.conf`:这个参数指定了要修改的文件路径和名称。
  - `regexp: '^Listen '`:这个参数指定了要查找的行的正则表达式。
  - `line: 'Listen 8080'`:这个参数指定了要插入的新行,这里将 Apache 的端口号修改为了 `8080`。
- `- replace:`:使用 `replace` 模块来配置 Apache 的 ServerName。
  - `path: /etc/httpd/conf/httpd.conf`:这个参数指定了要修改的文件路径和名称。
  - `regexp: '^#(ServerName).*'`:这个参数指定了要查找的行的正则表达式。
  - `replace: '\1 localhost'`:这个参数指定了要替换的行,这里将注释掉的 ServerName 行的值修改为了 `localhost`。
- `- service:`:使用 `service` 模块来启动 Apache 服务。
  - `name: httpd`:这个参数指定了要启动的服务名称,这里指定的是 Apache。
  - `enabled: yes`:这个参数指定了是否开机自启,这里指定了是。
  - `state: restarted`:这个参数指定了服务的状态,这里指定了重启。
- `- copy:`:使用 `copy` 模块来修改 Apache 的默认主页。
  - `src: /root/index.html`:这个参数指定了源文件的路径和名称,这里指定的是 `/root/index.html`。
  - `dest: /var/www/html/index.html`:这个参数指定了目标文件的路径和名称,这里指定的是 `/var/www/html/index.html`。
posted @ 2023-05-18 16:52  Mugetsukun  阅读(12)  评论(0编辑  收藏  举报