用户指南

https://docs.ansible.com/ansible/2.9/user_guide/index.html

Welcome to the Ansible User Guide!

This guide covers how to work with Ansible, including using the command line, working with inventory, and writing playbooks.

https://docs.ansible.com/ansible/2.9/user_guide/quickstart.html

We’ve recorded a short video that introduces Ansible.

https://www.ansible.com/resources/videos/quick-start-video

https://www.redhat.com/en/blog/system-administrators-guide-getting-started-ansible-fast (A system administrators guide to getting started with Ansible) 一篇入门指南

https://opensource.com/downloads/ansible-quickstart (A downloadable guide for getting started with Ansible)

https://docs.ansible.com/ansible/2.9/user_guide/basic_concepts.html

These concepts are common to all uses of Ansible.

  • Control node
    • 控制节点
  • Managed nodes
    • 被控节点
  • Inventory
    • 主机清单
    • Inventory A list of managed nodes. 一个文本文件,里面定义了要控制的IP地址列表
  • Modules
    • The units of code Ansible executes Each module has a particular use
    • 功能模块
  • Tasks
    • 任务
    • The units of action in Ansible
    • You can execute a single task once with an ad-hoc command.
  • Playbooks
    • 剧本
    • Ordered lists of tasks, saved so you can run those tasks in that order repeatedly.
    • Playbooks can include variables as well as tasks
    • Playbooks are written in YAML and are easy to read, write, share and understand.

https://docs.ansible.com/ansible/2.9/user_guide/intro_getting_started.html

This page illustrates the basic process with a simple inventory and an ad-hoc command. Once you understand how Ansible works, you can read more details about ad-hoc commands, organize your infrastructure with inventory, and harness the full power of Ansible with playbooks.

ad-hoc 即直接终端敲Ansible命令

Selecting machines from inventory use either IP addresses or FQDNs

192.0.2.50
aserver.example.org
bserver.example.org

Your inventory can store much more than IPs and FQDNs. You can create aliases, set variable values for a single host with host vars, or set variable values for multiple hosts with group vars.

FQDN 全主机名 hostname --fqdn

Ansible communicates with remote machines over the SSH protocol. By default, Ansible uses native OpenSSH and connects to remote machines using your current user name, just as SSH does.

Confirm that you can connect using SSH to all the nodes in your inventory using the same username. If necessary, add your public SSH key to the authorized_keys file on those systems.

Ansible 在远程主机执行的默认用户可以更换

Action: run your first Ansible commands

$ ansible all -m ping
$ ansible all -a "/bin/echo hello"

If you need privilege escalation (sudo and similar) to run a command, pass the become flags:

# as bruce
$ ansible all -m ping -u bruce
# as bruce, sudoing to root (sudo is default method)
$ ansible all -m ping -u bruce --become
# as bruce, sudoing to batman
$ ansible all -m ping -u bruce --become --become-user batman

Congratulations! You have contacted your nodes using Ansible. You used a basic inventory file and an ad-hoc command to direct Ansible to connect to specific remote nodes, copy a module file there and execute it, and return output. You have a fully working infrastructure.

https://docs.ansible.com/ansible/2.9/user_guide/intro_inventory.html

这篇文章讲的是Ansible主机清单的一些基本用法

The default location for inventory is a file called /etc/ansible/hosts. You can specify a different inventory file at the command line using the -i <path> option. 

pull inventory from dynamic or cloud sources or different formats (YAML, ini, etc), as described in Working with dynamic inventory (即从CMDB、配管系统里通过API接口拿到)

The inventory file can be in one of many formats, depending on the inventory plugins you have. The most common formats are INI and YAML. A basic INI etc/ansible/hosts might look like this:

mail.example.com

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

[dbservers]
one.example.com
two.example.com
three.example.com

Here’s that same basic inventory file in YAML format:

all:
hosts:
    mail.example.com:
children:
    webservers:
    hosts:
        foo.example.com:
        bar.example.com:
    dbservers:
    hosts:
        one.example.com:
        two.example.com:
        three.example.com:

如果机器之间涉及比较复杂的层次关系,用YAML格式看起来稍微好点

Default groups

There are two default groups: all and ungrouped. The all group contains every host. The ungrouped group contains all hosts that don’t have another group aside from all. Every host will always belong to at least 2 groups (all and ungrouped or all and some other group). Though all and ungrouped are always present, they can be implicit and not appear in group listings like group_names.

  • 机器按照功能(角色)、机房、生产OR测试进行分类
  • Adding ranges of hosts

Adding variables to inventory

  • 机器级别变量
  • 分组级别变量
  • 独立的变量文件(host or group)

You can store variable values that relate to a specific host or group in inventory. To start with, you may add variables directly to the hosts and groups in your main inventory file. As you add more and more managed nodes to your Ansible inventory, however, you will likely want to store variables in separate host and group variable files.

Assigning a variable to one machine: host variables

You can easily assign a variable to a single host, then use it later in playbooks. In INI:

[atlanta]
host1 http_port=80 maxRequestsPerChild=808
host2 http_port=303 maxRequestsPerChild=909

[targets]
localhost              ansible_connection=local
other1.example.com     ansible_connection=ssh        ansible_user=myuser
other2.example.com     ansible_connection=ssh        ansible_user=myotheruser
badwolf.example.com:5309

如果在生产环境机器可能统一都是某个非22端口,此时可以配置Ansible所在机器的SSH客户端配置文件,统一改

Generally speaking, this is not the best way to define variables that describe your system policy. Setting variables in the main inventory file is only a shorthand. See Organizing host and group variables for guidelines on storing variable values in individual files in the ‘host_vars’ directory.

Assigning a variable to many machines: group variables

If all hosts in a group share a variable value, you can apply that variable to an entire group at once. In INI:

[atlanta]
host1
host2

[atlanta:vars]
ntp_server=ntp.atlanta.example.com
proxy=proxy.atlanta.example.com

In YAML:

atlanta:
hosts:
    host1:
    host2:
vars:
    ntp_server: ntp.atlanta.example.com
    proxy: proxy.atlanta.example.com

Group variables are a convenient way to apply variables to multiple hosts at once. Before executing, however, Ansible always flattens variables, including inventory variables, to the host level. If a host is a member of multiple groups, Ansible reads variable values from all of those groups. If you assign different values to the same variable in different groups, Ansible chooses which value to use based on internal rules for merging.

Inheriting variable values: group variables for groups of groups

[atlanta]
host1
host2

[raleigh]
host2
host3

[southeast:children]
atlanta
raleigh

[southeast:vars]
some_server=foo.southeast.example.com
halon_system_timeout=30
self_destruct_countdown=60
escape_pods=2

[usa:children]
southeast
northeast
southwest
northwest


In YAML:

all:
  children:
    usa:
      children:
        southeast:
          children:
            atlanta:
              hosts:
                host1:
                host2:
            raleigh:
              hosts:
                host2:
                host3:
          vars:
            some_server: foo.southeast.example.com
            halon_system_timeout: 30
            self_destruct_countdown: 60
            escape_pods: 2
        northeast:
        northwest:
        southwest:

Organizing host and group variables

Although you can store variables in the main inventory file, storing separate host and group variables files may help you organize your variable values more easily. Host and group variable files must use YAML syntax. Valid file extensions include ‘.yml’, ‘.yaml’, ‘.json’, or no file extension. See YAML Syntax if you are new to YAML.

https://docs.ansible.com/ansible/2.9/reference_appendices/YAMLSyntax.html#yaml-syntax

Ansible loads host and group variable files by searching paths relative to the inventory file or the playbook file

Keeping your inventory file and variables in a git repo (or other version control) is an excellent way to track changes to your inventory and host variables.

这块要注意路径问题,放错找不到变量

/etc/ansible/hosts
/etc/ansible/group_vars/raleigh # can optionally end in '.yml', '.yaml', or '.json'
/etc/ansible/group_vars/webservers
/etc/ansible/host_vars/foosball

How variables are merged

要是有变量继承覆盖的困惑,可以来着看看(最好有意避开这样的坑)

Using multiple inventory sources

You can target multiple inventory sources (directories, dynamic inventory scripts or files supported by inventory plugins) at the same time by giving multiple inventory parameters from the command line or by configuring ANSIBLE_INVENTORY. This can be useful when you want to target normally separate environments, like staging and production, at the same time for a specific action.

ansible-playbook get_logs.yml -i staging -i production

inventory/
  openstack.yml          # configure inventory plugin to get hosts from Openstack cloud
  dynamic-inventory.py   # add additional hosts with dynamic inventory script
  static-inventory       # add static hosts and groups
  group_vars/
    all.yml              # assign variables to all hosts

Connecting to hosts: behavioral inventory parameters

各种连接控制参数,如SSH的端口

ansible_host
ansible_port
ansible_user
ansible_password
ansible_become
ansible_become_user
ansible_shell_type
ansible_python_interpreter

Examples from an Ansible-INI host file:

some_host         ansible_port=2222     ansible_user=manager
aws_host          ansible_ssh_private_key_file=/home/example/.ssh/aws.pem
freebsd_host      ansible_python_interpreter=/usr/local/bin/python
ruby_module_host  ansible_ruby_interpreter=/usr/bin/ruby.1.9.3

Non-SSH connection types

这里介绍了Ansible直接部署资源到Docker中

- name: create jenkins container
  docker_container:
    docker_host: myserver.net:4243
    name: my_jenkins
    image: jenkins

- name: add container to inventory
  add_host:
    name: my_jenkins
    ansible_connection: docker
    ansible_docker_extra_args: "--tlsverify --tlscacert=/path/to/ca.pem --tlscert=/path/to/client-cert.pem --tlskey=/path/to/client-key.pem -H=tcp://myserver.net:4243"
    ansible_user: jenkins
  changed_when: false

- name: create directory for ssh keys
  delegate_to: my_jenkins
  file:
    path: "/var/jenkins_home/.ssh/jupiter"
    state: directory

Inventory setup examples

Example: One inventory per environment
[dbservers]
db01.test.example.com
db02.test.example.com

[appservers]
app01.test.example.com
app02.test.example.com
app03.test.example.com

Example: Group by function
- hosts: dbservers
  tasks:
  - name: allow access from 10.0.0.1
    iptables:
      chain: INPUT
      jump: ACCEPT
      source: 10.0.0.1

https://docs.ansible.com/ansible/2.9/user_guide/intro_dynamic_inventory.html

动态得到主机清单(如请求API得到)

If you would like a GUI for handling dynamic inventory, the Red Hat Ansible Tower inventory database syncs with all your dynamic inventory sources, provides web and REST access to the results, and offers a graphical inventory editor. With a database record of all of your hosts, you can correlate past event history and see which hosts have had failures on their last playbook runs.

图形界面操作主机清单

Using inventory directories and multiple inventory sources

If the location given to -i in Ansible is a directory (or as so configured in ansible.cfg), Ansible can use multiple inventory sources at the same time. When doing so, it is possible to mix both dynamic and statically managed inventory sources in the same ansible run. Instant hybrid cloud!

In an inventory directory, executable files will be treated as dynamic inventory sources and most other files as static sources. Files which end with any of the following will be ignored:

~, .orig, .bak, .ini, .cfg, .retry, .pyc, .pyo

Any group_vars and host_vars subdirectories in an inventory directory will be interpreted as expected, making inventory directories a powerful way to organize different sets of configurations. See Using multiple inventory sources for more information.

https://docs.ansible.com/ansible/2.9/dev_guide/developing_inventory.html#developing-inventory

https://docs.ansible.com/ansible/2.9/user_guide/intro_patterns.html

各种复杂,完善的机器匹配都都可以参考这里

Patterns: targeting hosts and groups

Patterns are highly flexible - you can exclude or require subsets of hosts, use wildcards or regular expressions, and more. Ansible executes on all inventory hosts included in the pattern.

wildcards 通配符

regular expressions 正则表达式

ansible <pattern> -m <module_name> -a "<module options>""
ansible webservers -m service -a "name=httpd state=restarted"

In a playbook the pattern is the content of the hosts: line for each play:

- name: <play_name>
hosts: <pattern>

- name: restart webservers
hosts: webservers

不在主机清单里的IP是无法用Ansible操作的

Limitations of patterns

Patterns depend on inventory. If a host or group is not listed in your inventory, you cannot use a pattern to target it. If your pattern includes an IP address or hostname that does not appear in your inventory, you will see an error like this:

This works even if the host you target is not defined in your inventory. You can also limit the hosts you target on a particular run with the –limit flag:

ansible-playbook site.yml –limit datacenter2

https://docs.ansible.com/ansible/2.9/user_guide/intro_adhoc.html