Ansible Series (1): Basic Configuration and Use

Posted by cmack on Fri, 24 May 2019 00:10:30 +0200

Contents of this article:
1.1 Installation of Ansible
1.2 Configure Ansible
  1.2.1 Environment Configuration
  1.2.2 SSH Mutual Trust Configuration
  1.2.3 Simple Test
1.3 inventory

Ansible is a batch, automatic deployment tool, which can not only batch, but also automatically. It mainly communicates based on ssh, and does not require the client (controlled end) to install ansible.

1.1 Installation of Ansible

There are many ways to install, you can download the source code, compile and install it, you can get the resource installation from git, you can also install the rpm package. RPM installation requires epel source configuration.

cat <<eof>>/etc/yum.repos.d/my.repo
[epel]
name=epel
baseurl=http://mirrors.aliyun.com/epel/7Server/x86_64/
enable=1
gpgcheck=0
eof

The environment used in the next few articles.

Host description IP address host name operating system
ansible6_server1 192.168.100.150 server1.longshuai.com CentOS 6.6
ansible6_node1 192.168.100.59 node1.longshuai.com CentOS 6.6
ansible6_node2 192.168.100.60 node2.longshuai.com CentOS 6.6
ansible6_node3 192.168.100.61 node3.longshuai.com CentOS 6.6
ansible7_server2 192.168.100.62 server2.longshuai.com CentOS 7.2
ansible7_node1 192.168.100.63 anode1.longshuai.com CentOS 7.2
ansible7_node2 192.168.100.64 anode2.longshuai.com CentOS 7.2
ansible7_node3 192.168.100.65 anode3.longshuai.com CentOS 7.2

After many tests, installing ansible version 2.3 on CentOS 6 may be very slow, requiring the results of ansible execution to be saved to a file using redirection or the - t option, and the next execution will be faster.

shell> yum -y install ansible
/etc/ansible/ansible.cfg
/etc/ansible/hosts
/etc/ansible/roles
/usr/bin/ansible
/usr/bin/ansible-2
/usr/bin/ansible-2.6
/usr/bin/ansible-connection
/usr/bin/ansible-console
/usr/bin/ansible-console-2
/usr/bin/ansible-console-2.6
/usr/bin/ansible-doc
/usr/bin/ansible-doc-2
/usr/bin/ansible-doc-2.6
/usr/bin/ansible-galaxy
/usr/bin/ansible-galaxy-2
/usr/bin/ansible-galaxy-2.6
/usr/bin/ansible-playbook
/usr/bin/ansible-playbook-2
/usr/bin/ansible-playbook-2.6
/usr/bin/ansible-pull
/usr/bin/ansible-pull-2
/usr/bin/ansible-pull-2.6
/usr/bin/ansible-vault
/usr/bin/ansible-vault-2
/usr/bin/ansible-vault-2.6

Use ansible-doc to list relevant help.

ansible-doc -h
Usage: ansible-doc [options] [module...]

Options:
  -a, --all             Show documentation for all modules
  -h, --help            show this help message and exit
  -l, --list            List available modules
  -M MODULE_PATH, --module-path=MODULE_PATH
                        specify path(s) to module library (default=None)
  -s, --snippet         Show playbook snippet for specified module(s)
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)
  --version             show program's version number and exit

The "-l" option is used to list the modules of ansible, which is usually filtered in combination with grep. For example, find out the available modules related to yum.

ansible-doc -l | grep yum
yum                                Manages packages with the `yum' package manager   
yum_repository                     Add or remove YUM repositories

Then use the "-s" option to get help with the use of the specified module. For example, get the usage syntax of the yum module.

ansible-doc -s yum
- name: Manages packages with the `yum' package manager
  action: yum
      conf_file           # The remote yum configuration file to use for the transaction.
      disable_gpg_check   # Whether to disable the GPG checking of signatures of packages being  
                            installed. Has an effect only if state is `present' or  `latest'.
      disablerepo         # `Repoid' of repositories to disable for the install/update operation. 
                            These repos will not persist beyond the transaction. When specifying 
                            multiple repos, separate them with a ",".
      enablerepo          # `Repoid' of repositories to enable for the install/update operation. 
                            These repos will not persist beyond the transaction. When specifying 
                            multiple repos, separate them with a ",".
      exclude             # Package name(s) to exclude when state=present, or latest
      installroot         # Specifies an alternative installroot, relative to which all packages
                            will be installed.
      list                # Package name to run the equivalent of yum list <package> against.
      name=               # Package name, or package specifier with version, like `name-1.0'. 
                            When using state=latest, this can be '*' which means run: yum -y update.
                            You can also pass a url or a local path to a rpm file(using state=present).
                            To operate on several packages this can accept a comma separated list of
                            packages or (as of 2.0) a list of packages.
      skip_broken         # Resolve depsolve problems by removing packages that are causing problems
                            from the trans‐ action.
      state               # Whether to install (`present' or `installed', `latest'), or remove 
                            (`absent' or `removed') a package.
      update_cache        # Force yum to check if cache is out of date and redownload if needed. Has
                            an effect only if state is `present' or `latest'.
      validate_certs      # This only applies if using a https url as the source of the rpm.
                            e.g. for localinstall. If set to `no', the SSL certificates will not be 
                            validated. This should only set to `no' used on personally controlled 
                            sites using self-signed certificates as it avoids verifying the source 
                            site. Prior to 2.1 the code worked as if this was set to `yes'.

For example, use yum to install UNIX DOS packages.

ansible 192.168.100.60 -m yum -a "name=unix2dos state=present"

192.168.100.60 is a machine remotely controlled by ansible, i.e. to install UNIX DOS on this machine. The next section describes how to specify the host to be controlled. "-m" specifies the module name, and "-a" specifies module parameters for the module, such as name and state.

For the ansible command options and the use of each module, see: Ansible Series (2): Options and Common Modules.

1.2 Configure ansible

1.2.1 Environment Configuration

Ansible configuration stores configuration data in ini format. Almost all configurations in Ansible can be reassigned through Playbook or environment variables of Ansible. When running the Ansible command, the command will look for the configuration file in the following order.

  • ANSIBLE_CONFIG: First, the Ansible command checks the environment variable and the configuration file that the environment variable points to.
  • . / ansible.cfg: Second, the ansible.cfg configuration file in the current directory will be checked.
  • ~/ ansible.cfg: Again, the. ansible.cfg configuration file in the current user home directory will be checked.
  • / etc/ansible/ansible.cfg: Finally, the configuration files generated automatically when installing Ansible with the package management tool will be checked.

1. Configuration using context variables

Most Ansible parameters can be configured by setting environment variables with the beginning of ANSIBLE_and parameter names must be capital letters, as follows:

export ANSIBLE_SUDO_USER=root

After setting the environment variable, ANSIBLE_SUDO_USER can be directly referenced in subsequent operations.

2. Setting ansible.cfg configuration parameters

Ansible has many configuration parameters. Here are some default configuration parameters:

inventory = /root/ansible/hosts
library = /usr/share/my_modules/
forks = 5
sudo_user = root
remote_port = 22
host_key_checking = False
timeout = 20
log_path = /var/log/ansible.log

Inventory: This parameter represents the location of the inventory file, and the inventory is a list of hosts that Ansible needs to connect to for management.
Library: All operations of Ansible are implemented using modules, and the library parameter refers to the directory where the Ansible module is stored.
forks: Set how many processes Ansible can work at the same time by default, and five processes are processed in parallel by default. The number of specific settings can be determined according to the performance of the control end and the number of managed nodes.
sudo_user: Set the default user to execute the command, or reset this parameter in playbook.
remote_port: Specifies the management port to connect the managed node, default is 22, unless a special SSH port is set, there is no need to modify this parameter.
host_key_checking: Sets whether to check the SSH host's key. You can set it to True or False. That is, the host of SSH verifies again.
Timeout: Sets the timeout interval for SSH connections in seconds.
Log_path: Ansible does not log by default. If you want to record the output of the Ansible system in the log file, you need to set log_path. It is important to note that the module will call (r)syslog of the managed node to record. Users who execute Ansible need to have the right to write to the log.

1.2.2 SSH Mutual Trust Configuration

The ssh public key of ansible server is distributed to each managed node.

On ansible 6_server 1 and ansible_server 2:

ssh-keygen -t rsa -f ~/.ssh/id_rsa -N ''
ssh-copy-id root@192.168.100.59
ssh-copy-id root@192.168.100.60
ssh-copy-id root@192.168.100.61
ssh-copy-id root@192.168.100.62
ssh-copy-id root@192.168.100.63
ssh-copy-id root@192.168.100.64
ssh-copy-id root@192.168.100.65
ssh-copy-id root@192.168.100.150

Ansible itself can also be used to add keys to the controlled nodes in batches. Use the authorized_key module of ansible. See the introduction of common modules later.

Following is a non-interactive ssh-copy-id implementation with expect tools, so as not to always ask for the login password of remote users.

# Install expect
[root@server2 ~]# yum -y install expect

# expect script
[root@server2 ~]# cat auto_sshcopyid.exp 
#!/usr/bin/expect

set timeout 10
set user_hostname [lindex $argv 0]
set password [lindex $argv 1]

spawn ssh-copy-id $user_hostname
expect {
        "(yes/no)?"
        {
                send "yes\n"
                expect "*password: " { send "$password\n" }
        }
        "*password: " { send "$password\n" }
}

expect eof

# shell script for bulk calling expect
[root@server2 ~]# cat sshkey.sh 
#!/bin/bash

ip=`echo -n "$(seq -s "," 59 65),150" | xargs -d "," -i echo 192.168.100.{}`
password="123456"
#user_host=`awk '{print $3}' /root/.ssh/id_rsa.pub`

for i in $ip;do
        /root/auto_sshcopyid.exp root@$i $password &>>/tmp/a.log
        ssh root@$i "echo $i ok"
done

# Executing shell scripts to configure mutual trust
[root@server2 ~]# chmod +x /root/{sshkey.sh,auto_sshcopyid.exp}
[root@server2 ~]# ./sshkey.sh

1.2.3 Simple Test

Add a list of managed nodes to the default inventory file / etc/ansible/hosts.

On ansible 6_server 1:

cat >>/etc/ansible/hosts<<eof
192.168.100.59
192.168.100.60
192.168.100.61
192.168.100.62
192.168.100.63
192.168.100.64
192.168.100.65
[centos6]
192.168.100.59
192.168.100.60
192.168.100.61
[centos7]
192.168.100.63
192.168.100.64
192.168.100.65
[centos:children]
centos6
centos7
eof

On ansible 7_server 2:

cat >>/etc/ansible/hosts<<eof
192.168.100.150
192.168.100.59
192.168.100.60
192.168.100.61
192.168.100.63
192.168.100.64
192.168.100.65
[centos6]
192.168.100.59
192.168.100.60
192.168.100.61
[centos7]
192.168.100.63
192.168.100.64
192.168.100.65
[centos:children]
centos6
centos7
eof

Use ping module to test managed nodes. The success shows that ansible can control the node.

ansible 192.168.100.59 -m ping
ansible centos6 -m ping
192.168.100.59 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.100.60 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.100.61 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

If you want to specify that a non-root user runs the ansible command, add "-sudo" or "-s" to increase the privileges of the user specified by the sudo_user configuration item.

ansible webservers -m ping -u ansible --sudo

Or use becom to elevate permissions.

ansible webservers -m ping -b --become-user=root --become-method=sudo

1.3 inventory

Inventory is used to define the list of hosts to be managed by ansible. It defines a single host and a host group. The above / etc/ansible/hosts is the default inventory. The following shows the commonly used definition rules for inventory.

cat -n /etc/ansible/hosts
1 192.168.100.59:22
2 192.168.100.60 ansible_ssh_pass='123456'
3 [nginx]
4 192.168.100.5[7:9]
5 [nginx:vars]
6 ansible_ssh_pass='123456'
7 [webservers:children]
8 nginx

The first line and the second line define the host separately. The first line carries the port connecting the managed node, and the second line carries the parameter passed to ssh separately. This parameter is the password parameter of the logged-in remote user when ssh is connected.
The third and fourth lines define the nginx host group, which contains 192.168.100.57 to 59 hosts.
Lines 5 and 6 define the variables to be passed to the nginx host group.
The seventh and eighth lines define a new host group, webservers, whose members are nginx groups.

You can specify multiple inventory configuration files, just set the inventory instruction to the corresponding file or directory in the ansible configuration file such as / etc/ansible/ansible.cfg. If it is a directory, then all files in this directory are inventory files.

Some built-in variables can be used in the inventory file, where most ansible connection and privilege variables can be used. ansible command interpretation.

inventory_hostname is a variable that can be used in ansible, which represents the name of each host in inventory. For example, "192.168.100.59". This is the first variable currently encountered.

 

Back to the outline of the series: http://www.cnblogs.com/f-ck-need-u/p/7048359.html

For reprinting, please indicate the source: http://www.cnblogs.com/f-ck-need-u/p/7553186.html

Note: If you think this article is not bad, please click on the recommendation in the lower right corner. With your support, the author will be more enthusiastic about writing. Thank you very much.

Topics: Linux ansible ssh yum CentOS