Ansible quick start

DevOps 2020. 1. 15. 17:50

====================================================================================

+. SSH Setup 

====================================================================================

$ sudo vi /etc/ssh/sshd_config

 ------------------------------------------

PermitRootLogin yes

PasswordAuthentication yes

 ------------------------------------------

$ sudo service ssh restart

$ ssh-keygen 

          --> /home/tomcat/.ssh/ansible/id_rsa

$ ssh-copy-id -i ~/.ssh/ansible/id_rsa root@130.210.105.28      (managed node user & host)

          --> copying 'public key' to remote server's 'authorized_keys

$ ssh 'root@130.210.105.28'  

$ ssh-copy-id -i ~/.ssh/ansible/id_rsa tomcat@130.210.105.28    (managed node user & host)

 

 >> https://code-maven.com/enable-ansible-passwordless-sudo

 

 

====================================================================================

+. SSH Setup - using different key files for each server

====================================================================================

$ ssh-keygen

   -> /home/tomcat/.ssh/ansible/id_rsa

$ ssh-copy-id -i ~/.ssh/ansible/id_rsa root@ssh.sever.com

$ ssh root@ssh.server.com

 

 

====================================================================================

+. Inventory file - simple example #01

====================================================================================

 ------------------------------------------

[dev]

localhost

 

[dev:vars]

ansible_ssh_private_key_file=~/.ssh/id_rsa

 

[all:vars]

ansible_python_interpreter=/usr/bin/python3

 ------------------------------------------

 

 

 

====================================================================================

+. Ansible ping

====================================================================================

$ ansible all -m ping -i ./e-hosts

   => SSH password error : set 'host_key_checking' to 'false'

     

      $ sudo vi /etc/ansible/ansible.cfg

      $ host_key_checking = False

 

 

====================================================================================

+. 'Missing sudo password' error

====================================================================================

 

$ sudo visudo

    %sudo   ALL=(ALL:ALL) NOPASSWD: ALL

 

 

 

 

 

 

====================================================================================

+. Playbook example #01 (ansible-playbook -i ../inv/local-hosts ../playbook/os-setup.yml)

====================================================================================

### ************************************************************************************* ###

---

#- hosts: all

- hosts: localhost

  become: true

#  vars_files:

#    - vars/default.yml

#

#   --- default.yml ---

#   ---

#   create_user: sammy

#   copy_local_key: "{{ lookup('file', lookup('env','HOME') + '/.ssh/id_rsa.pub') }}"

#   sys_packages: [ 'curl', 'vim', 'git', 'ufw']

#   --------------------

 

  tasks:

    - name: Install Prerequisites

      apt: name=aptitude update_cache=yes state=latest force_apt_get=yes

 

  # Sudo Group Setup

    - name: Make sure we have a 'wheel' group (create if not exists)

      group:

        name: wheel

        state: present

 

    - name: Allow 'wheel' group to have passwordless sudo

      lineinfile:

        path: /etc/sudoers

        state: present

        regexp: '^%wheel'

        line: '%wheel ALL=(ALL) NOPASSWD: ALL'

        validate: '/usr/sbin/visudo -cf %s'

        

  # User + Key Setup

    - name: Create a new regular user with sudo privileges

      user:

        name: "ansible01"

        state: present

        groups: wheel,tomcat

        append: true

        create_home: true

        shell: /bin/bash

        

#    - name: Set authorized key for remote user

#      authorized_key:

#        user: "ansible01"

#        state: present

#        key: "{{ copy_local_key }}"

 

    - name: Disable password authentication for root

      lineinfile:

        path: /etc/ssh/sshd_config

        state: present

        regexp: '^#?PermitRootLogin'

        line: 'PermitRootLogin prohibit-password'

 

#    - name: Add apt repository for Chrome

    - apt_repository:

        repo: deb http://dl.google.com/linux/chrome/deb/ stable main

        state: present

        filename: google-chrome

 

 

  # Install Packages

    - name: Update apt

      apt: update_cache=yes

 

    - name: Install required system packages

      apt: name=nmon,htop state=latest

 

# # UFW Setup

#    - name: UFW - Allow SSH connections

#      ufw:

#        rule: allow

#        name: OpenSSH

#

#    - name: UFW - Deny all other incoming traffic by default

#      ufw:

#        state: enabled

#        policy: deny

#        direction: incoming

 

 

# Remote shell execution

# # https://docs.ansible.com/ansible/latest/modules/shell_module.html

    - name: Create script test directory

      become: true

      become_user: root

      file:

         path: /opt/dev/ansible/tmp_work/ansible_filetest_01

         state: directory

         mode: "u=rwx,g=rwx,o=rwx"

 

    - name: Change to target directory & generate shell script.

      become: true

      become_user: tomcat

      shell:

         cmd: echo "echo \"Exec by Ansible\"" > ansible_test_script01.sh ; echo "date" >> ansible_test_script01.sh ; chmod u+x ansible_test_script01.sh  ; sleep 1

         chdir: /opt/dev/ansible/tmp_work/ansible_filetest_01

 

    - name: Execute shell script.

      become: true

      become_user: tomcat

      shell: /opt/dev/ansible/tmp_work/ansible_filetest_01/ansible_test_script01.sh >> ansible_test_log01.txt

      args:

         chdir: /opt/dev/ansible/tmp_work/ansible_filetest_01

 

# # SCP file copy from master to remote : define remote server to 'host' & defile source-master- to 'delegate_to' -> 'delegate_to' executes transfer process.

    - name: SCP file copy from master to remote.

      become: true

      become_user: root

      synchronize:

         src: /opt/dev/ansible/tmp_work/transfer_files

         dest: /opt/dev/ansible/tmp_work/ansible_filetest_01

      delegate_to: localhost

 

    - name: Copy local file

      become: true

      become_user: tomcat

      copy:

        src: /opt/dev/ansible/tmp_work/transfer_files/src.txt

        dest: /opt/dev/ansible/tmp_work/transfer_files/src_copied.txt

 

#     - name: Remove script test file

#       become: true

#       become_user: root

#       file:

#          path: /opt/dev/ansible/tmp_work/ansible_filetest_01

#          state: absent

 

 

 

# # Disabling warnings

# - name: Using curl to connect to a host via SOCKS proxy (unsupported in uri). Ordinarily this would throw a warning.

#   shell: curl --socks5 localhost:9000 http://www.ansible.com

#   args:

#     warn: no

### ************************************************************************************* ###

 

 

====================================================================================

+. Playbook example #02 (ansible-playbook -i ../inv/local-hosts ../playbook/docker-ops.yml)

====================================================================================

### ************************************************************************************* ###

# # https://docs.ansible.com/ansible/latest/modules/docker_container_module.html !!!

---

#- hosts: all

- hosts: localhost

  become: true

 

  tasks:

#     - name: Remove container from all networks

#       docker_container:

#         name: ansible-docker-test

#         state: absent

#         purge_networks: yes

  

    - name: Create Docker container

      docker_container:

        name: ansible-docker-test

        image: ubuntu:18.04

        recreate: yes

        command: bash

        detach: true

        interactive: true

        tty: true

 

    - name: add docker container to inventory

      add_host:

        name: ansible-docker-test

        ansible_connection: docker

 

- hosts: ansible-docker-test

  gather_facts: false

  tasks:

 

    - name: update apt cache

      delegate_to: ansible-docker-test

      raw: apt -y update

 

    - name: install python

      delegate_to: ansible-docker-test

      raw: apt -y install python-minimal

 

#     - name: demonstrate that normal ansible modules work

#       file:

#         path: /etc/testdir

#         state: directory

 

    - name: Install python on docker

      delegate_to: ansible-docker-test

      raw: apt -y update && apt install -y python-minimal

### ************************************************************************************* ###

 

 

 

====================================================================================

+. Playbook example #03 ( https://docs.ansible.com/ansible/latest/modules/docker_container_module.html)

====================================================================================

### ************************************************************************************* ###

- name: Create a data container

  docker_container:

    name: mydata

    image: busybox

    volumes:

      - /data

 

- name: Re-create a redis container

  docker_container:

    name: myredis

    image: redis

    command: redis-server --appendonly yes

    state: present

    recreate: yes

    exposed_ports:

      - 6379

    volumes_from:

      - mydata

 

- name: Restart a container

  docker_container:

    name: myapplication

    image: someuser/appimage

    state: started

    restart: yes

    links:

     - "myredis:aliasedredis"

    devices:

     - "/dev/sda:/dev/xvda:rwm"

    ports:

     - "8080:9000"

     - "127.0.0.1:8081:9001/udp"

    env:

        SECRET_KEY: "ssssh"

        # Values which might be parsed as numbers, booleans or other types by the YAML parser need to be quoted

        BOOLEAN_KEY: "yes"

 

- name: Container present

  docker_container:

    name: mycontainer

    state: present

    image: ubuntu:14.04

    command: sleep infinity

 

- name: Stop a container

  docker_container:

    name: mycontainer

    state: stopped

 

- name: Start 4 load-balanced containers

  docker_container:

    name: "container{{ item }}"

    recreate: yes

    image: someuser/anotherappimage

    command: sleep 1d

  with_sequence: count=4

 

- name: remove container

  docker_container:

    name: ohno

    state: absent

 

- name: Syslogging output

  docker_container:

    name: myservice

    image: busybox

    log_driver: syslog

    log_options:

      syslog-address: tcp://my-syslog-server:514

      syslog-facility: daemon

      # NOTE: in Docker 1.13+ the "syslog-tag" option was renamed to "tag" for

      # older docker installs, use "syslog-tag" instead

      tag: myservice

 

- name: Create db container and connect to network

  docker_container:

    name: db_test

    image: "postgres:latest"

    networks:

      - name: "{{ docker_network_name }}"

 

- name: Start container, connect to network and link

  docker_container:

    name: sleeper

    image: ubuntu:14.04

    networks:

      - name: TestingNet

        ipv4_address: "172.1.1.100"

        aliases:

          - sleepyzz

        links:

          - db_test:db

      - name: TestingNet2

 

- name: Start a container with a command

  docker_container:

    name: sleepy

    image: ubuntu:14.04

    command: ["sleep", "infinity"]

 

- name: Add container to networks

  docker_container:

    name: sleepy

    networks:

      - name: TestingNet

        ipv4_address: 172.1.1.18

        links:

          - sleeper

      - name: TestingNet2

        ipv4_address: 172.1.10.20

 

- name: Update network with aliases

  docker_container:

    name: sleepy

    networks:

      - name: TestingNet

        aliases:

          - sleepyz

          - zzzz

 

- name: Remove container from one network

  docker_container:

    name: sleepy

    networks:

      - name: TestingNet2

    purge_networks: yes

 

- name: Remove container from all networks

  docker_container:

    name: sleepy

    purge_networks: yes

 

- name: Start a container and use an env file

  docker_container:

    name: agent

    image: jenkinsci/ssh-slave

    env_file: /var/tmp/jenkins/agent.env

 

- name: Create a container with limited capabilities

  docker_container:

    name: sleepy

    image: ubuntu:16.04

    command: sleep infinity

    capabilities:

      - sys_time

    cap_drop:

      - all

 

- name: Finer container restart/update control

  docker_container:

    name: test

    image: ubuntu:18.04

    env:

      arg1: "true"

      arg2: "whatever"

    volumes:

      - /tmp:/tmp

    comparisons:

      image: ignore   # don't restart containers with older versions of the image

      env: strict   # we want precisely this environment

      volumes: allow_more_present   # if there are more volumes, that's ok, as long as `/tmp:/tmp` is there

 

- name: Finer container restart/update control II

  docker_container:

    name: test

    image: ubuntu:18.04

    env:

      arg1: "true"

      arg2: "whatever"

    comparisons:

      '*': ignore  # by default, ignore *all* options (including image)

      env: strict   # except for environment variables; there, we want to be strict

 

- name: Start container with healthstatus

  docker_container:

    name: nginx-proxy

    image: nginx:1.13

    state: started

    healthcheck:

      # Check if nginx server is healthy by curl'ing the server.

      # If this fails or timeouts, the healthcheck fails.

      test: ["CMD", "curl", "--fail", "http://nginx.host.com"]

      interval: 1m30s

      timeout: 10s

      retries: 3

      start_period: 30s

 

- name: Remove healthcheck from container

  docker_container:

    name: nginx-proxy

    image: nginx:1.13

    state: started

    healthcheck:

      # The "NONE" check needs to be specified

      test: ["NONE"]

 

- name: start container with block device read limit

  docker_container:

    name: test

    image: ubuntu:18.04

    state: started

    device_read_bps:

      # Limit read rate for /dev/sda to 20 mebibytes per second

      - path: /dev/sda

        rate: 20M

    device_read_iops:

      # Limit read rate for /dev/sdb to 300 IO per second

      - path: /dev/sdb

        rate: 300

### ************************************************************************************* ###

 

 

'DevOps' 카테고리의 다른 글

Ping Test for Tomcat AJP connector  (0) 2020.01.15
GitLab with Docker Image official guide (GitLab)  (0) 2020.01.15
docker cli #01  (0) 2020.01.15
Git cheat sheet #02  (0) 2020.01.15
Git cheat sheet #01  (0) 2020.01.15
블로그 이미지

Melting

,