Wednesday 19 March 2014

ansible note1

Most Imp:

You need to have the "ssh-agent bash" and "ssh-add private_key(s)" first.

Edit (or create) /etc/ansible/hosts and put one or more remote systems in it, for which you have your SSH key in authorized_keys:
192.168.1.50
aserver.example.org
bserver.example.org


$ ssh-agent bash
$ ssh-add ~/.ssh/id_rsa


$ ansible all -m ping

# as bruce, sudoing to batman
$ ansible all -m ping -u bruce --sudo --sudo-user batman

It is ok to put systems in more than one group, for instance a server could be both a webserver and a dbserver.

If you have hosts that run on non-standard SSH ports you can put the port number after the hostname with a colon. Ports listed in your SSH config file won’t be used, so it is important that you set them if things are not running on the default port:

badwolf.example.com:5309

Suppose you have just static IPs and want to set up some aliases that don’t live in your host file, or you are connecting through tunnels. You can do things like this:

jumper ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50



######### Example of /etc/ansible/hosts file: #############

cat /etc/ansible/hosts
# 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

[group1]
host1 ansible_ssh_host=host1.example.com ansible_ssh_port=port ansible_ssh_user=user


# 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
#127.0.0.1

######### Notes #########

sudo nano /etc/ansible/hosts

[group_name]
alias ansible_ssh_host=server_ip_address

[droplets]
host1 ansible_ssh_host=111.111.111.111
host2 ansible_ssh_host=222.222.222.222
host3 ansible_ssh_host=333.333.333.333


We can put our configuration in here. YAML files start with "---", so make sure you don't forget that part.

ansible -m ping all

ansible -m ping droplets

host1:1717 ansible_ssh_user=ubuntu
host2:1717 ansible_ssh_user=ubuntu


[somegroup]
foo ansible_ssh_port=1234
bar ansible_ssh_port=1235


amit@amitAsus:~$ ansible -m ping group1
host1 | success >> {
    "changed": false, 
    "ping": "pong"
}

host2| success >> {
    "changed": false, 
    "ping": "pong"
}


- hosts: h1:h2
  user: admin
  tasks:
  - name: update package list
    action: command /usr/bin/apt-get update
  - name: upgrade packages
    action: command /usr/bin/apt-get -u -y dist-upgrade
- hosts: h3
  user: sysadmin
  tasks:
  - name: update package list
    action: command /usr/bin/apt-get update
  - name: upgrade packages
    action: command /usr/bin/apt-get -u -y dist-upgrade 
    
NOTE: you can add as many ssh-key if you want:
1. ssh-agent bash
2. ssh-add /data/aws-keys/one-private-key
3. ssh-add /data/aws-keys/another-private-key

For multiple host group:  [group1:group2]

amit@amitAsus:~$ ansible -m ping group1:group2


we could also specify an individual host:

ansible -m ping host1

We can specify multiple hosts by separating them with colons:

ansible -m ping host1:host2


###
The -m ping portion of the command is an instruction to Ansible to use the "ping" module. These are basically commands that you can run on your remote hosts. The ping module operates in many ways like the normal ping utility in Linux, but instead it checks for Ansible connectivity.



The ping module doesn't really take any arguments, but we can try another command to see how that works. We pass arguments into a script by typing -a.

The "shell" module lets us send a terminal command to the remote host and retrieve the results. For instance, to find out the memory usage on our host1 machine, we could use:

ansible -m shell -a 'free -m' host1



## If you started an ansible command and did a ^C its process will be there on the system as following:

amit     17178  0.0  0.0  45716  2972 ?        S    15:35   0:00 ssh -tt -q -o ControlMaster=auto -o ControlPersist=60s -o ControlPath=/home/amit/.ansible/cp/ansible-ssh-%h-%p-%r -o Port=1717 -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=user -o ConnectTimeout=10 host2.example.com /bin/sh -c 'mkdir -p $HOME/.ansible/tmp/ansible-1395223494.41-7224770274317 && chmod a+rx $HOME/.ansible/tmp/ansible-1395223494.41-7224770274317 && echo $HOME/.ansible/tmp/ansible-1395223494.41-7224770274317'


## 
[droplets]
host1 ansible_ssh_host=111.111.111.111
host2 ansible_ssh_host=222.222.222.222
host3 ansible_ssh_host=333.333.333.333

we can use alias of host too then:


amit@amitAsus:~/test$ ansible
ansible           ansible-doc       ansible-galaxy    ansible-playbook  ansible-pull
amit@amitAsus:~/test$ ansible-doc 
Usage: ansible-doc [options] [module...]

Show Ansible module documentation

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -M MODULE_PATH, --module-path=MODULE_PATH
                        Ansible modules/ directory
  -l, --list            List available modules
  -s, --snippet         Show playbook snippet for specified module(s)
  -v                    Show version number and exit

amit@amitAsus:~/test$ ansible-doc -l
accelerate           Enable accelerated mode on remote node                      
acl                  Sets and retrieves file ACL information.                    
add_host             add a host (and alternatively a group) to the ansible-playbo
airbrake_deployment  Notify airbrake about app deployments                       
apt                  Manages apt-packages                                        
apt_key              Add or remove an apt key                                    
apt_repository       Add and remove APT repositores                              
arista_interface     Manage physical Ethernet interfaces                         
arista_l2interface   Manage layer 2 interfaces                                   
arista_lag           Manage port channel (lag) interfaces                        
arista_vlan          Manage VLAN resources                                       
assemble             Assembles a configuration file from fragments               
async_status         Obtain status of asynchronous task                          
authorized_key       Adds or removes an SSH authorized key                       
bigip_monitor_http   Manages F5 BIG-IP LTM http monitors                         
bigip_monitor_tcp    Manages F5 BIG-IP LTM tcp monitors                          
bigip_node           Manages F5 BIG-IP LTM nodes                                 
bigip_pool           Manages F5 BIG-IP LTM pools                                 
bigip_pool_member    Manages F5 BIG-IP LTM pool members                          
boundary_meter       Manage boundary meters                                      
bzr                  Deploy software (or files) from bzr branches                
campfire             Send a message to Campfire                                  
cloudformation       create a AWS CloudFormation stack                           
command              Executes a command on a remote node                         
copy                 Copies files to remote locations.                           
cron                 Manage cron.d and crontab entries.                          
datadog_event        Posts events to DataDog  service                            
debug                Print statements during execution                           
digital_ocean        Create/delete a droplet/SSH_key in DigitalOcean             
django_manage        Manages a Django application.                               
dnsmadeeasy          Interface with dnsmadeeasy.com (a DNS hosting service).     
docker               manage docker containers                                    
easy_install         Installs Python libraries                                   
ec2                  create or terminate an instance in ec2, return instanceid...
ec2_ami              create or destroy an image in ec2, return imageid           
ec2_eip              associate an EC2 elastic IP with an instance.               
ec2_elb              De-registers or registers instances from EC2 EL*s*          
ec2_facts            Gathers facts about remote hosts within ec2 (aws)           
ec2_group            maintain an ec2 VPC security group.                         
ec2_tag              create and remove tag(s) to ec2 resources.                  
ec2_vol              create and attach a volume, return volume id and device map.
ec2_vpc              configure AWS virtual private clouds                        
ejabberd_user        Manages users for ejabberd servers                          
elasticache          Manage cache clusters in Amazon Elasticache. - Returns infor
facter               Runs the discovery program `facter' on the remote system... 
fail                 Fail with custom message                                    
fetch                Fetches a file from remote nodes                            
file                 Sets attributes of files                                    
filesystem           Makes file system on block device                           
fireball             Enable fireball mode on remote node                         
firewalld            Manage arbitrary ports/services with firewalld              
flowdock             Send a message to a flowdock                                
gc_storage           This module manages objects/buckets in Google Cloud Storage.
gce                  create or terminate GCE instances                           
gce_lb               create/destroy GCE load-balancer resources                  
gce_net              create/destroy GCE networks and firewall rules              
gce_pd               utilize GCE persistent disk resources                       
gem                  Manage Ruby gems                                            
get_url              Downloads files from HTTP, HTTPS, or FTP to node            
git                  Deploy software (or files) from git checkouts               
github_hooks         Manages github service hooks.                               
glance_image         Add/Delete images from glance                               
group                Add or remove groups                                        
group_by             Create Ansible groups based on facts                        
grove                Sends a notification to a grove.io channel                  
hg                   Manages Mercurial (hg) repositories.                        
hipchat              Send a message to hipchat                                   
homebrew             Package manager for Homebrew                                
hostname             Manage hostname                                             
htpasswd             manage user files for basic authentication                  
include_vars         Load variables from files, dynamically within a task.       
ini_file             Tweak settings in INI files                                 
irc                  Send a message to an IRC channel                            
jabber               Send a message to jabber user or chat room                  
jboss                deploy applications to JBoss                                
kernel_blacklist     Blacklist kernel modules                                    
keystone_user        Manage OpenStack Identity (keystone) users, tenants and role
lineinfile           Ensure a particular line is in a file, or replace an existin
linode               create / delete / stop / restart an instance in Linode Publi
lvg                  Configure LVM volume groups                                 
lvol                 Configure LVM logical volumes                               
macports             Package manager for MacPorts                                
mail                 Send an email                                               
modprobe             Add or remove kernel modules                                
mongodb_user         Adds or removes a user from a MongoDB database.             
monit                Manage the state of a program monitored via Monit           
mount                Control active and configured mount points                  
mqtt                 Publish a message on an MQTT topic for the IoT              
mysql_db             Add or remove MySQL databases from a remote host.           
mysql_replication    Manage MySQL replication                                    
mysql_user           Adds or removes a user from a MySQL database.               
mysql_variables      Manage MySQL global variables                               
nagios               Perform common tasks in Nagios related to downtime and notif
netscaler            Manages Citrix NetScaler entities                           
newrelic_deployment  Notify newrelic about app deployments                       
nova_compute         Create/Delete VMs from OpenStack                            
nova_keypair         Add/Delete key pair from nova                               
npm                  Manage node.js packages with npm                            
ohai                 Returns inventory data from `Ohai'                          
open_iscsi           Manage iscsi targets with open-iscsi                        
openbsd_pkg          Manage packages on OpenBSD.                                 
openvswitch_bridge   Manage Open vSwitch bridges                                 
openvswitch_port     Manage Open vSwitch ports                                   
opkg                 Package manager for OpenWrt                                 
osx_say              Makes an OSX computer to speak.                             
ovirt                oVirt/RHEV platform management                              
pacman               Package manager for Archlinux                               
pagerduty            Create PagerDuty maintenance windows                        
pause                Pause playbook execution                                    
ping                 Try to connect to host and return `pong' on success.        
pingdom              Pause/unpause Pingdom alerts                                
pip                  Manages Python library dependencies.                        
pkgin                Package manager for SmartOS                                 
pkgng                Package manager for FreeBSD >= 9.0                          
pkgutil              Manage CSW-Packages on Solaris                              
portinstall          Installing packages from FreeBSD's ports system             
postgresql_db        Add or remove PostgreSQL databases from a remote host.      
postgresql_privs     Grant or revoke privileges on PostgreSQL database objects...
postgresql_user      Adds or removes a users (roles) from a PostgreSQL database..
quantum_floating_ip  Add/Remove floating IP from an instance                     
quantum_floating_ip_associate Associate or disassociate a particular floating IP with an i
quantum_network      Creates/Removes networks from OpenStack                     
quantum_router       Create or Remove router from openstack                      
quantum_router_gateway set/unset a gateway interface for the router with the specif
quantum_router_interface Attach/Dettach a subnet's interface to a router             
quantum_subnet       Add/Remove floating IP from an instance                     
rabbitmq_parameter   Adds or removes parameters to RabbitMQ                      
rabbitmq_plugin      Adds or removes users to RabbitMQ                           
rabbitmq_user        Adds or removes users to RabbitMQ                           
rabbitmq_vhost       Manage the state of a virtual host in RabbitMQ              
raw                  Executes a low-down and dirty SSH command                   
rax                  create / delete an instance in Rackspace Public Cloud       
rax_clb              create / delete a load balancer in Rackspace Public Cloud...
rax_clb_nodes        add, modify and remove nodes from a Rackspace Cloud Load Bal
rax_facts            Gather facts for Rackspace Cloud Servers                    
rax_network          create / delete an isolated network in Rackspace Public Clou
rds                  create or delete an Amazon rds instance                     
redhat_subscription  Manage Red Hat Network registration and subscriptions using 
redis                Various redis commands, slave and flush                     
rhn_channel          Adds or removes Red Hat software channels                   
rhn_register         Manage Red Hat Network registration using the `rhnreg_ks' co
riak                 This module handles some common Riak operations             
route53              add or delete entries in Amazons Route53 DNS service        
rpm_key              Adds or removes a gpg key from the rpm db                   
s3                   idempotent S3 module putting a file into S3.                
script               Runs a local script on a remote node after transferring it..
seboolean            Toggles SELinux booleans.                                   
selinux              Change policy and state of SELinux                          
service              Manage services.                                            
set_fact             Set host facts from a task                                  
setup                Gathers facts about remote hosts                            
shell                Execute commands in nodes.                                  
slurp                Slurps a file from remote nodes                             
stat                 retrieve file or file system status                         
subversion           Deploys a subversion repository.                            
supervisorctl        Manage the state of a program or group of programs running v
svr4pkg              Manage Solaris SVR4 packages                                
swdepot              Manage packages with swdepot package manager (HP-UX)        
synchronize          Uses rsync to make synchronizing file paths in your playbook
sysctl               Manage entries in sysctl.conf.                              
template             Templates a file out to a remote server.                    
unarchive            Copies archive to remote locations and unpacks them         
uri                  Interacts with webservices                                  
urpmi                Urpmi manager                                               
user                 Manage user accounts                                        
virt                 Manages virtual machines supported by libvirt               
wait_for             Waits for a condition before continuing.                    
xattr                set/retrieve extended attributes                            
yum                  Manages packages with the `yum' package manager             
zfs                  Manage zfs                                                  
zypper               Manage packages on SuSE and openSuSE                        
zypper_repository    Add and remove Zypper repositories                          


External link:
http://docs.ansible.com/intro.html

https://www.digitalocean.com/community/articles/how-to-install-and-configure-ansible-on-an-ubuntu-12-04-vps

No comments:

Post a Comment