In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article is to share with you about configuration management and IT automation tool Ansible, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article. Let's take a look at it.
Today let's talk about ansible, a powerful configuration management solution written by Python. Although there are many configuration management solutions available on the market, they have their own advantages and disadvantages, and the characteristic of ansible lies in its simplicity. What makes ansible unique in mainstream configuration management systems is that it doesn't require you to install your own components on every node you want to configure. One of the advantages provided at the same time is that you can control your entire infrastructure in more than one place if necessary. The last point is its correctness, maybe there is some controversy here, but I think it can still be used as an advantage most of the time. Having said enough, let's start installing and configuring Ansible on RHEL/CentOS and Debian/Ubuntu-based systems.
Preparatory work
Release: RHEL/CentOS/Debian/Ubuntu Linux
A designer-friendly modern template language of Jinja2:Python
A YAML Encoding / Decoding function Library of PyYAML:Python
Paramiko: SSHv2 protocol function library written by pure Python.
Httplib2: a fully functional HTTP client function library
Most of the actions listed in this article have been assumed that you will perform as a root user in bash or any other modern shell.
How does Ansible work?
The Ansible tool does not use daemons, nor does it require any additional custom security architecture, so it can be said to be easy to deploy. All you need is the SSH client and server.
+-+
| | SSH with Ansible installed | File Server 1 | |
| | Linux/Unix workstation | | Database server 2 | locally or remotely |
+-+ module | proxy server 3 | data center
192.168.1.100+-+Unix/Linux server
Where:
192.168.1.100-install Ansible on your local workstation or server.
File server 1 to proxy server 3-use 192.168.1.100 and Ansible to automatically manage all servers.
SSH-set the SSH key between 192.168.1.100 and the local / remote server.
Ansible installation tutorial
Ansible is easy to install, and many distributions of third-party software repositories have off-the-shelf packages that can be installed directly. Other simple installation methods include installing it using pip, or getting the latest version from github. If you want to use your package manager installation, you will probably need an EPEL repository on RHEL/CentOS Linux-based systems.
Install ansible on a RHEL/CentOS Linux-based system
Enter the following yum command:
$sudo yum install ansible
Install ansible on a Debian/Ubuntu Linux-based system
Enter the following apt-get command:
$sudo apt-get install software-properties-common
$sudo apt-add-repository ppa:ansible/ansible
$sudo apt-get update
$sudo apt-get install ansible
Install ansible using pip
The pip command is a tool for installing and managing Python packages, such as those in Python Package Index. The following methods are common in Linux and Unix-like systems:
$sudo pip install ansible
Install the latest version of ansible from the source code
You can install the latest version from github with the following command:
$cd ~
$git clone git://github.com/ansible/ansible.git
$cd. / ansible
$source. / hacking/env-setup
When you run ansible from a git checkout, keep in mind that you need to set up your environment before using it every time, or you can add this setup process to your bash rc file:
# join BASH RC
$echo "export ANSIBLE_HOSTS=~/ansible_hosts" > > ~ / .bashrc
$echo "source ~ / ansible/hacking/env-setup" > > ~ / .bashrc
Ansible's hosts file includes a series of hosts it can operate. By default, ansible looks for hosts files through the path / etc/ansible/hosts, but this behavior can also be changed so that it is convenient when you want to operate on more than one ansible or for different customers in different data centers. You can specify the hosts file with the command line argument-I:
$ansible all-m shell-a "hostname"-- ask-pass-I / etc/some/other/dir/ansible_hosts
However, I prefer to use an environment variable, which can work when you want to source a different file to switch work goals. The environment variable here is $ANSIBLE_HOSTS, which can be set as follows:
$export ANSIBLE_HOSTS=~/ansible_hosts
Once all the required components have been installed and you have your hosts file ready, you can try it. For quick testing, I wrote 127.0.0.1 into ansible's hosts file here:
$echo "127.0.0.1" > ~ / ansible_hosts
Now let's test a simple ping:
$ansible all-m ping
Or prompt for the ssh password:
$ansible all-m ping-- ask-pass
There are several problems encountered in the initial setup, so it is highly recommended to set up SSH public key authentication for ansible. But in the test we just used-- ask-pass, on some machines you will need to install sshpass or specify-c paramiko like this:
$ansible all-m ping-- ask-pass-c paramiko
Of course, you can also install sshpass, but sshpass is not always available in standard repositories, so paramiko may be easier.
Set SSH public key authentication
So there is a configuration, as well as some basic other things. Now let's do something practical. The power of ansible is largely reflected in playbooks, which is basically written ansible scripts (for the most part), but before making a playbook, we'll start with some one-sentence scripts. Now let's create and configure SSH public key authentication to omit the-c and-- ask-pass options:
$ssh-keygen-t rsa
Sample output:
Generatingpublic/private rsa key pair.
Enter file in which to save the key (/ home/mike/.ssh/id_rsa):
Enter passphrase (empty forno passphrase):
Enter same passphrase again:
Your identification has been saved in/home/mike/.ssh/id_rsa.
Yourpublic key has been saved in/home/mike/.ssh/id_rsa.pub.
The key fingerprint is:
94:a0:19:02:ba:25:23:7f:ee:6c:fb:e8:38:b4:f2:42 mike@ultrabook.linuxdork.com
The key's randomart image is:
+-[RSA 2048]-+
|. . | |
|. . +. . | |
| =. O o |
|. *. | |
|. . . S |
| | E.O. |
|. .. | |
| o okeeper.. | |
| | + oclinic roomo. | |
+-+
There are obviously many ways to put it where it should be on the remote host. But since we are using ansible, let's use it to do this:
$ansible all-m copy-a "src=/home/mike/.ssh/id_rsa.pub dest=/tmp/id_rsa.pub"-- ask-pass-c paramiko
Sample output:
SSH password:
127.0.0.1 | success > > {
"changed": true
"dest": "/ tmp/id_rsa.pub"
"gid":
"group": "users"
"md5sum": "bafd3fce6b8a33cf1de415af432774b4"
"mode": "0644"
"owner": "mike"
Size: 410
"src": "/ home/mike/.ansible/tmp/ansible-tmp-1407008170.46-208759459189201/source"
"state": "file"
"uid": 1000
}
Next, add the public key file to the remote server. Enter:
$ansible all-m shell-a "cat / tmp/id_rsa.pub > > / root/.ssh/authorized_keys"-- ask-pass-c paramiko
Sample output:
SSH password:
127.0.0.1 | FAILED | rc=1 > >
/ bin/sh:/root/.ssh/authorized_keys:Permission denied
Short oil, you need to use root to execute this command, so add a-u parameter:
$ansible all-m shell-a "cat / tmp/id_rsa.pub > > / root/.ssh/authorized_keys"-- ask-pass-c paramiko-u root
Sample output:
SSH password:
127.0.0.1 | success | rc=0 > >
Note that this is intended to demonstrate the operation of transferring files through ansible. In fact, ansible has a more convenient built-in SSH key management support:
$ansible all-m authorized_key-a "user=mike key=' {{lookup ('file',' / home/mike/.ssh/id_rsa.pub')}} 'path=/home/mike/.ssh/authorized_keys manage_dir=no"-- ask-pass-c paramiko
Sample output:
SSH password:
127.0.0.1 | success > > {
"changed": true
"gid":
"group": "users"
"key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCq+Z8/usprXk0aCAPyP0TGylm2MKbmEsHePUOd7p5DO1QQTHak+9gwdoJJavy0yoUdi+C+autKjvuuS+vGb8+I+8mFNu5CvKiZzIpMjZvrZMhHRdNud7GuEanusTEJfi1pUd3NA2iXhl4a6S9a/4G2mKyf7QQSzI4Z5ddudUXd9yHmo9Yt48/ASOJLHIcYfSsswOm8ux1UnyeHqgpdIVONVFsKKuSNSvZBVl3bXzhkhjxz8RMiBGIubJDBuKwZqNSJkOlPWYN76btxMCDVm07O7vNChpf0cmWEfM3pXKPBq/UBxyG2MgoCGkIRGOtJ8UjC/daadBUuxg92/u01VNEB mike@ultrabook.linuxdork.com"
"key_options": null
"keyfile": "/ home/mike/.ssh/authorized_keys"
"manage_dir": false
"mode": "0600"
"owner": "mike"
"path": "/ home/mike/.ssh/authorized_keys"
Size: 410
"state": "file"
"uid": 1000
"unique": false
"user": "mike"
}
Now these keys have been set. Let's try to run a random command, such as hostname, hopefully we won't be prompted for a password
$ansible all-m shell-a "hostname"-u root
Sample output:
127.0.0.1 | success | rc=0 > >
Success! Now we can use root to execute the command without being disturbed by the prompt for a password. We can now easily configure any host in the ansible hosts file. Let's delete the public key file in / tmp:
$ansible all-m file-a "dest=/tmp/id_rsa.pub state=absent"-u root
Sample output:
127.0.0.1 | success > > {
"changed": true
"path": "/ tmp/id_rsa.pub"
"state": "absent"
}
Let's do something more complicated. I want to make sure that some packages are installed and are the latest versions:
$ansible all-m zypper-a "name=apache2 state=latest"-u root
Sample output:
127.0.0.1 | success > > {
"changed": false
"name": "apache2"
"state": "latest"
}
Well, the public key file we just put in / tmp has disappeared, and we've installed the latest version of apache. Let's take a look at-m zypper in the previous command, a feature that makes ansible very flexible and gives playbooks more power. If you don't use openSUSE or Suse enterprise, you may not be familiar with zypper, which is basically the equivalent of yum in the suse world. In all the above examples, there is only one machine in my hosts file. All but the last command should be used in any standard * nix system and standard ssh configuration, which creates a problem. What if we want to manage many different machines at the same time? This is where the configurability of playbooks and ansible sparkles. First, let's modify our hosts file a little bit:
$cat ~ / ansible_hosts
Sample output:
[RHELBased]
10.50.1.33
10.50.1.47
[SUSEBased]
127.0.0.1
First, we created some grouped servers and gave them some meaningful tags. Then let's create a playbook that performs different operations for different types of servers. You may have noticed that the data structure of this yaml is similar to the command line statement we ran earlier. Simply put,-m is a module, while-an is used to provide module parameters. In the YAML representation, you can specify the module first, then insert a colon:, and finally specify the parameters.
-
-hosts:SUSEBased
Remote_user: root
Tasks:
-zypper: name=apache2 state=latest
-hosts:RHELBased
Remote_user: root
Tasks:
-yum: name=httpd state=latest
Now that you have a simple playbook, you can run it like this:
$ansible-playbook testPlaybook.yaml-f 10
Sample output:
PLAY [SUSEBased] *
GATHERING FACTS *
Ok: [127.0.0.1]
TASK: [zypper name=apache2 state=latest] * *
Ok: [127.0.0.1]
PLAY [RHELBased] *
GATHERING FACTS *
Ok: [10.50.1.33]
Ok: [10.50.1.47]
TASK: [yum name=httpd state=latest] *
Changed: [10.50.1.33]
Changed: [10.50.1.47]
PLAY RECAP *
10.50.1.33: ok=2 changed=1 unreachable=0 failed=0
10.50.1.47: ok=2 changed=1 unreachable=0 failed=0
127.0.0.1: ok=2 changed=0 unreachable=0 failed=0
Notice that you will see the output of each machine contacted by ansible. The-f parameter allows ansible to run instructions on multiple hosts simultaneously. In addition to specifying all hosts, or the names of a host group, you can also transfer the import of ssh public keys from the command line to playbook, which will provide great convenience when setting up new hosts and even allow new hosts to run a playbook directly. To demonstrate, let's put our previous public key example into a playbook:
-
-hosts:SUSEBased
Remote_user: mike
Sudo: yes
Tasks:
-authorized_key: user=root key= "{{lookup ('file',' / home/mike/.ssh/id_rsa.pub')}}" path=/root/.ssh/authorized_keys manage_dir=no
-hosts:RHELBased
Remote_user: mdonlon
Sudo: yes
Tasks:
-authorized_key: user=root key= "{{lookup ('file',' / home/mike/.ssh/id_rsa.pub')}}" path=/root/.ssh/authorized_keys manage_dir=no
There are many other things that can be done, such as configuring the public key at startup, or introducing other processes that allow you to configure some machines as needed. However, as long as SSH is configured to accept password login, these can be used in almost all processes. Before you start writing too much playbook, another thing to consider is that code management can effectively save you time. The machine needs to be constantly changing, but you don't need to rewrite a playbook every time the machine changes, you just need to update the relevant parts and commit the changes. Another benefit associated with this is that, as I mentioned earlier, you can manage your entire infrastructure from different places. You just need to git clone your playbook repository to a new machine and complete the setup process for managing everything.
Real-life ansible examples
Many users often use services like pastebin, and many companies configure similar things for their internal use for obvious reasons. Recently, I came across a program called showterm, and coincidentally, I was asked by a customer to configure it for internal use. I'm not going to go into the details of the application here, but if you're interested, you can use Google to search for showterm. As a reasonable real-world example, I will try to configure a showterm server and configure the client applications needed to use it. We also need a database server in the process. Now let's start by configuring the client:
-
-hosts: showtermClients
Remote_user: root
Tasks:
-yum: name=rubygems state=latest
-yum: name=ruby-devel state=latest
-yum: name=gcc state=latest
-gem: name=showterm state=latest user_install=no
This part is very simple. Here is the primary server:
-
-hosts: showtermServers
Remote_user: root
Tasks:
-name:ensure packages are installed
Yum: name= {{item}} state=latest
With_items:
-postgresql
-postgresql-server
-postgresql-devel
-python-psycopg2
-git
-ruby21
-ruby21-passenger
-name: showterm server from github
Git: repo= https://github.com/ConradIrwin/showterm.io dest=/root/showterm
-name:Initdb
Command: service postgresql initdb
Creates=/var/lib/pgsql/data/postgresql.conf
-name:StartPostgreSQLand enable at boot
Service: name=postgresql
Enabled=yes
State=started
-gem: name=pg state=latest user_install=no
Handlers:
-name: restart postgresql
Service: name=postgresql state=restarted
-hosts: showtermServers
Remote_user: root
Sudo: yes
Sudo_user: postgres
Vars:
Dbname: showterm
Dbuser: showterm
Dbpassword: showtermpassword
Tasks:
-name: create db
Postgresql_db: name= {{dbname}}
-name: create user with ALL priv
Postgresql_user: db= {{dbname}} name= {{dbuser}} password= {{dbpassword}} priv=ALL
-hosts: showtermServers
Remote_user: root
Tasks:
-name: database.yml
Template: src=database.yml dest=/root/showterm/config/database.yml
-hosts: showtermServers
Remote_user: root
Tasks:
-name: run bundle install
Shell: bundle install
Args:
Chdir:/root/showterm
-hosts: showtermServers
Remote_user: root
Tasks:
-name: run rake db tasks
Shell:'bundle exec rake db:create db:migrate db:seed'
Args:
Chdir:/root/showterm
-hosts: showtermServers
Remote_user: root
Tasks:
-name: apache config
Template: src=showterm.conf dest=/etc/httpd/conf.d/showterm.conf
It's all right. Note that this is an arbitrary program in a sense, but we can now continuously deploy it on any number of machines, which is the benefit of configuration management. In addition, in most cases, the definition syntax here is almost self-evident, and the wiki page does not need to add too much detail. Of course, in my opinion, a wiki page with too many details is never a bad thing.
Extended configuration
We haven't covered all the details here. Ansible has many options for configuring your system. You can embed variables in your hosts file, and ansible will apply them to remote nodes. Such as:
[RHELBased]
10.50.1.33 http_port=443
10.50.1.47 http_port=80 ansible_ssh_user=mdonlon
[SUSEBased]
127.0.0.1 http_port=443
Although this is convenient for quick configuration, you can also divide variables into multiple files in yaml format. In your hosts file path, you can create two subdirectories, groupvars and hostvars. Any files placed in these paths, as long as they match the name of a host group, or a host name in your hosts file, will be inserted at run time. So the previous example will look like this:
Ultrabook:/etc/ansible # pwd
/ etc/ansible
Ultrabook:/etc/ansible # tree
.
├── group_vars
│├── RHELBased
│└── SUSEBased
├── hosts
└── host_vars
├── 10.50.1.33
└── 10.50.1.47
2 directories,5 files
Ultrabook:/etc/ansible # cat hosts
[RHELBased]
10.50.1.33
10.50.1.47
[SUSEBased]
127.0.0.1
Ultrabook:/etc/ansible # cat group_vars/RHELBased
Ultrabook:/etc/ansible # cat group_vars/SUSEBased
-
Http_port:443
Ultrabook:/etc/ansible # cat host_vars/10.50.1.33
-
Http_port:443
Ultrabook:/etc/ansible # cat host_vars/10.50.1.47
-
Http_port:80
Ansible_ssh_user: mdonlon
Improve Playbooks
There are also many ready-made ways to organize playbooks. In the previous example, we used a separate file, so this aspect has been greatly simplified. A common way to organize these files is to create roles. To put it simply, you load a master file as your playbook, and it will import all the data from other files, which are roles. For example, if you have a wordpress site, you need a web front end and a database. The web front end will include a web server, application code, and any required modules. Sometimes the database runs on the same host and sometimes on a remote host, so the role can come in handy. You create a directory and create a corresponding small playbook for each role. In this example we need an apache role, a mysql role, a wordpress role, a mod_php role, and a php role. The biggest advantage is that not every character has to be applied to the same machine. In this example, mysql can be applied to a single machine. This also makes it possible for code reuse, for example, your apache role can also be used in python and other similar php applications. Showing these is a bit beyond the scope of this article, and there are always many different ways to do one thing, I suggest searching for some playbook examples of ansible. There are a lot of people contributing code on github, and of course there are other sites.
Module
In ansible, the behind-the-scenes work is dominated by modules for all the work done. Ansible has a very rich repository of built-in modules, including package installation, file transfer, and everything we have done in this article. But for some people, these don't meet their configuration needs, and ansible also provides a way for you to add your own modules. The great thing about Ansible's API is that it doesn't restrict modules and must be written in Python, the language in which it is written, that is, you can write modules in any language. The Ansible module works by passing JSON data, so you only need to generate a piece of JSON data in the language you want. I'm pretty sure any scripting language can do this, so you can start writing something now. There is a lot of documentation on the Ansible website, including how the module interface works, and there are many examples of modules on Github. Note that some minority languages may not be well supported, but that may only be because not many people are contributing code in that language. Try to write something and publish your results.
Overall, although there are many solutions in configuration management, I hope this article will show the simple setup process of ansible, which in my opinion is one of its most important points. Please note that because I am trying to show different ways of doing something, not all of the previous examples are best practices for your individual environment or for general situations.
The above is how to use Ansible, a configuration management and IT automation tool. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
Dns parsing cache: ipconfig/ flushdns to view all ip:ipconfig/all
© 2024 shulou.com SLNews company. All rights reserved.