카테고리 없음

앤서블 로컬에 파일 있는지 체크하여 copy

Mussyan 2021. 1. 15. 10:05

Ansible copy file exist

Ansible에서 실제 기능을 수행하는 Roles의 기능들이 있다.

 

그 중 copy 기능은 로컬에 있는 파일을 목표 인스턴스의 목표 경로에 복사하는 역할을 한다.

 

이 때 파일 이름, 경로에 문자열 변수를 활용할 수 있어서 아래와 같이 입력값을 활용하여 필요한 파일을 결정할 수 있다.

- name: run aws-rule sh
  become: true
  become_user: USER
  shell:
    chdir: '/home/USER/bin/'
    cmd: './aws-rule-{{ rule_kind }}.sh {{ bucket_name }}'

 

하지만 위와 같이(예제는 쉘 스크립트 실행 명령어이나 형태는 같다) 활용할 경우 한 가지 문제점이 발생할 수 있다.

 

로컬에 해당 파일이 없는 경우엔 해당 작업 수행 시 앤서블이 멈춰버린다는 점이다.

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: If you are using a module and expect the file to exist on the remote, see the remote_src option
fatal: [{TARGET_IP}]: FAILED! => {"changed": false, "msg": "Could not find or access ~~~~~~ on the Ansible Controller.\nIf you are using a module and expect the file to exist on the remote, see the remote_src option"}

위와 같은 메세지와 함께 앤서블 FAILED 상태로 중단.

 

문자열 변수를 활용하여 입력값에 따른 파일을 활용하고자 할 때 충분히 발생할 수 있는 사항이다.

 

해결법으로는 로컬에 해당 파일이 존재하는지를 먼저 체크하고 존재할 경우에만 copy를 실행하는 것으로 코드는 아래와 같다.

- name: Ansible check file exists
  stat:
    path: ../../aws/iamrolepolicy-{{ rule_kind }}.json
  register: file_check

- name: upload optional config
  copy: src=../../aws/iamrolepolicy-{{ rule_kind }}.json dest=/home/USER/bin/iamrolepolicy-{{ rule_kind }}.json
  when: file_check.stat.exists

stat path로 해당 파일이 존재하는지 확인.

존재할 경우 register: 변수명에 상태값 입력

copy 시 when: 변수명.stat.exists로 파일이 존재하는지 파악하여 존재할 경우에만 실행하도록 할 수 있다.

TASK [rule : Ansible check file exists example.] ***************************************************************************************************
ok: [{TARGET_IP}]

TASK [rule : upload optional config] ***************************************************************************************************************
skipping: [{TARGET_IP}]

파일이 없을 경우 위와 같이 skipping.