-
[Ansible] List 변수를 다른 구분자로 변환DevOps/Ansible 2020. 3. 4. 17:08
ㅁ 상황
- Ansible Playbook에서 uri 모듈을 이용하여 HTTP GET 메서드로 데이터 정보를 가지고 오려고 한다.
- url에서 호출할 때 인벤토리에 'master'라는 그룹에 있는 호스트 서버 정보를 조회하려고 한다.
# vim tes.yml - name: 'Get system board api information' uri: url: "https://{{ system_url }}/api/web/index.php/system/api/v1/server/detail/{{ groups['master'] }}" validate_certs: false method: GET body_format: json headers: Content-Type: application/json status_code: 200 delegate_to: localhost register: get_api_result vars: system_url: 'test.com'
ㅁ 문제
- Ansible을 실행시키면 요청된 서버가 없다고 나오는데, 위 url 호출할 때 groups['master']에서 가져온 호스트네임이 조회가 되지 않는다는 내용이다.
- 아래 url 끝부분에 보면 ['test.com']로 List 변수 포맷으로 되어있어서 서버 정보를 정상적으로 조회하지 못했다.
# ansible-playbook main2.yml -vvv -i hosts ok: [test.com -> localhost] => { ... "content_type": "application/json", "invocation": { ... ... }, "json": { "code": "0001", "message": "요청된 hostname 또는 farmkey에 속하는 서버가 없습니다.", "data": [], "url": "https://test.com/api/web/index.php/system/api/v1/server/detail/['test.com']" }
ㅁ 해결
- 두 가지 해결 방안을 생각해보았는데, 코드 가독성을 높이기 위해서 두 번째 방법을 선택했다.
- 첫 번째, List 변수를 정규표현식을 사용하여 치환시켜주는 방법
ㄴ {{ groups['master] | regex_replace('\[|\]'.'') }} - 두 번째, List 변수를 join 필터를 사용하여 변환시켜주는 방법
ㄴ {{ groups['master'] | join('\n') }}
# vim tes.yml - name: 'Get system board api information' uri: url: "https://{{ system_url }}/api/web/index.php/system/api/v1/server/detail/{{ groups['master'] | join('\n') }}" validate_certs: false method: GET body_format: json headers: Content-Type: application/json status_code: 200 delegate_to: localhost register: get_api_result vars: system_url: 'test.com' # ansible-playbook main2.yml -vvv -i hosts ok: [test.com -> localhost] => { ... "content_type": "application/json", "invocation": { ... ... }, "json": { "code": "0001", "message": "조회 성공", "data": [ ... ], "url": "https://test.com/api/web/index.php/system/api/v1/server/detail/test.com" }
'DevOps > Ansible' 카테고리의 다른 글
[Ansible] Playbook Keyword (v 2.9) (0) 2020.03.04 [Ansible] YAML Syntax (0) 2020.02.29 [Ansible] Playbook Style Guide (0) 2020.01.21