ansible-乱

Working mechanism: ssh Clientless

Work:
. 1, the CMDB
2, public cloud private cloud the API
. 3, using AD-hoc
. 4, ansible-PlayBook
ansible Run underlying call transport connection module, a command or file transfer to the / tmp directory remote server, remote execution, after the delete operation and returns the result.

Profiles

/ etc / ansible functions; inventory Host Configuration Tool function
/ usr / bin series of commands default storage location
sequential read commands ansible:
the current directory ---- execute commands under the user's home directory .ansible.cfg ------ /etc/ansible.cfg, first find, first use

ansible CI


2) [privilege_escalation] sudo user privilege escalation
3)
4) [ssh_connection]
5) [accelerate]
6)] [selinux
7)] [colours

Public and private key
ssh-keygen -N "" -b 4096 -t rsa -C "" -f /root/.ssh/stanley.rsa
native adding authentication
ssh-copy-id -i /root/.ssh/stanley.rsa root @ localhost

ssh -i /root/.ssh/stanley.rsa root @ local
command format

ansible [options]

After executing the command status
Red: abnormal process, terminate the remaining tasks
green: After the execution of the target does not change the state of
orange: normal execution, the target state change
ansible-DOC
-LL list the modules
ping display shows
ansibl-PlayBook .yml
ansibl-Vault encryption profiles
inventory management is the main configuration file, the default stored in / etc / ansible / hosts
to use (the default is only one inventory is not required to specify the path
ansible -i / etc / ansible / hosts the Webs -m the ping
inventory may be in the other path use -i to specify the location
ansible all --list

Inventory Configuration
define a host group, and

192.168.22.1
ntp.magedu.com:2222
nfs.magedu.com

Packet #
[WebServ]
web1.magedu.com
Web all numbers between [10:20] .magedu.com 10-20

Host host variable definition defines the variables
[WebServ]
web1.magedu.com Http_port MaxRequestsPerChild = 808 = 801

 组变量
 [groupeservers]
 web1.magedu.com 
 web2.magedu.com
 [groupeservers:vars]
 ntp_server=ntp.magedu.com     组中所有主机的ntp_serve值
 com
 nfs_server=nfs.magedu.com
 com 

   定义组嵌套变量及组变量

[apache]
httpd1.magedu.com
httpd2.magedu.com
[nginx]
ngx1.magedu.com
ngx2.magedu.com
[webservers:children]
apache
nginx
[webservers:vars]
ntp_server=ntp.magedu.com

Multivariate

Inventory can be defined variables, also be defined in addition, a separate configuration file is stored in YAML to .yml .yaml .json suffix
or no suffix, to retrieve from the following location:
Inventory default configuration file / etc / ansible / the hosts
the Playbook in vars defined domains
Roles vars directory file
Roles same directory group_vars hosts_vars directory file

priority:

DINGY

Regular expressions
use for inventory in the host list
ansible -m -a
Webserver for matching
ansible webservers -m service -a "name = httpd state = restart"
the total amount of matching
ansible -m All of ping
ans- " " -M of ping
ans- 192.168.1.
-M of ping
logical or OR match
ans- "web1: web2 "-m ping
logical not!
webservers:! phoenix (webservers all hosts in the group but not phonenix)
logic and
webservers: & phoenix 2 groups exist

Multi condition combination
webservers: dbservers: & staging:! Phoenix webservers, dbservers all the hosts in the absence and in the staging presence phoenix

Fuzzy matching

  • 0 or more arbitrary characters
    .magedu.com
    One
    .magedu.com
    domain cutting
    STR = '123456'
    Print STR [0:. 1]
    Examples:
    [webservers]
    web1
    web2
    Web3
    webservers [0] # web1
    webservers [-1] Web3
    webservers [0:. 1] #webservers [0] webservers [. 1]
    webservers [. 1:] webservers [. 1] webservers [2] web2 Web3
    regular matching a regular matching ~ start
    ~ (web | db) * example.com ..

    years- ~ 192.168. [0-9] {\ 2}. [0-9] {2} -m ping

Qualified Host make changes
ansible app -m command -a "service ntpd status" --limit "192.168.36.3"

ansible 192.168.36.1 -m command -a "service ntpd status"

 playbook 正式运行前使用  --check 或 -C 检测playbook改变哪些内容
 ansible-playbook   --check 
   ansible-playbook       xxxx.yml    --limit    webserver    限定webserver组
   

inventory 内置参数
General for all connections:
ansible_host
The name of the host to connect to, if different from the alias you wish to give to it.
ansible_port
The ssh port number, if not 22
ansible_user
The default ssh user name to use.

    Specific to the SSH connection:
    
    ansible_host
    The name of the host to connect to, if different from the alias you wish to give to it.
    ansible_port
    The ssh port number, if not 22
    ansible_user
    The default ssh user name to use.
    Specific to the SSH connection:

    ansible_ssh_pass
    The ssh password to use (never store this variable in plain text; always use a vault. See Variables and Vaults)
    ansible_ssh_private_key_file
    Private key file used by ssh. Useful if using multiple keys and you don’t want to use SSH agent.
    ansible_ssh_common_args
    
    playbook    语法检测
    ansible-play    nginx.yml   --syntax-check
                                           --list-hosts

ansible test70 -m blockinfile -a 'path = / testdir / rc.local block = "systemctl start mariadb \ nsystemctl start httpd"' is inserted into the end of line 2
effects:

BEGIN ANSIBLE MANAGED BLOCK

systemctl start mariadb
systemctl start httpd

BEGIN ANSIBLE MANAGED BLOCK

Custom tag
ansible test70 blockinfile -m -a '= path / the testdir / Block the rc.local = "Start systemctl MariaDB \ nsystemctl Start the httpd" marker = "# Serivce} to {Start Mark"'
ansible test70 blockinfile -a -m ' path = / testdir / rc.local block = "systemctl start mariadb" marker = "# {mark} serivce to start" ' statement updates the block

ansible test70 -m blockinfile -a 'path=/testdir/rc.local block="" marker="#{mark} serivce to start" ' 删除内容
ansible test70 -m blockinfile -a 'path=/testdir/rc.local  marker="#{mark} serivce to start" state=absent' 删除内容
ansible test70 -m blockinfile -a 'path=/testdir/rc.local block="####blockinfile test####"  marker="#{mark} test reg" insertafter="^#!/bin/bash" ' 指定位置插入

lineinfile, ensure that the specified text in a row.

Be sure to specify a line of text exists in the file, if the specified text exists, do not do the operation, otherwise the file is added at the end of
ansible test70 -m lineinfile -a 'path = / testdir / test line = "test text"'
based on regular expressions Alternatively a row, if there are many rows match, only the last match line will be replaced, is replaced by the specified text, if there is no match to give any row, line is added to the last row
ansible test70 -m lineinfile -a 'path = / testdir / test regexp = " ^ line" line = "test text" '

The regular expression replace a row, if there are many rows match, only the last match line will be replaced, is replaced by the specified text, if there is no match to give any row is not operating
ansible test70 -m lineinfile -a 'path = / testdir / test regexp = " ^ line" line = "test text" backrefs = yes'
matched lines deleted
ansible test70 -m lineinfile -a 'path = / testdir / test line = "lineinfile -" state = absent'
according to the regular expression matching, and delete
ansible test70 -m lineinfile -a 'path = / testdir / test regexp = "^ lineinfile" state = absent'
after opening to reference matching
ansible test70 -m lineinfile -a 'path = / testdir / test regexp = "(H. {4 }). * (H. {4})" line = "\ 2" backrefs = yes'

Definition of a variable
variable names consist of alphanumeric, underscores, variable names beginning with the letter, the built-in keywords as variable names can not

Variable priority

Document definition variable priority greater than the variable in the playbook hosts

definition;

- the hosts: test70
  VARS:
    testvar1: # testfile defined
  REMOTE_USER: the root
  Tasks:
  - name: Task1
    File:
      path: / the testdir / {{}} # testvar1 reference
      state: touch
defining a plurality of variables:
VARS:
  testvar1: testfile
  testvar2: Testfile2

yaml syntax definition
VARS:
  - testvar1: testfile
  - testvar2: Testfile2

To define property values

- hosts: test70
  remote_user: root
  vars:
    nginx:
      conf80: /etc/nginx/conf.d/80.conf
      conf8080: /etc/nginx/conf.d/8080.conf
  tasks:
  - name: task1
    file:
      path: "{{nginx.conf80}}" #或者 "{{nginx['conf8080']}}" 引用
      state: touch
  - name: task2
    file:
      path: "{{nginx.conf8080}}"
      state: touch

Use double quotes when referencing a variable, in the beginning at the reference position.
path: / testdir / {{testvar1 }} is not in double quotation marks at the beginning can not
be assigned equal sign, no quote
---
- the hosts: test70
  REMOTE_USER: the root
  VARS:
    Nginx:
      conf80: /etc/nginx/conf.d /80.conf
      conf8080: /etc/nginx/conf.d/8080.conf
  Tasks:
  - name: Task1
    File:
      path nginx.conf80 = {{}}
      State = Touch
  - name: Task2
    File:
      path Nginx = {{[ 'conf8080']}}
      State = Touch

Define variables in a separate file and application file name nginx_vars.yml do not need to define variables vars keywords in the file, defined directly.

An example syntax:
  testvar1: testfile
  testvar2: Testfile2
Syntax two examples:
  - testvar1: testfile
  - testvar2: Testfile2
Syntax three examples:
Nginx:
  conf80: /etc/nginx/conf.d/80.conf
  conf8080: / etc / Nginx / the conf .d / 8080.conf
references
---
- the hosts: test70
  REMOTE_USER: the root
  vars_files:
  - /testdir/ansible/nginx_vars.yml
  Tasks:
  - name: Task1
    File:
      path nginx.conf80 = {{}}
      State = Touch
  - name : Task2
    File:
      path = {{Nginx [ 'conf8080']}}
      State = Touch

May refer to multiple files,
VARS and vars_files can be used simultaneously
  VARS:
  - conf90: /etc/nginx/conf.d/90.conf
  vars_files:
  - /testdir/ansible/nginx_vars.yml

Information (a lot of information ansible test70 -m setup display collected

Use the keywords you want to view information
ansible test70 -m setup -a 'filter = ansible_memory_mb'
wildcard filter
ansible test70 Setup -a -m "filter = mb "
information is written in a custom remote host

在远程主机 /etc/ansible/facts.d/testinfo.fact 写入信息
[root@test70 facts.d]# cat testinfo.fact
[testmsg]
msg1=This is the first custom test message
msg2=This is the second custom test message
json格式
{
   "testmsg":{
       "msg1":"This is the first custom test message",
       "msg2":"This is the second custom test message"
   }
}

调用
ansible test70 -m setup -a "filter=ansible_local"

Find the remote host /etc/ansible/facts.d default directory, if the local tacts information into another directory, you specify the
ansible test70 -m setup -a 'fact_path = / testdir'

debug module

- hosts: test70
  REMOTE_USER: root
  Tasks:
  - name: Touch testfile
    File:
      path: / testdir / testfile
      State: Touch
  - name: Debug Demo
    Debug:
      msg: the this IS Debug info, the Test File has been at The Touched
after performing console output
debug module output and variable information custom
---
- the hosts: test70
  REMOTE_USER: the root
  VARS:
    testvar from: Test value of variable
  Tasks:
  - name: Demo debug
    debug:
      var: testvar from


- the hosts: test70
  REMOTE_USER: the root
  VARS:
    testvar from: testv
  Tasks:
  - name: Demo Debug
    Debug:
      MSG: "IS value of testvar from: {{}} testvar from" Variables front #MSG references cited are: the need to use ""

Obtain host information memory

- hosts: test70
  remote_user: root
  tasks:
  - name: debug demo
    debug:
      msg: "Remote host memory information: {{ansible_memory_mb}}"

An example syntax:
Debug:
     MSG: "the Remote Host Memory Information: ansible_memory_mb.real {} {}"
Syntax two examples:
Debug:
     MSG: "the Remote Host Memory Information: {{ansible_memory_mb [ 'Real']}}"
both syntax previously has been an example, not repeat them here.

Register variables:
returns the value of the runtime module, the default is not displayed (using -vvvv shown), which may be written to the tag extracted by the reference


- hosts: test70
  remote_user: root
  tasks:
  - name: test shell
    shell: "echo test > /var/testshellfile"
    register: testvar #注册变量
  - name: shell module return values
    debug:
      var: testvar # 引用

The value returned
changed: [192.168.36.73] => {
"changed": to true,
"cmd": "echo test1> / Data / testfile",
"Delta": "0: 00: 00.002276",
"End": " 2019-04-2318: 30: 31.285899 "
can obtain its value, by way of the specified Key;
syntax a
  - name: the shell Module1 return values
    Debug:
      MSG:" {{}} testvar.cmd "
syntax two
  - name: return values Module1 the shell
    Debug:
      MSG: "{{testvar from [ 'cmd']}}"
return value meaning documents: https://docs.ansible.com/ansible/2.4/shell_module.html
prompts the user to enter information:
---
- hosts: test70
  REMOTE_USER: root
  vars_prompt:
    - name: "your_name"
      prompt: "the What IS your name"
# default input is not displayed; you want to display
private: no
    - name: "your_age"
      prompt: "How old are you"
  tasks:
   - name: output vars
     debug:
      msg: Your name is {{your_name}},You are {{your_age}} years old.

Set default values ​​for the message

- the hosts: test70
  REMOTE_USER: the root
  vars_prompt:
    - name: "Solution"
      prompt: "the Choose The Solution you want \ n-
      A: solutionA \ n-
      B: solutionB \ n-
      C: solutionC \ n-"
      Private: NO
      default: A
  Tasks:
   - name: the Output VARS
     Debug:
      msg: at the Final Solution Solution IS {{}}.
script: create a user account after a password (required for password encryption, use passlib library, python user can confirm password


- hosts: test70
  remote_user: root
  vars_prompt:
    - name: "user_name"
      prompt: "Enter user name"
      private: no
    - name: "user_password"
      prompt: "Enter user password"
      encrypt: "sha512_crypt"
      confirm: yes
  tasks:
   - name: create user
     user:
      name: "{{user_name}}"
      password: "{{user_password}}"

Variable passed through the command line

playbook undefined variables can be referenced directly by passing command line
ansible-playbook cmdvar.yml --extra-vars " pass_var = cmdline pass var" # incoming variable length
ansible-playbook cmdvar.yml -e 'pass_var = " test "pass_var1 =" test1 " 'short variable
if the variable is not defined, nor pass variables, will complain, you can add a default variable in the playbook playbo


- hosts: test70
  remote_user: root
  vars:
    pass_var: test_default
  tasks:
  - name: "Passing Variables On The Command Line"
    debug:
      msg: "{{pass_var}}"

Adding host variable list, the host range is limited to a variable corresponding host
test70 ansible_host = 10.1.1.70 testhostvar = test70_host_var applications. Use testhostvar} {} {
YAML configuration syntax
All:
 the hosts:
   test70:
     ansible_host: 10.1.1.70
     ansible_port: 22 is
     testhostvar: test70_host_var
     testhostvar1: test70_host_var1

Host group variable

[testB]
test70 ansible_host=10.1.1.70
test71 anisble_host=10.1.1.71
 
[testB:vars]
test_group_var1='group var test'
test_group_var2='group var test2'

YAML
all:
 children:
   testB:
     hosts:
       test70:
         ansible_host: 10.1.1.70
         ansible_port: 22
       test71:
         ansible_host: 10.1.1.71
         ansible_port: 22
     vars:
       test_group_var1: 'group var test1'
       test_group_var2: 'group var test2'

By set_fact defined variables

The value of a variable can be imparted by set_fact another variable, the following example

- hosts: test70
  remote_user: root
  vars:
    testvar1: test1_string
  tasks:
  - shell: "echo test2_string"
    register: shellreturn
  - set_fact:
      testsf1: "{{testvar1}}"
      testsf2: "{{shellreturn.stdout}}"
  - debug:
      msg: "{{testsf1}} {{testsf2}}"

http://www----zsythink.net/archives/2698 finally there do not know how
built-in variables

All -m -a Debug ansible "MSG = {{}} ansible_version"
of hostvars
inventory_hostname current host name is operated, the corresponding host name in the list,
inventory_hostname_short, hostname shorter
all hosts play_hosts current play list operated
groups host information packet for each packet, and a separate host is not a packet
of GROUP_NAMES
inventory_dir


uncomment this to disable SSH key host checking

71 #host_key_checking = False the first time check key uncommented, the default answer yes

In performing sudo, sudo need to enter a password, use -K
the chrony synchronization PlayBook
Server 0.centos.pool.ntp.org iBurst

allow 192.168.0.0/16

local stratum 10

Scheduled Tasks

Do not enter confirm password visudo NOPASSWORD: ALL

All the ping -u -m Yon ansible -K -b
-u -u using the current default user (ie, user control terminal used)
enable logging log_path
ansible 'appservers:! webservers' -m the ping
ansible command-line options

Modify ansible default module -m shell default shell execution

Create a user's home directory, but does not generate a home directory file
document classification placement, yaml and configuration files

Variable priorities Variable File> playbook> -e> hosts host variables> hosts public variables

The role of cross-references, from roles / httpd / files / xxxx.index.html

The role of the default path

Guess you like

Origin www.cnblogs.com/g2thend/p/11621328.html