Testar ssh/ansible com container docker

Estou estudando ansible a algum tempo, e geralmente esse tipo de curso sempre indica para fazer laboratório com vagrant ( uma espécie de automação para maquinas virtuais), porem como já estou também trabalhando com docker a um tempo, resolvi uni o útil ao agradável, porem a essência do docker é ser imutável e efêmero por isso quase não se encontra nada como se acessar container por ssh, por isso subi um código em debian para que possamos fazer isso! lets go….

Primeiro passo vamos clonar o código que subi no gitlab (lembrando que esse post, estamos contemplando que docker, git e ansible já esta instalado e configurado).

[deploy@server ~]$ git clone https://gitlab.com/ansible35/container-ssh.git
[deploy@server ~]$ cd container-ssh/

próximo passo buildar a imagem docker:

[deploy@server container-ssh]$
[deploy@server container-ssh]$ docker image build -t ssh .
....
Removing intermediate container 588c15d8ecf3
 ---> 73504f1430cf
Successfully built 73504f1430cf
Successfully tagged ssh:latest
[deploy@server container-ssh]$

agora vamos subir o container com a porta ssh (22) liberada no host espelhando no container:

[deploy@server container-ssh]$
[deploy@server container-ssh]$ docker container run -dit -p 22:22 --name debian-ssh --hostname debian-ssh ssh
[deploy@server container-ssh]$

nesse momento vamos acessar o container e preparar para receber as requisições do ansible fazer as tarefas de playbook ou ate mesmo comando adhoc. (o comando adduser é um script de debian então tem q executar “enters” ate terminar, lembrando de colocar a senha)
vamos seguir os passos abaixo:

[deploy@server container-ssh]$ docker container run -dit -p 22:22 --name debian-ssh --hostname debian-ssh ssh
c9e963813af07accf15734023287b90484471b9058eeeae52aba23453d406990
[deploy@server container-ssh]$ docker exec -it debian-ssh bash
root@debian-ssh:/# adduser deploy
root@debian-ssh:/# visudo

após executar o comando visudo, vamos inserir uma linha para que o usuário deploy não necessite colocar senha quando for usar o sudo (isso é opcional e estamos num ambiente de laboratório), ao abrir o arquivo colocar no fim a seguinte linha:

....
deploy  ALL=(ALL)       NOPASSWD: ALL
...

colocado essa linha, salvar o arquivo e sair do container com ctrl+D, apos sair do contianer vamos descubrir o ip do container para testar o ssh:

[deploy@server container-ssh]$
[deploy@server container-ssh]$ docker inspect debian-ssh | grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",

[deploy@server container-ssh]$

tendo IP em mãos, vamos fazer p acesso com ssh.

[deploy@server container-ssh]$
[deploy@server container-ssh]$ ssh deploy@172.17.0.2
deploy@172.17.0.2's password:
Linux debian-ssh 5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021 x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
deploy@debian-ssh:~$

feito o acesso reconhecido as chaves, saímos do ssh com comando crtl+D, e vamos para copiar as chaves do host para dentro do container e não precisar mais usando senha:

[deploy@server container-ssh]$ cd /home/deploy/.ssh/
[deploy@server .ssh]$ssh-copy-id -i deploy@172.17.0.2
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/dsribeiro/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
deploy@172.17.0.2's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'deploy@172.17.0.2'"
and check to make sure that only the key(s) you wanted were added.
[deploy@server ~]$ssh 'deploy@172.17.0.2'
Linux debian-ssh 5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021 x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Fri Oct  7 14:38:31 2022 from 172.17.0.1
deploy@debian-ssh:~$

agora já conseguimos fazer teste simples de ping com ansible, mas também já rodar a playbook (lembrando que tanto para playbook como para o comando adhoc com modulo ping tem que estar configurado hosts no ansible), vamos executar primeiro comando de ping:

[deploy@server ~]$ ansible -m ping ssh-debian
ssh-debian | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
[deploy@server ~]$

acima testamos a conexão sem senha usando comando adhoc e o modulo ping, agora vamos rodar playbook simples de atualização do sistema, e instalação de alguns softwares que não vem instalado por padrão para ter também a certeza que a playbook funcionou.

[deploy@server ~]$ docker exec -it debian-ssh bash
root@debian-ssh:/# nano
bash: nano: command not found
root@debian-ssh:/# htop
bash: htop: command not found
root@debian-ssh:/# links
bash: links: command not found
root@debian-ssh:/# telnet
bash: telnet: command not found
root@debian-ssh:/# git
bash: git: command not found
root@debian-ssh:/#
[deploy@server ~]$ cd container-ssh/
[deploy@server container-ssh]$ ansible-playbook playbook.yml -b
PLAY [default playbook - Starting deploy] ************************************************************************************************************************************************************************************
TASK [Gathering Facts] *******************************************************************************************************************************************************************************************************
ok: [ssh-debian]

TASK [update : update/upgrade system RH] *************************************************************************************************************************************************************************************
skipping: [ssh-debian]

TASK [update : update/upgrade system Debian] *********************************************************************************************************************************************************************************
[WARNING]: Updating cache and auto-installing missing dependency: python3-apt
changed: [ssh-debian]

TASK [update : Install a list of packages] ***********************************************************************************************************************************************************************************
changed: [ssh-debian]

PLAY RECAP *******************************************************************************************************************************************************************************************************************
ssh-debian                 : ok=1    changed=2   unreachable=0    failed=0    skipped=1    rescued=0    ignored=0

[deploy@server container-ssh]$

o código é simples mas ajuda pra fazer ate um troubleshooting com mais facilidade, espero ter deixado uma ajuda, caso queira ver se funcionou a playbook, entrar no container e ver algum software que estava na lista para instalar.

docker exec -it debian-ssh bash
root@debian-ssh:/# git
usage: git [--version] [--help] [-C <path>] [-c <name>=<value>]
           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
           [-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]
           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
           <command> [<args>]

These are common Git commands used in various situations:

start a working area (see also: git help tutorial)
   clone             Clone a repository into a new directory
   init              Create an empty Git repository or reinitialize an existing one

work on the current change (see also: git help everyday)
   add               Add file contents to the index
   mv                Move or rename a file, a directory, or a symlink
   restore           Restore working tree files
   rm                Remove files from the working tree and from the index
   sparse-checkout   Initialize and modify the sparse-checkout

examine the history and state (see also: git help revisions)
   bisect            Use binary search to find the commit that introduced a bug
   diff              Show changes between commits, commit and working tree, etc
   grep              Print lines matching a pattern
   log               Show commit logs
   show              Show various types of objects
   status            Show the working tree status

grow, mark and tweak your common history
   branch            List, create, or delete branches
   commit            Record changes to the repository
   merge             Join two or more development histories together
   rebase            Reapply commits on top of another base tip
   reset             Reset current HEAD to the specified state
   switch            Switch branches
   tag               Create, list, delete or verify a tag object signed with GPG

collaborate (see also: git help workflows)
   fetch             Download objects and refs from another repository
   pull              Fetch from and integrate with another repository or a local branch
   push              Update remote refs along with associated objects

'git help -a' and 'git help -g' list available subcommands and some
concept guides. See 'git help <command>' or 'git help <concept>'
to read about a specific subcommand or concept.
See 'git help git' for an overview of the system.
root@debian-ssh:/# telnet
telnet> quit
root@debian-ssh:/#


Deixe um comentário