项目作者: dholdaway

项目描述 :
Ansible refresh
高级语言: Shell
项目地址: git://github.com/dholdaway/ansible.git
创建时间: 2017-01-09T22:59:42Z
项目社区:https://github.com/dholdaway/ansible

开源协议:

下载


Ansible refresh

Version 0.1

Table of Contents

Install Vagrant

Install Ruby

Getting Started

Install Ansible

Ansible Config

Ansible Commands

Ansible Command Sheet (merge me with commands above)

Other Notes


Install Vagrant


install vagrant

  1. vagrant -v

Vagrant 1.9.1

  1. ruby -v

ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14]

you need version 2.2.+ of ruby for the vagrant-hostmanager


Install Ruby 2.2.+


  1. brew install rbenv ruby-build
  2. rbenv install 2.2.2
  3. rbenv global 2.2.2
  4. echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile

Getting Started:


  1. clone me
  2. vagrant plugin install vagrant-hostmanager
  3. vagrant up
  4. vagrant ssh

    This should put you at the control host
    with access, by name, to other vms
    See Topology.pdf for network layout.


Install Ansible ( work in progress and is installed via vagrant up so can be skipped)


Install Ansible and everything needed: ( Centos )

  1. yum install -y epel-release -y
  2. yum update
  3. yum install git python python-devel python-pip openssl ansible -y

Check if it works:

  1. ansible --version

Ansible Config


Change config file:

  1. vim /etc/ansible/ansible.cfg

uncomment

  1. inventory = /etc/ansible/hosts
  2. sudo_user = root

Setup hosts file:

  1. mv /etc/ansible/hosts /etc/ansible/hosts.org
  2. vim /etc/ansible/hosts
  1. [local]
  2. localhost
  3. [<host group>]
  4. <ip or fqdn of host>
  5. [<host group>]
  6. <ip or fqdn of host>
  7. <ip or fqdn of host>`

Setup Ansible user:

  1. adduser ansible
  2. passwd ansible
  3. visudo
  1. ansible ALL=(ALL) NOPASSWD: ALL

Setup SSH_Keys from Ansible server

  1. su - ansible
  2. ssh-keygen
  3. ssh-copy-id localhost
  4. ssh-copy-id <host name>

The best way to get Ansible for Ubuntu is to add the project’s PPA (personal package archive) to your system.

To do this effectively, we need to install the software-properties-common package, which will give us the ability to work with PPAs easily. (This package was called python-software-properties on older versions of Ubuntu.)

  1. sudo apt-get update
  2. sudo apt-get install software-properties-common

Once the package is installed, we can add the Ansible PPA by typing the following command:

  1. sudo apt-add-repository ppa:ansible/ansible

Press ENTER to accept the PPA addition.

Next, we need to refresh our system’s package index so that it is aware of the packages available in the PPA. Afterwards, we can install the software:

  1. sudo apt-get update
  2. sudo apt-get install ansible

We now have all of the software required to administer our servers through Ansible

check that version 2.2+ is installed

  1. ansible --version

ansible 2.2.0.0


Commands


(ansible) (group or host) (sudo) (arbitrary) (command)

  1. ansible app -s -a "service apache2 restart"

runs ping against all hosts

  1. ansible all -m ping

Under the “facts” directory will be a file for each host in GROUP

  1. ansible [GROUP] -m setup --tree "facts

installs the latest telnet package

  1. ansible app -s -m apt -a "name=telnet state=latest"

Command Sheet ( merge me with commands above)


Ansible options:
-s = sudo
-m = module
-a ““= action/command

User Modules:

  • ping
  • copy
  • apt and/or yum
  • user

Run ping on all hosts:

  1. ansible all -m ping

Run ls -al on all hosts:

  1. ansible all -a "ls -al"

Run command as root:

  1. ansible all -s -a "cat /var/log/messages"

Copy file from local to host:

  1. ansible <host group1> -m copy -a "src=<filenaam> dest=</folder/file>"

Install latest version of a package:

  1. ansible <host group> -s -m yum/apt -a "name=elinks state=latest"

Remove a package:

  1. ansible <host group> -s -m yum/apt -a "name=elinks state=absent"
  2. ansible webserver -s -m apt -a "name=nginx state=absent"
  1. app02 | SUCCESS => {
  2. "changed": true,
  3. "stderr": "",
  4. "stdout": "Reading package lists...\nBuilding dependency tree...\nReading state information...\nThe following packages were automatically installed and are no longer required:\n libxslt1.1 nginx-common nginx-core\nUse 'apt-get autoremove' to remove them.\nThe following packages will be REMOVED:\n nginx\n0 upgraded, 0 newly installed, 1 to remove and 156 not upgraded.\nAfter this operation, 96.3 kB disk space will be freed.\n(Reading database ... 65250 files and directories currently installed.)\nRemoving nginx (1.4.6-1ubuntu3.7) ...\n",
  5. "stdout_lines": [
  6. "Reading package lists...",
  7. "Building dependency tree...",
  8. "Reading state information...",
  9. "The following packages were automatically installed and are no longer required:",
  10. " libxslt1.1 nginx-common nginx-core",
  11. "Use 'apt-get autoremove' to remove them.",
  12. "The following packages will be REMOVED:",
  13. " nginx",
  14. "0 upgraded, 0 newly installed, 1 to remove and 156 not upgraded.",
  15. "After this operation, 96.3 kB disk space will be freed.",
  16. "(Reading database ... 65250 files and directories currently installed.)",
  17. "Removing nginx (1.4.6-1ubuntu3.7) ..."
  18. ]
  19. }
  20. app01 | SUCCESS => {
  21. "changed": true,
  22. "stderr": "",
  23. "stdout": "Reading package lists...\nBuilding dependency tree...\nReading state information...\nThe following packages were automatically installed and are no longer required:\n libxslt1.1 nginx-common nginx-core\nUse 'apt-get autoremove' to remove them.\nThe following packages will be REMOVED:\n nginx\n0 upgraded, 0 newly installed, 1 to remove and 156 not upgraded.\nAfter this operation, 96.3 kB disk space will be freed.\n(Reading database ... 65250 files and directories currently installed.)\nRemoving nginx (1.4.6-1ubuntu3.7) ...\n",
  24. "stdout_lines": [
  25. "Reading package lists...",
  26. "Building dependency tree...",
  27. "Reading state information...",
  28. "The following packages were automatically installed and are no longer required:",
  29. " libxslt1.1 nginx-common nginx-core",
  30. "Use 'apt-get autoremove' to remove them.",
  31. "The following packages will be REMOVED:",
  32. " nginx",
  33. "0 upgraded, 0 newly installed, 1 to remove and 156 not upgraded.",
  34. "After this operation, 96.3 kB disk space will be freed.",
  35. "(Reading database ... 65250 files and directories currently installed.)",
  36. "Removing nginx (1.4.6-1ubuntu3.7) ..."
  37. ]
  38. }

Add user:

  1. ansible <host group> -s -m user -a "name=test"

Remove user without home dir:

  1. ansible <host group> -s -m user -a "name=test state=absent"

Deploying From Source Control Deploy your webapp straight from git:

  1. ansible webservers -m git -a "repo=git://foo.example.org/repo.git dest=/srv/myapp version=HEAD"

Since Ansible modules can notify change handlers it is possible to tell Ansible to run specific tasks when the code is updated, such as deploying Perl/Python/PHP/Ruby directly from git and then restarting apache.

Managing Services
Ensure a service is started on all webservers:

  1. ansible webservers -m service -a "name=httpd state=started"

Alternatively, restart a service on all webservers:

  1. ansible webservers -m service -a "name=httpd state=restarted"

Ensure a service is stopped:

  1. ansible webservers -m service -a "name=httpd state=stopped"

using LIMIT on a playbook run to host

  1. ansible-playbook site.yml --limit app01

Using TAGS

list

  1. ansible-playbook site.yml --list-tags
  1. playbook: site.yml
  2. play #1 (all): all TAGS: []
  3. TASK TAGS: []
  4. play #2 (control): control TAGS: []
  5. TASK TAGS: [{{ 'packages' }}]
  6. play #3 (database): database TAGS: []
  7. TASK TAGS: []
  8. play #4 (webserver): webserver TAGS: []
  9. TASK TAGS: []
  10. play #5 (loadbalancer): loadbalancer TAGS: []
  11. TASK TAGS: []

skip

  1. ansible-playbook site.yml --skip-tags "packages"

do

  1. ansible-playbook site.yml --tags "package"

using Limit and tags

  1. ansible-playbook site.yml --limit lb01 --tags "configure"
  1. PLAY [all] *********************************************************************
  2. TASK [setup] *******************************************************************
  3. ok: [lb01]
  4. PLAY [loadbalancer] ************************************************************
  5. TASK [nginx : configure nginx sites] *******************************************
  6. ok: [lb01] => (item={'key': u'myapp', 'value': {u'frontend': 80, u'backend': 80}})
  7. TASK [nginx : get active sites] ************************************************
  8. ok: [lb01]
  9. TASK [nginx : de-activate sites] ***********************************************
  10. skipping: [lb01] => (item=myapp)
  11. TASK [nginx : activate nginx sites] ********************************************
  12. ok: [lb01] => (item={'key': u'myapp', 'value': {u'frontend': 80, u'backend': 80}})
  13. PLAY RECAP *********************************************************************
  14. lb01 : ok=4 changed=0 unreachable=0 failed=0

Playbooks


run playbook

  1. ansible-playbook <locationofplaybook.yaml>

Example playbook (Update System)

  1. ---
  2. - hosts: local
  3. tasks:
  4. - name: Upgrade all packages to the latest version
  5. apt:
  6. update_cache: yes
  7. upgrade: yes
  8. - name: Remove useless packages from the cache
  9. apt:
  10. autoclean: yes
  11. - name: Remove dependencies that are no longer required
  12. apt:
  13. autoremove: yes
  14. ...

Example playbook
installs curl on control host using sudo

  1. ---
  2. - hosts: control
  3. become: true
  4. tasks:
  5. - name: install tools
  6. apt: name={{item}} state=present update_cache=yes
  7. with_items:
  8. - curl

Example playbook with items
installs a number of web items

  1. ---
  2. - hosts: webserver
  3. become: true
  4. tasks:
  5. - name: install web components
  6. apt: name={{item}} state=present update_cache=yes
  7. with_items:
  8. - apache2
  9. - libapache2-mod-wsgi
  10. - python-pip
  11. - python-virtualenv
  12. - python-mysqldb

Example playbook with wait for

  1. ---
  2. - hosts: loadbalancer
  3. become: true
  4. tasks:
  5. - name: verify nginx service
  6. command: service nginx status
  7. - name: verify nginx is listening on 80
  8. wait_for: port=80 timeout=1

Gathering Facts with Filter inside a Playbook

But you can disable the default behavior and call setup yourself with the filter parameter.

  1. - hosts: all
  2. sudo: yes
  3. gather_facts: False
  4. tasks:
  5. - setup:
  6. filter: ansible_*

Since you’re working on a role and might not want to have this setup call in your role, you could make use of pre_tasks.

  1. - hosts: all
  2. sudo: yes
  3. gather_facts: False
  4. pre_tasks:
  5. - setup:
  6. filter: ansible_*
  7. roles:
  8. - your_role_here

playbook using Selective Removal: shell, register, with_items, when

  1. ---
  2. - name: install tools
  3. apt: name={{item}} state=present update_cache=yes
  4. with_items:
  5. - python-httplib2
  6. - name: install nginx
  7. apt: name=nginx state=present update_cache=yes
  8. - name: configure nginx sites
  9. template: src=nginx.conf.j2 dest=/etc/nginx/sites-available/{{ item.key }} mode=0644
  10. with_dict: "{{ sites }}"
  11. notify: restart nginx
  12. - name: get active sites
  13. shell: ls -1 /etc/nginx/sites-enabled
  14. register: active
  15. - name: de-activate sites
  16. file: path=/etc/nginx/sites-enabled/{{ item }} state=absent
  17. with_items: active.stdout_lines
  18. when: item not in sites
  19. notify: restart nginx
  20. - name: activate nginx sites
  21. file: src=/etc/nginx/sites-available/{{ item.key }} dest=/etc/nginx/sites-enabled/{{ item.key }} state=link
  22. with_dict: " {{ sites }}"
  23. notify: restart nginx
  24. - name: ensure nginx started
  25. service: name=nginx state=started enabled=yes

Roles


Roles are a way to reuse functionality by putting all of the logic for a particular use case in the same place. As an example if you have tasks that you might run on all servers regardless of what the server is used for, that logic might be put in a role called “common.”

And if you have logic to configure a web server, then you may have another role named “webserver.” And whenever you need to install a new web application, you can include these two roles in your playbook.

ansible-galaxy init

Roles have a directory structure like this:

  1. rolename
  2. - files
  3. - handlers
  4. - meta
  5. - templates
  6. - tasks
  7. - vars

Within each directory, Ansible will search for and read any Yaml file called main.yml automatically.


Vault


  1. ansible-vault create <name>

type a password

create a yml file

  1. ---
  2. vault_db_pass: <any string>
  1. ansible-vault edit vault

enter password to open file

ERROR! Decryption failed on /vagrant/group_vars/all/vault

  1. ansible-playbook XXX.yml --ask-vault-pass

or

  1. echo "password" > ~/.vault_pass.txt
  2. chmod 0600 !$

and stash it in the ansible.cfg

  1. [defaults]
  2. inventory = ./dev
  3. vault_password_file = ~/.vault_pass.txt
  1. ansible-vault -h
  1. Usage: ansible-vault [create|decrypt|edit|encrypt|rekey] \
  2. [--help] [options] file_name
  3. Options:
  4. -h, --help show this help message and exit

For the most part, we’ll use ansible-vault create|edit /path/to/file.yml. Here, however, are all of the available commands:

create - Create a new file and encrypt it
decrypt - Create a plaintext file from an encrypted file
edit - Edit an already-existing encrypted file
encrypt - Encrypt an existing plain-text file
rekey - Set a new password on a encrypted file


Troubleshooting Ansible


ansible to prompt and ask us which steps to run

  1. ansible-playbook site.yml --step
  1. PLAY [all] *********************************************************************
  2. Perform task: TASK: setup (N)o/(y)es/(c)ontinue: y
  1. ansible-playbook site.yml --start-at-task "activate nginx sites"
  1. PLAY [all] *********************************************************************
  2. PLAY [control] *****************************************************************
  3. PLAY [database] ****************************************************************
  4. PLAY [webserver] ***************************************************************
  5. PLAY [loadbalancer] ************************************************************
  6. TASK [nginx : activate nginx sites] ********************************************
  7. ok: [lb01] => (item={'key': u'myapp', 'value': {u'frontend': 80, u'backend': 80}})
  8. TASK [nginx : ensure nginx started] ********************************************
  9. ok: [lb01]
  10. PLAY RECAP *********************************************************************
  11. lb01 : ok=2 changed=0 unreachable=0 failed=0

if a host fails ansible generates a limit file for you to re-run.

  1. ansible-playbook site.yml --limit @xxx.retry

check syntax of yml file

  1. ansible-playbook --syntax-check site.yml

Dry Run

  1. ansible-playbook --check site.yml

note that not all modules are support, plus it wont gather facts

debugging

ansible has a debug module

this is our task

  1. - name: get active sites
  2. shell: ls -1 /etc/nginx/sites-enabled
  3. register: active
  4. changed_when: "active.stdout_lines != sites.keys()"
  5. tags: [ 'configure' ]
  6. - debug: var=active.stdout_lines
  1. ansible-playbook site.yml --limit lb01 --start-at-task "get active sites"
  1. PLAY [all] *********************************************************************
  2. PLAY [loadbalancer] ************************************************************
  3. TASK [nginx : get active sites] ************************************************
  4. ok: [lb01]
  5. TASK [nginx : debug] ***********************************************************
  6. ok: [lb01] => {
  7. "active.stdout_lines": [
  8. "myapp"
  9. ]
  10. }
  11. TASK [nginx : de-activate sites] ***********************************************
  12. skipping: [lb01] => (item=myapp)
  13. TASK [nginx : activate nginx sites] ********************************************
  14. ok: [lb01] => (item={'key': u'myapp', 'value': {u'frontend': 80, u'backend': 80}})
  15. TASK [nginx : ensure nginx started] ********************************************
  16. ok: [lb01]
  17. PLAY RECAP *********************************************************************
  18. lb01 : ok=4 changed=0 unreachable=0 failed=0
  • debug: var=vars

is also useful for printing all the vars within the role.


Other notes


Variable Precedence: Where Should I Put A Variable?

  1. In 2.x, we have made the order of precedence more specific (with the last listed variables winning prioritization):
  2. role defaults [1]
  3. inventory vars [2]
  4. inventory group_vars
  5. inventory host_vars
  6. playbook group_vars
  7. playbook host_vars
  8. host facts
  9. play vars
  10. play vars_prompt
  11. play vars_files
  12. registered vars
  13. set_facts
  14. role and include vars
  15. block vars (only for tasks in block)
  16. task vars (only for the task)
  17. extra vars (always win precedence)
  18. Basically, anything that goes into role defaults (the defaults folder inside the role) is the most malleable and easily overridden. Anything in the vars directory of the role overrides previous versions of that variable in namespace. The idea here to follow is that the more explicit you get in scope, the more precedence it takes with command line -e extra vars always winning. Host and/or inventory variables can win over role defaults, but not explicit includes like the vars directory or an include_vars task.

Return code with ansible command
When you run a ansible command you have a return code like

  1. rc=0 it's if true
  2. rc=1 it's if false

Which syntax would loop through and render the elements of the list variable “backends” in a Jinja2 template?

  1. {% for server in backends %} {{ server }} {% endfor %}

For loop is in ‘{%’, ends with ‘endfor’ and the variable is rendered with ‘{{‘

one error on ansible 2.2.0.0 register.stdout_lines format. Incorrect syntax:

  1. with_items: active.stdout_lines

Correct syntax:

  1. with_items: "{‌{active.stdout_lines}}"

How could you define a variable value and be absolutely sure that it would not be overridden anywhere else by Ansible?

  1. Pass the variable using the `-e` or `--extra-vars`parameter when running `ansible-playbook`.

What ad-hoc command would you run to determine the facts available for a server?

  1. ansible -m setup

The “setup” module will query all facts on a host and return them.

to time the how long a playbook takes

  1. time ansible-playbook <playbook>
  1. real 0m9.064s
  2. user 0m2.771s
  3. sys 0m1.263s

this is useful for optimisation

Templates

Templates at their core are a way to copy files to a remote server. However the difference between templates and static files is that templates will be processed before they’re copied to the remote host. And this allows you to include variables, conditionals, loops, etc. Ansible uses Jinja2 as its template engine.

Handlers

Handlers are basically tasks that are run when some event happens. As an example if you change a web server’s configuration file, you’ll need to restart the web server service. This is an ideal use case for handlers.


Playbooks Database (its probably already been written)


https://galaxy.ansible.com/



https://www.vagrantup.com

https://www.vagrantup.com/downloads.html

https://github.com/devopsgroup-io/vagrant-hostmanager

https://github.com/willthames/ansible-lint

https://atom.io/packages/linter-ansible-linting

http://erikzaadi.com/2015/11/15/linting-ansible-yaml-in-vim/

http://docs.ansible.com/ansible/index.html

http://docs.ansible.com/ansible/playbooks.html

http://docs.ansible.com/ansible/playbooks_best_practices.html <— READ ME

https://github.com/ansible/ansible-examples

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

http://docs.ansible.com/ansible/intro_adhoc.html#managing-packages

https://docs.ansible.com/ansible/playbooks_variables.html

https://liquidat.wordpress.com/2016/01/26/howto-introduction-to-ansible-variables/

http://stackoverflow.com/questions/22522985/how-can-i-write-variables-inside-the-tasks-file-in-ansible

http://stackoverflow.com/questions/30662069/how-can-i-pass-variable-to-ansible-playbook-in-the-command-line

http://docs.ansible.com/ansible/playbooks_loops.html#looping-over-hashes

https://docs.ansible.com/ansible/playbooks_vault.html



https://docs.ansible.com/ansible/uri_module.html

http://sgargan.blogspot.co.uk/2013/10/troubleshooting-ssh-connections-in.html

http://stackoverflow.com/questions/37425078/ansible-failed-to-connect-to-the-host-via-ssh-error

http://stackoverflow.com/questions/37213551/ansible-ssh-connection-fail