Ansible Study

78 阅读4分钟

Ref

www.coursera.org/learn/divei…

github.com/spurin/dive…

github.com/spurin/dive…

diveinto.com/p/playgroun…

Lab

github.com/spurin/dive…

diveinto.com/p/playgroun…

ansible / password

This tutorial provides you with a fully working Ansible lab, accessible in your browser 🚀

Firstly, we'll clone the Dive Into Ansible lab. This is using a customised branch off the diveintoansible-lab repository that is A) preconfigured for use with Google cloudshell and B) has docker-compose preloaded in the bin directory (the default docker-compose on gcp cloudshell is too old). For convenience you can send this to the terminal using the convenient 'Copy to Cloud Shell' icon on the top right of the text box

git clone -b cloudshell-gcp <https://github.com/spurin/diveintoansible-lab.git> ${HOME}/diveintoansible-lab

In the Dive Into Ansible course, we configure SSH relationships as part of the course content.

If you are following the course and are yet to complete the lesson where we configure ssh keys between our hosts, do not run this step. However, if you have previously followed this lesson and wish to automate SSH connectivity between all virtual machines, saving you the time of re-doing this, you can do so by by executing the following command -

ssh-keygen -f ${HOME}/diveintoansible-lab/config/guest_ssh -P "" <<< y; cp -rf ${HOME}/diveintoansible-lab/config/guest_ssh ${HOME}/diveintoansible-lab/config/root_ssh; cp -rf ${HOME}/diveintoansible-lab/config/guest_ssh.pub ${HOME}/diveintoansible-lab/config/root_ssh.pub 

Launch the lab with the following commands -

cd ${HOME}/diveintoansible-lab; bin/docker-compose up --quiet-pull

When this completes, you'll see text similar to the following -

Attaching to centos2, ubuntu3, centos1, docker, ubuntu1, centos3, ubuntu2, ubuntu-c, portal

To access the Portal, click the Web Preview Icon, if you cant find it, click -> here for a walkthrough on where to find it.

Select 'Preview on Port 8080' and you're good to go!

Install Modules

ansible-galaxy collection install ansible.posix

Connectivity

image.png

  • add password.txt

echo password > password.txt

  • sshpass ssh-copy-id
#!/bin/bash

for user in ansible root
do
    for os in unbntu centos
    do
        for instance in 1 2 3
        do
            sshpass -f password.txt ssh-copy-id -o StrictHostKeyChecking=no ${user}@${os} ${instance}
        done
    done
done
  • Test
ANSIBLE_HOST_KEY_CHECKING=False ansible all -m ping

ansible all -m ping

ansible all -m ping -o

ansible -i,ubunut1,ubuntu2,ubuntu3,centos1,centos2,centos3 all -m ping

ssh-keygen -H -F ubuntu1

Test Code

github.com/spurin/dive…

git clone github.com/spurin/dive…

Architecture and Design

Ansible's core components include the following:

  • Control Node: This is the central node that orchestrates and manages the entire Ansible infrastructure. It is responsible for executing playbooks, managing inventory, and communicating with remote nodes.
  • Inventory: This is a list of remote nodes (or hosts) that Ansible will manage. It can include information such as the IP addresses, hostnames, and groups of the remote nodes.
  • Modules: Modules are the building blocks of Ansible. They are small, standalone programs that perform specific tasks on remote nodes, such as installing software, managing files, or running commands. Ansible has a wide range of built-in modules, and you can also create custom modules if needed.
  • Playbooks: Playbooks are the main configuration and orchestration language of Ansible. They are YAML-formatted files that describe the desired state of the remote nodes and the steps required to achieve that state. Playbooks can include multiple tasks, each task using a specific module to perform a particular operation.
  • Connections/Transports: Ansible uses various connections or transports to communicate with remote nodes. The most common transport is SSH, but Ansible also supports other protocols such as local, chroot, and paramiko (a Python library for SSHv2 protocols).

These core components work together to enable Ansible to automate the configuration, deployment, and management of IT infrastructure.

Configuration

ansible.cfg

ANSIBLE_CONFIG

Inventories

  • ansible.cfg
[defaults]
inventory = hosts
host_key_checking = False

[all]
centos
  • command
ansible all -m ping

ansible all -m ping -o

ansible ubuntu --list-hosts

ansible all --list-hosts
ansible centos1 -m ping -o
ansible ~.*3 --list-hosts

ansible host -m setup

ANSIBLE_HOST_KEY_CHECKING=False

Modules

Setup Module

Used for gathering facts when exectuting playbooks.

  • This module is automatically executed when using playbooks to gather useful information as varibles, about remote targets. The information can be used during execution
  • The Module can also be exeucted directly by the ansible command to find out the varibles available to a host
  • Ansible provide many 'facts' about a target automatically
  • This module is also suported for windows target
  • In Ansible 2.10, this has been moved to ansible-base and is classed as a ‘builtin' plugin, it can be referenced via the name setup or ansible.builtin.setup
  • Documentation - docs.ansible.com/ansible/lat…
ansible host -m setup
ansible host -m setup | more

File Module

Used for file, symlinks and directory manipulation

  • Sets attributes of files, symlinks and directories, or, removes files, symlinks and directories
  • Many other modules support the same options as the ‘file’ module, including [copy], [template] and [assemble]
  • For windows targets, use the [win_file] module instead
  • In Ansible 2.10, this has been moved to ansible-base and is classed as a ‘builtin' plugin, it can be referenced via the name fileor ansible.builtin.setup
  • Documentation - docs.ansible.com/ansible/lat…
ansible host -m file  -a 'path=/home/cms/tmp state=touch'

ansible host -m file  -a 'path=/home/cms/tmp state=file mode=600'
  • Unix permissions
  • Idempotency

Copy

ansible host -m copy -a 'src=/tmp/x dest=/tmp/y'

ansible host -m copy -a 'remote_src=yes src=/tmp/x dest=/tmp/y'

Command

ansible host -a 'hostname' -o

ansible host -a 'touch /tmp/test_command_module creates=/tmp/test_command_module'

ansible host -a 'touch /tmp/test_command_module removes=/tmp/test_command_module'

Fetch

docs.ansible.com/ansible/lat…

ansible host -m fetch -a 'src=/tmp/test_modules.txt dest=/tmp' -o 

ansible-doc file

Playbooks

Target Options

  • become
  • connection
  • gather_facts
---
# YAML documents begin with the document separator ---
 
# The minus in YAML this indicates a list item.  The playbook contains a list
# of plays, with each play being a dictionary
-
 
  # Hosts: where our play will run and options it will run with
  hosts: linux
 
  # Vars: variables that will apply to the play, on all target systems
  vars:
    motd_centos: "Welcome to CentOS Linux - Ansible Rocks\n"
    motd_ubuntu: "Welcome to Ubuntu Linux - Ansible Rocks\n"
 
  # Tasks: the list of tasks that will be executed within the playbook
  tasks:
    - name: Configure a MOTD (message of the day)
      copy:
        content: "{{ motd_centos }}"
        dest: /etc/motd
      notify: MOTD changed
      when: ansible_distribution == "CentOS"

    - name: Configure a MOTD (message of the day)
      copy:
        content: "{{ motd_ubuntu }}"
        dest: /etc/motd
      notify: MOTD changed
      when: ansible_distribution == "Ubuntu"
 
  # Handlers: the list of handlers that are executed as a notify key from a task
  handlers:
    - name: MOTD changed
      debug:
        msg: The MOTD was changed
 
  # Roles: list of roles to be imported into the play
 
# Three dots indicate the end of a YAML document
...
  • get description
ansible all -i centos2,ubuntu2 -m setup | grep ansible_decription

varibles

Facts

  • Can be written in any language
  • Returns a JSON structure
  • Returns an ini structure
  • By default, expects to use /etc/ansible/facts.d
ansible host -m setup -a 'gather_subnet=network' | more

ansible host -m setup -a 'filter=ansible_mem*'

image.png

Templating with Jinja2

  • The Jinja2 Templating Language
  • If / elif / else statements
  • for loops
  • break and continue
  • ranges
  • Jinja2 filters
  tasks:
    - name: Ansible Jinja2 if
      debug:
        msg: >
             --== Ansible Jinja2 if statement ==--
 
             {# If the hostname is ubuntu-c, include a message -#}
             {% if ansible_hostname == "ubuntu-c" -%}
                   This is ubuntu-c
             {% endif %}

ansible.cfg

[defaults]
inventory = hosts
host_key_checking = False
jinja2_extensions = jinja2.ext.loopcontrols

Creating Executing

  tasks:
    - name: Install EPEL
      yum:
        name: epel-release
        update_cache: yes
        state: latest
      when: ansible_distribution == 'CentOS'

    - name: Install Nginx CentOS
      yum:
        name: nginx
        update_cache: yes
        state: latest
      when: ansible_distribution == 'CentOS'

    - name: Install Nginx Ubuntu
      apt:
        name: nginx
        update_cache: yes
        state: latest
      when: ansible_distribution == 'Ubuntu'


     - name: Install Nginx
      package:
        name: nginx
        state: latest

    - name: Restart nginx
      service:
        name: nginx
        state: restarted
      notify: Check HTTP Service

  # Handlers: the list of handlers that are executed as a notify key from a task
  handlers:
    - name: Check HTTP Service
      uri:
        url: http://{{ ansible_default_ipv4.address }}
        status_code: 200