· 5 years ago · Oct 22, 2020, 01:46 PM
1Playbook task
2- name: Import cluster to Rancher
3 shell: "{{ lookup('file', 'import-cluster.sh') }}"
4
5 .....
6Contents of import-cluster.sh
7
8#!/bin/bash
9URL="..."
10CLUSTER_NAME=`echo ${HOSTNAME,,}`
11
12# Login to rancher
13LOGINRESPONSE=`curl -s "https://${URL}/v3-public/localProviders/local?action=login" -H 'content-type: application/json' --data-binary '{"username":"admin","password":"...."}' --insecure`
14LOGINTOKEN=`echo $LOGINRESPONSE | jq -r .token`
15
16# Create API key
17APIRESPONSE=`curl -s "https://${URL}/v3/token" -H 'content-type: application/json' -H "Authorization: Bearer $LOGINTOKEN" --data-binary '{"type":"token","description":"automation"}' --insecure`
18
19# Extract and store token
20APITOKEN=`echo $APIRESPONSE | jq -r .token`
21
22# Set server-url
23RANCHER_SERVER="${URL}"
24curl -s "https://${URL}/v3/settings/server-url" -H 'content-type: application/json' -H "Authorization: Bearer $APITOKEN" -X PUT --data-binary '{"name":"server-URL","value":"'https://$RANCHER_SERVER'"}' --insecure > /dev/null
25
26# Create cluster in Rancher
27CLUSTERRESPONSE=`curl -s "https://${URL}/v3/cluster" -H 'content-type: application/json' -H "Authorization: Bearer $APITOKEN" --data-binary '{"type":"cluster","name":"'${CLUSTER_NAME}'","import":true}' --insecure`
28
29# Extract clusterid to use for generating the docker run command
30CLUSTERID=`echo $CLUSTERRESPONSE | jq -r .id`
31
32# Generate token (clusterRegistrationToken) and extract nodeCommand
33AGENTCOMMAND=`curl -s "https://${URL}/v3/clusters/${CLUSTERID}/clusterregistrationtoken" -H 'content-type: application/json' -H "Authorization: Bearer $APITOKEN" --data-binary '{"type":"clusterRegistrationToken","clusterId":"'$CLUSTERID'"}' --insecure | jq -r .insecureCommand`
34
35# Run import command
36"${AGENTCOMMAND}"
37
38....
39
40Example content of AGENTCOMMAND:
41curl --insecure -sfL https://..../v3/import/whjq8qljwzrrtnxl2qc8wcm22nhdxrrsdbdv5hqpwl2fn2tjfwz68x.yaml | kubectl apply -f -
42