Skip to content
This repository was archived by the owner on Oct 17, 2024. It is now read-only.

Latest commit

 

History

History
380 lines (264 loc) · 13.2 KB

adhoc-ansible.md

File metadata and controls

380 lines (264 loc) · 13.2 KB

Running Ansible

Running Ansible

  • There are two ways to run ansible:
    • ad hoc
      • Run a single task
      • ansible <pattern> [options]
    • Playbook
      • Run multiple tasks sequentially
      • ansible-playbook <pattern> [options]

Ad hoc tasks with Ansible

ansible [options]

  • Perform a few ad hoc operations with Ansible
    • Check connection to server
    • Install packages
    • Run system commands

Before we start

In all the following examples, $INTRO_ANSIBLE_DIR is the path to the introduction-to-ansible/sample-code directory.

$ echo $INTRO_ANSIBLE_DIR
/home/train/introduction-to-ansible/sample-code

Simulating a remote server

Vagrant-vm


    $ cd $INTRO_ANSIBLE_DIR/adhoc
    $ vagrant up --provider virtualbox
    .
    
    ==> default: Machine booted and ready!

If all went well you now have a remote host to manage!

Behind the scenes

  • Create SSH connection to a host or list of hosts (group) in parallel
  • Copy a small blob of executable code to each remote machine
  • Performs task: execute the code; capturing return code and output
  • Removes the blob of code
  • Closes the SSH connection
  • Report back on outcome of task

Connecting Ansible to a Host

  • Ansible works by creating an SSH connection with remote hosts
  • Need a way to tell Ansible how to connect to our Vagrant VM via SSH

The Inventory File

        <li class="fragment" data-fragment-index="0">
            A text file in <code>.ini</code> syntax
        </li>
        <li class="fragment" data-fragment-index="1">Identifies hosts for ansible to interact with
            <ul>
                <li>
                    Each host on a separate line
                </li>
            </ul>
        </li>
    
        <li class="fragment"
            data-fragment-index="2">Provides optional arguments after host
            <ul>
                <li>connection information</li>
                <li>
                    other arbitrary variables for
                    specific host
                </li>
            </ul>
        </li>
    
    </ul></div>
    
    
        #sample inventory
    
    web1.mycompany.com
    web2.mycompany.com
    app1.mycompany.com
    
    db.mycompany.com
    lb.mycompany.com
    
    [auckland]
    web1.mycompany.com
    
    [wellington]
    web2.mycompany.com
    

    Sample Inventory File

    [web]
    web1.mycompany.com ansible_host=152.240.43.12 opt2=arg2
    web2.mycompany.com
    
    [db]
    db1.mycompany.com
    
    [app]
    app1.mycompany.com
    app2.mycompany.com
    
    [lb]
    loadbalancer.mycompany.com

    Grouping Hosts

          <li class="fragment" data-fragment-index="0">
              `[sections]` used to organise hosts into
              <em>groups</em>
              <ul>
                  <li>functional roles</li>
                  <li>separate regions</li>
              </ul>
          </li>
          <li class="fragment" data-fragment-index="1">
              Either group or specific hosts can be used in
              ansible commands
          </li>
        
      
      </ul></div>
      <div class="fragment" data-fragment-index="0" style="width:50%;float:left">
          <pre style="font-size:13pt;"><code class="ini" data-trim>
              # sample inventory
              [web]
              web1.mycompany.com
              web2.mycompany.com
      
              [app]
              app1.mycompany.com
              app2.mycompany.com
      
              [wellington]
              web1.mycompany.com
              app1.mycompany.com
      
              [auckland]
              web2.mycompany.com
              app2.mycompany.com
      
          </code></pre>
      </div>
      

      Our first inventory file

      cat $INTRO_ANSIBLE_DIR/adhoc/hosts
      
      • Our inventory file specifies single remote host: _myserver_
      • To connect to our Vagrant VM we need to set some special connection variables
        • ansible_host
        • ansible_user
        • ansible_port
        • ansible_private_key_file
      • Variables specified on same line as host
      Exercise: Edit your inventory file to fill in missing connection information
      $ vagrant ssh-config
      Host default
          HostName ???
          User ???
          Port ???
          .
          IdentityFile ???
          .
          
      

      Use the values from your host to fill in missing arguments in ansible/hosts

      Running ad hoc commands with Ansible

      ansible <host pattern> [OPTIONS]

      • host pattern can be:
        • the name of a specific host in inventory
        • a group of hosts from the inventory
      Option Argument Description
      -m string module name to execute; default to command module
      -a string arguments to module
      -i string path to inventory file
      -b Privilege escalation
      --become-method string which become method to use; default is sudo
      Exercise: Ping remote host
      [ping](http://docs.ansible.com/ansible/latest/ping_module.html) is an Ansible module that just checks whether or not Ansible can create a SSH sessions with hosts. Use the _ping_ module to check if our host accepts SSH connections
      
      $ ansible myserver -i ansible/hosts -m ping
      myserver | SUCCESS => {
          "changed": false,
          "ping": "pong"
      }

      The ansible.cfg File

      
      # sample ansible.cfg
      
      [defaults]
      inventory = hosts
      remote_user = vagrant
      private_key_file = .vagrant/machines/default/virtualbox/private_key
      host_key_checking = False
      
      • A configuration file where you can provide some defaults for ansible
      • .ini syntax
      • Specify SSH connection, which inventory file to use

      Locating ansible.cfg

      • 4 possible locations in order of priority
        • File specified by ANSIBLE_CONFIG
        • Current directory (ansible.cfg)
        • Home directory (~/.ansible.cfg)
        • `/etc/ansible/ansible.cfg`
      Exercise: Set up ansible.cfg and modify inventory file
      cat $INTRO_ANSIBLE_DIR/ansible.cfg.sample
      
      
      
      cd $INTRO_ANSIBLE_DIR/adhoc
      cp ../ansible.cfg.sample ansible.cfg
      cat $INTRO_ANSIBLE_DIR/adhoc/hosts
      myserver ansible_host=127.0.0.1 ansible_port=2222
      

      You now no longer need to specify an inventory file

       $ ansible myserver -m ping

      Ansible Modules

      • Blob of python that performs a very specific action
      • Ship with Ansible
      • More than 200 [Ansible modules](https://docs.ansible.com/ansible/latest/list_of_all_modules.html)
      • When you run Ansible:
        • `scp` to temporary directory on target host
        • Execute python on target host
        • Returns JSON
        • Code removed from target host
        • Local Ansible evaluates returned JSON
        • Output for task based on returned values

      Ansible Output

      • The output for each task tells you the net effect of task execution
        • ok : no change was made
        • changed : A change was made to target
        • failed : Ansible was unable to change target
      • Exact interpretation will depend on task and module implementation

      The command module

      ansible <host pattern> -m command -a <args to command>

      Exercise: Get tail of system messages on your vagrant host
      • Use the command modules to tail the system log file
      • This will be /var/log/messages on centos
      
          $ ansible myserver  -b -a "tail /var/log/messages"
      
      Exercise: install a package
      • Use the yum module to install mtr (network monitoring tool)
      
          $ ansible myserver -b -m yum -a "name=mtr state=present"
      

      Module documentation

      Places you can find module documentation

      
          $ ansible-doc yum
      
          > YUM    (~/venv/local/lib/python2.7/site-packages/ansible/modules/packaging/os/yum.py)
      
                  Installs, upgrade, downgrades, removes, and lists packages and groups with the `yum' package manager.
      
          OPTIONS (= is mandatory):
      
          - allow_downgrade
                  Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting
                  allow_downgrade=True can make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete
                  list of specified packages to install (because dependencies between the downgraded package and others can cause changes to the packages which were in
                  the earlier transaction).
                  (Choices: yes, no)[Default: no]
                  version_added: 2.4
      

      Summary

      • This section has given you a small taste of using Ansible in ad hoc mode
      • Interacted with a remote server
        • Check if SSH works
        • Install OS packages
        • Start services
      • Explore documetation with ansible-doc

      Before we move on

      vagrant halt
      vagrant destroy