03_ansible inventory、Hosts and Groups、Host Variables、Group Variables、Default groups、Pattern

4.ansible inventory
4.1.Hosts and Groups
4.1.1.Case
4.2.Host Variables
4.3.Group Variables
4.4.Groups of Groups, and Group Variables
4.5.Default groups
4.6.Splitting Out Host and Group Specific Data
4.7.List of Behavioral Inventory Parameters
4.7.1. General all connections
4.7.2. Non-SSH connection type
5.Pattern

4.ansible inventory

Reposted from: https://www.cnblogs.com/mhc-fly/p/7080974.html

Multiple systems can be securely addressed in your infrastructure at the same time. It can be selected by selecting the system part listed in Ansible's inventory, which is stored in /etc/ansible/hosts by default. You can use -i on the command line option to specify additional inventory files.
This inventory can not only be configured, but also use multiple inventory files at the same time, and describe from dynamic inventory, extract inventory from dynamic or cloud sources. Introduced in version 2.4, Ansible has an inventory plugin that makes it flexible and customizable.

4.1.Hosts and Groups

The inventory file can be in one of many formats, depending on which inventory plugin you have. For this example, the format of /etc/ansible/hosts is an INI (similar to Ansible's default), as follows:

# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
#   - Comments begin with the '#' character
#   - Blank lines are ignored
#   - Groups of hosts are delimited by [header] elements
#   - You can enter hostnames or ip addresses
#   - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.

green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10

# 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

# 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

Headings in parentheses are group names and are used to classify systems and determine which systems you control when and for what purpose.
It is possible to put systems in multiple groups, for example the servers could be a webserver and a dbserver. If you do this, be aware that the variables will come from all groups they belong to. Variable priority is described in detail in later chapters.

If you have a host running on a non-standard SSH port, you can write the port number after the host name, separated by a colon. The ports listed in your SSH config file will not be used with paramiko connections, but will be used with openssh connections.

To make things unambiguous, it is recommended that you set this up if running on the default port:

badwolf.example.com:5309

Let's say you only have static IP and want to setup some alias that exists in your hosts file, or you are connecting through a tunnel. You can also describe the host like this:

badwolf.example.com:5309

In the example above, attempting to contact against the host alias "jumper" (which may not even be the real hostname) would contact 192.0.2.50 on port 5555. Note that this is using the functionality of the Inventory file to define some special variables. In general, this is not the best way to define variables that describe system policy, but we'll share advice on this later. We just started
adding a lot of hosts? If you have many hosts that follow a similar pattern, you can do this instead of listing each hostname:

[webservers]
www[01:50].example.com

For numeric patterns, leading zeros can be included or removed as desired. Ranges make inclusive you can also define alphabetic ranges:

[databases]
db-[a:f].example.com

Connection types and users can also be selected on a per-host basis:

[targets]
localhost              ansible_connection=local
other1.example.com     ansible_connection=ssh        ansible_user=mpdehaan
other2.example.com     ansible_connection=ssh        ansible_user=mdehaan

As mentioned above, setting these in the Inventory file is just a shorthand, we'll discuss how they are stored in individual files in the "host_vars" directory later.

4.1.1. Case

The configuration in /etc/ansible/hosts is as follows:

[webserver]
172.17.0[3:6]

Then execute:

[root@node2 ansible]# ansible webserver -m ping
172.17.05 | SUCCESS => {
    
    
    "ansible_facts": {
    
    
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
172.17.03 | SUCCESS => {
    
    
    "ansible_facts": {
    
    
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
172.17.04 | SUCCESS => {
    
    
    "ansible_facts": {
    
    
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
172.17.06 | SUCCESS => {
    
    
    "ansible_facts": {
    
    
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
[root@node2 ansible]#

4.2.Host Variables

As above, it's easy to assign variables to hosts that will be used later in the playbook:

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

4.3.Group Variables

Variables can also be applied to an entire group at once:

[atlanta]
host1
host2

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

Note that this is just a convenient way to apply variables to multiple hosts at once. Even though you can target hosts by group, variables are always flattened to the host level before playing.

4.4.Groups of Groups, and Group Variables

Groups can also be created using the :children suffix, as described above, you can apply :vars with :vars :

[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

See the next section if you need to store list or hash data, or if you want to keep host and group specific variables separate from the Inventory file. Subgroups have several properties to note:

  • First, any host that is a member of a child group is automatically a member of the parent group.
  • Second, the variables of the child group will have higher priority (override) the variables of the parent group.

4.5.Default groups

There are two default groups: all and ungrouped. all contains every host. ungrouped includes all hosts that have no other group than all hosts.

4.6.Splitting Out Host and Group Specific Data

The preferred practice in Ansible is not actually to store variables in the main Inventory file.
In addition to storing variables directly in the INI file, host and group variables can be stored in a single file relative to the Inventory file.
These variable files are in YAML format. Valid file extensions include '.yml', '.yaml', '.json' or no file extension. If you are new to YAML, see YAML syntax.
Assuming the inventory file path is:

/etc/ansible/hosts

If the host is named "foosball", and is in the "raleigh" and "webservers" groups, the variables in the YAML file at the following locations will be available to the host:

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

For example, suppose you have hosts grouped by datacenter, and each datacenter uses a few different servers. The data in the file "/etc/ansible/group_vars/raleigh" for the "releign" group might look like this:

ntp_server: acme.example.org
database_server: storage.example.org

It is fine if these files do not exist, as this is an optional feature.
As an advanced use case, you can create directories named after groups or hosts, and Ansible will read all files in those directories. An example of the "raleigh" group:

/etc/ansible/group_vars/raleigh/db_settings
/etc/ansible/group_vars/raleigh/cluster_settings

All hosts in the "raleigh" group will have the variables defined in these files. This can be useful when individual files start to get too large, or when you want to use Vault Safe as part of a group variable. Note that this only works with Ansible 1.4 or later.

Tip: In Ansible 1.2 or later, the group_vars/ and host_vars/ directories can exist in either the playbook directory or the inventory directory. If both paths exist, variables in the playbook directory will override variables set in the Inventory directory.

Tip: Keep track of Inventory variables and Inventory directories when keeping Inventory files and variables in a git repo (or other version control). If both paths exist, variables in the playbook directory will override variables set in the Inventory directory.

Tip: Keeping inventory files and variables in a git repo (or other version control) is an excellent way to keep track of inventory variables and host variables.

4.7.List of Behavioral Inventory Parameters

Setting the following variables controls how the remote host can be interacted with.

ansible_connection:
The type of connection to the host. This can be the name of any of Ansible's connection plugins. The SSH protocol type is smart, ssh or paramiko. The default is smart. Non-SSH based types are covered in the next section.

4.7.1. All connections in general

The name of the host that ansible_host
will connect to, if different from the alias to provide.
ansible_port
ssh port number, if not 22 the default ssh username to use for
ansible_user . Specific to SSH connections:

ansible_ssh_pass
The ssh password to use (Do not store this variable in plain text; always use Vault. See Variables and Vault)
ansible_ssh_private_key_file
Private key file to use for ssh. Useful if using multiple keys and you don't want to use an SSH agent.
ansible_ssh_common_args
This setting is always appended to the default command line for sftp, scp and ssh. There is ProxyCommand for configuring a specific host (or group).
ansible_sftp_extra_args
This setting is always appended to the default sftp command line.
ansible_scp_extra_args
This setting is always appended to the default scp command line.
ansible_ssh_extra_args
This setting is always appended to the default ssh command line.
ansible_ssh_pipelining
determines whether to use SSH pipelining. This can override the pipelining settings in ansible.cfg.
ansible_ssh_executable (added in version 2.2)
This setting overrides the default behavior of using system ssh. This can override the ssh_executable setting in ssh_executable.
Privilege Escalation (see Optional Privilege Escalation for details):

Ansible_BECOME
is equivalent to Ansible_Sudo or Ansible_SU, allowing forced privileges to upgrade
Ansible_BECOME_METHOD
to allow setting permissions to upgrade method
Ansible_Become_user
is equivalent to Ansible_Sudo_user or Ansible_SU_USER. , Allow settings to become a user who upgrades through privileges
Ansible_becomE_PASS
is equivalent to Ansible_sudo_pass or Ansible_su_Pass. You can set the permission upgrade password (never pure with pure This variable is stored as text; always use Vault), see Variables and Vault)
Remote host environment parameters:

ansible_shell_type
The shell type of the target system. This setting should not be used unless you have ansible_shell_executable set to a non-Bourne(sh) compatible shell. By default, commands are formatted using sh -style syntax. Setting this to csh or fish will cause commands executed on the target system to follow the syntax of those shells.
ansible_python_interpreter
target host python path. This is useful for systems that have multiple Pythons or are not in /usr/bin/python (like *BSD) or where /usr/bin/python is not a 2.X series Python. We do not use the /usr/bin/env mechanism, as this requires the remote user's path to be set correctly, and also assumes that the python executable is named python, where the executable might be named python2.6.
ansible_*_interpreter
works for anything like ruby ​​or perl, like ansible_python_interpreter. This will override the shebang for modules that will run on that host.
New features in version 2.1

ansible_shell_executable
This sets the shell the controller will use on the target machine, overriding executable in ansible.cfg which defaults to /bin/sh. You should only be able to change that if it is not possible to use /bin/sh (i.e. /bin/sh is not installed on the target machine or cannot be run from sudo).
Example from Ansible-INI hosts 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

4.7.2. Non-SSH connection types

The connection type can be changed using the host specific parameter ansible_connection=. The following non-SSH based connectors are available:

local
This connector can be used to deploy the playbook to the control machine itself.

The docker
connector inserts this playbook directly into a Docker container using a native Docker client. The following parameters are handled by this connector:

The name of the Docker container that ansible_host
will connect to.
The username for ansible_user
to operate inside the container. User must exist inside the container.
ansible_become
if set to true, will use become_user to operate inside the container.
ansible_docker_extra_args
can be a string of any additional arguments understood by Docker, they are not command-specific. This parameter is mainly used to configure the remote Docker daemon to use.
Here's an example of how to immediately deploy to the created container:

- 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

5.Pattern

In Ansible, Patterns refers to how we determine which host to manage. It means which host to interact with. But in :doc:playbooks it refers to the corresponding host application-specific configuration or execution of specific processes.

Let's review the command usage introduced in the chapter: doc:intro_adhoc. The command format is as follows:

ansible <pattern_goes_here> -m <module_name> -a <arguments>

Examples are as follows:

ansible  webservers  -m service -a “name=httpd state=restarted” 

A pattern is usually associated with a set of groups (a collection of hosts) - in the example above, all hosts are in the "webservers" group.

Anyway, before using Ansible, we need to tell Ansible in advance which machine will be executed. The premise of this is that unique host names or host groups need to be defined in advance.

The following patterns are equivalent to targeting all machines in the inventory:

all
*

It is also possible to write IP addresses or serial hostnames:

one.example.com
one.example.com: two.example.com
192.168.1.50
192.168.1.*

The following patterns represent one or more groups respectively. Multiple groups are separated by colons to represent or relationships. This means that a host can have multiple groups at the same time:

webservers
webservers: dbservers

You can also enqueue a specific group, in the following example, all machines executing the command must belong to the webservers group but not in the phoenix group at the same time:

webservers:!phoenix

You can also specify the intersection of the two groups, as shown in the following example, to execute the command, a machine needs to belong to both the webservers and staging groups.

webservers:&staging

You can also combine more complex conditions

webservers:dbservers:&staging:!phoenix

The above example means "the machines in the 'webservers' and 'dbservers' groups that belong to the 'staging' group and do not belong to the 'phoenix' group execute the command"

You can also use variables if you want to specify the group by passing parameters, ansible-playbook can achieve it through the "-e" parameter, but this usage is not commonly used:

webservers:!{
    
    {
    
    excluded}}:&{
    
    {
    
    required}}

You don't have to strictly define groups, single host names, IPs, groups all support wildcards:

*.example.com
*.com

Ansible also supports a mix of wildcards and groups:

one*.com:dbservers

In advanced syntax, you can also select the corresponding numbered server in the group:

webservers[0]

Or a subset of servers in a group:

webservers[0-25]

Most people use regular expressions in patterns, but you can. Just start with '~':

~(web|db).*\.example\.com

At the same time, let us understand some skills in advance. In addition to the above, you can also add exclusion conditions through the –limit flag. /usr/bin/ansible or /usr/bin/ansible-playbook both support:

ansible-playbook site.xml --limit datacenter2

If you want to read hosts from a file, prefix the file name with @. This feature is supported since Ansible 1.2:

ansible-playbook site.yml --limit @retry_hosts.txt

Guess you like

Origin blog.csdn.net/toto1297488504/article/details/132216429