---
schema_version: "1"
id: 01d1f73e7b13b8cf4d998e8a8425ee324986ed6baeae3fc8f020e9f8bf84352d
title: Jenkins Pipeline と Anypoint CLI を使用した Flex Gateway の自動化
collection: mulesoft
version: current
locale: ja-jp
portal_url: https://docs.salesforce.com/mulesoft/current/ja-jp/gateway/1.10/flex-conn-jenkins-cli.md
canonical_url: https://docs.mulesoft.com/jp/gateway/1.10/flex-conn-jenkins-cli
source_site: docs.mulesoft.com
content_type: documentation
content_hash: a977ae2eff5dcca25f32f5c252309c360db05a3b4b788bcf513d1990dd15d045
description: MuleSoft Documentation Site
release: "1.10"
latest: false
---
# Jenkins Pipeline と Anypoint CLI を使用した Flex Gateway の自動化

Jenkins Pipeline を使用して、接続モードでの Flex Gateway のワークフローを自動化できます。Jenkins Pipeline を使用すると、Flex Gateway を登録して実行し、Anypoint CLI の機能 (API インスタンスの作成やデプロイなど) を使用できます。

API Manager CLI のその他の機能を追加するには、[API Manager の CLI](https://docs.mulesoft.com/jp/anypoint-cli/latest/api-mgr)を参照してください。

このチュートリアルには、異なるコードブロックを含む異なる手順があります。手順を進めながら、コードブロックを同じ Jenkinsfile に追加します。Jenkins Pipeline で使用される構文についての詳細は、 [Jenkins Pipeline ドキュメント](https://www.jenkins.io/doc/book/pipeline/)​を参照してください。

<table><tbody><tr><td class="icon"><i class="fa icon-note" title="Note"></i></td><td class="content">Anypoint CLI を使用した Flex Gateway の自動化は、API Manager API を使用した Flex Gateway の自動化と多くの類似点があります。API Manger API 要求を使用して Flex Gateway を自動化するには、<a href="https://docs.mulesoft.com/jp/gateway/1.10/flex-conn-jenkins-api" class="xref page">Jenkins Pipeline と API Manager API を使用した Flex Gateway の自動化</a>を参照してください。</td></tr></tbody></table>

## [](#始める前に)始める前に

Jenkins Pipeline をデプロイする前に、次のタスクを完了します。

1. [Flex Gateway をダウンロードします](https://docs.mulesoft.com/jp/gateway/1.10/flex-install)​。
2. [接続アプリケーションを設定します](https://docs.mulesoft.com/jp/access-management/connected-apps-developers#create-a-connected-app)​。
    
    1. **\[App acts on its behalf (client credentials) (アプリケーションが自身のために行動する (クライアントログイン情報))\]**​ 種別を使用し、以下のスコープを含めます。
        
        - API Manager: **\[Manage API Configuration (API 設定の管理)\]**​、​**\[Manage Policies (ポリシーの管理)\]**​、​**\[View Policies (ポリシーの参照)\]**​、​**\[Deploy API Proxies (API プロキシのデプロイ)\]**
        - Runtime Manager: **\[Read Servers (サーバーの参照)\]**​ および ​**\[Manage Servers (サーバーの管理)\]**
        - Exchange: **\[Exchange Viewer (Exchange 閲覧者)\]**
        - 一般: **\[View Organization (組織の表示)\]**
    2. 設定する接続アプリケーションの ​**ID**​ と​**シークレット**​を保存します。
3. 作成または適用する Exchange アセット (API) のグループ ID、アセット ID、およびアセットバージョン (GAV) を収集します。
    
    Exchange から GAV を収集する手順は、次のとおりです。
    
    1. Exchange に移動します。
    2. 追加または適用するアセットを見つけます。
    3. URL からグループ ID とアセット ID を収集します。
        
        たとえば、API Manager API Exchange URL ​`https://anypoint.mulesoft.com/exchange/portals/anypoint-platform/f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform/api-manager-api/minor/1.0/pages/home/`​ から収集された ID は次のとおりです。
        
        - グループ ID: `f1e97bc6-315a-4490-82a7-23abe036327`
        - アセット ID: `api-manager-api`
    4. **\[Latest Stable (最新の安定バージョン)\]**​ からアセットのバージョンを収集します。
        
        たとえば、API Gateway HTTP 基本認証ポリシーテンプレートから収集されたバージョンは ​`1.3.2`​ です。
4. Anypoint Platform インスタンスから以下の情報を収集します。
    
    - Flex Gateway を実行する組織の​**組織 ID**
        
        詳細は、​[「組織 ID を見つける」](https://docs.mulesoft.com/jp/access-management/organization#find-your-organization-id)​を参照してください。
    - Flex Gateway を実行する環境の​**環境 ID**
        
        詳細は、​[「API Manager の外観」](https://docs.mulesoft.com/jp/api-manager/latest/latest-overview-concept#what-api-manager-looks-like)​を参照してください。

## [](#初期設定)初期設定

API インスタンスを作成して Flex Gateway にデプロイする前に、次の手順を完了する必要があります。

1. [役立つ関数を定義する](#define-useful-functions)​。
2. [役立つパラメーターを定義する](#define-useful-parameters)​。
3. [Anypoint CLI 4.x をインストールする](#install-anypoint-cli-4-x)​。
4. [登録して実行する](#register-and-run)​。

これらの Pipeline フェーズを実装したら、API を管理するための API Manager CLI 要求を作成して Pipeline をカスタマイズできます。

### [](#役立つ関数を定義する)役立つ関数を定義する

まず、Jenkinsfile で ​`pipeline`​ ブロックの前にこれらの役立つ関数を定義します。

```Jenkinsfile
def parseYamlFile(String file) {
    object = readYaml file: file
    return object
}

def getAPIInstanceID(String file) {
    return readFile(file: file).split(' ').last().replace('\n', '').trim()
}
```

### [](#役立つパラメーターを定義する)役立つパラメーターを定義する

Jenkins Pipeline のコマンドは一部のパラメーターを再利用するため、Jenkinsfile の先頭でパラメーターを定義すると役立ちます。

含まれているパラメーター定義をテンプレートとして使用して、追加の API またはポリシーに必要なパラメーターを定義することもできます。

パラメーターを定義する手順は、次のとおりです。

1. 次の情報を収集します。
    
    - `<your-org-id>`​: Flex Gateway を実行する組織の​**組織 ID**
    - `<your-env-id>`​: Flex Gateway を実行する組織の​**環境 ID**
    - `<gateway-version>`​: 使用している Flex Gateway のバージョン (例: `1.4.0`​)
    - `<connected-app-client-id>`​: 接続アプリケーションの ​**ID**
    - `<connected-app-client-secret>`​: 接続アプリケーションの​**シークレット**​。
    - API GAV:
        
        - `<asset-group-id>`​: Exchange から取得したグループ ID
        - `<asset-id-from-exchange>`​: Exchange から取得した、作成する API のアセット ID
        - `<asset-version>`​: Exchange から取得した、作成する API のアセットバージョン
    - `<gateway-name>`​: Flex ゲートウェイの名前
2. サンプルコンテンツを置き換えたら、パラメーター定義を Jenkinsfile に追加して、すべてのパラメーターが存在するかどうかを検証します。​`stages`​ ブロックの前の ​`pipeline`​ ブロックでパラメーターを定義します。
    
    ```Jenkinsfile
    parameters {
        string(name: 'ENV_ID', defaultValue: '<your-env-id>', description: 'Your environment id')
        string(name: 'ORG_ID', defaultValue: '<your-org-id>', description: 'Your organization id')
        string(name: 'FLEX_VERSION', defaultValue: '<gateway-version>', description: 'Flex version to run')
        string(name: 'CONNECTED_APP_CLIENT_ID', defaultValue: '<connected-app-client-id>', description: 'Your connected app client id')
        string(name: 'CONNECTED_APP_CLIENT_SECRET', defaultValue: '<connected-app-client-secret', description: 'Your connected app client secret')
        string(name: 'EXCHANGE_ASSET_ID', defaultValue: '<asset-id-from-exchange>', description: 'The id of the http api exchange asset')
        string(name: 'EXCHANGE_ASSET_VERSION', defaultValue: '<asset-version>', description: 'The version of the http api exchange asset')
        string(name: 'GATEWAY_NAME', defaultValue: '<gateway-name>', description: 'Unique gateway name')
    }
    ```
3. Jenkinsfile で check parameters ​`stage`​ を ​`stages`​ ブロックに追加します。
    
    ```Jenkinsfile
    stage('Check parameters') {
        steps {
            script {
                if (!params.ENV_ID || !params.ORG_ID || !params.GATEWAY_NAME || !params.FLEX_VERSION || !params.CONNECTED_APP_CLIENT_ID || !params.CONNECTED_APP_CLIENT_SECRET || !params.EXCHANGE_ASSET_ID || !params.EXCHANGE_ASSET_VERSION)  {
                    error("Not all parameters where specified")
                }
            }
        }
    }
    ```
    
    このフェーズが失敗した場合は、不足しているパラメーターを指定して Pipeline を再実行します。

## [](#anypoint-cli-4-x-のインストール)Anypoint CLI 4.x のインストール

Anypoint CLI 4.x を Docker コンテナにインストールするには、Jenkinsfile で ​`install Anypoint CLI 4.x`​ stage を ​`stages`​ ブロックに追加します。

```Jenkinsfile
stage('Install anypoint-cli-v4') {
    steps {
        script {
            sh """
                docker run --name container-anypoint-cli-v4 -d node:16 \
                sh -c " npm install -g anypoint-cli-v4 ; anypoint-cli-v4 plugins:install anypoint-cli-api-mgr-plugin; \
                while :; do sleep 1; done"
            """
            sh """
                docker exec container-anypoint-cli-v4 \
                sh -c "while ! anypoint-cli-v4 plugins 2> /dev/null | grep -q "anypoint-cli-api-mgr-plugin"; do :; done"
            """
        }
    }
}
```

### [](#登録して実行する)登録して実行する

Jenkinsfile で登録フェーズと実行フェーズを ​`stages`​ ブロックに追加します。

```Jenkinsfile
stage('Register flex gateway') {
   steps {
       script {
           sh """
               docker run --entrypoint flexctl \
                -v ${pwd()}:/registration -u 0 mulesoft/flex-gateway:${params.FLEX_VERSION} \
                register \
                --client-id=${params.CONNECTED_APP_CLIENT_ID} \
                --client-secret=${params.CONNECTED_APP_CLIENT_SECRET} \
                --environment=${params.ENV_ID} \
                --connected=true \
                --organization=${params.ORG_ID} \
                --output-directory=/registration \
                ${params.GATEWAY_NAME}
           """

           sh """
               grep "name: registration" registration.yaml
           """
       }
   }
}


stage('Run flex gateway') {
    steps {
        script {
            sh """
                docker run --name flex-gw -d \
                -v ${pwd()}:/usr/local/share/mulesoft/flex-gateway/conf.d \
                -p 8082:8082 \
                mulesoft/flex-gateway:${params.FLEX_VERSION}
            """
        }
    }
}
```

## [](#api-インスタンスを作成する)API インスタンスを作成する

Anypoint CLI 4.x をインストールしたら、API インスタンスを作成して Flex Gateway にデプロイできます。

このステップを繰り返して、複数の API インスタンスを追加できます。その他の API 設定フラグについては、​[api-mgr:api:manage コマンド](https://docs.mulesoft.com/jp/anypoint-cli/latest/api-mgr#api-mgr-api-manage)​を参照してください。

Jenkinsfile で create API instance ​`stage`​ を ​`stages`​ ブロックに追加します。

```Jenkinsfile
stage("Create API Instance") {
    steps {
        script {
            sh """
                docker exec container-anypoint-cli-v4 anypoint-cli-v4 api-mgr:api:manage ${params.EXCHANGE_ASSET_ID} ${params.EXCHANGE_ASSET_VERSION} \
                --client_id=${params.CONNECTED_APP_CLIENT_ID} --client_secret=${params.CONNECTED_APP_CLIENT_SECRET} \
                --isFlex --withProxy --deploymentType=hybrid --scheme=http --port=8082 \
                --uri=https://httpbin.org:443 --path=/httpbin > api-response
            """
        }
    }
}
```

<table><tbody><tr><td class="icon"><i class="fa icon-note" title="Note"></i></td><td class="content">たとえば、このフェーズでは、ポート ​<code>8082</code>​ および ​<code>/httpbin</code>​ パスでリスンし、​<code>https://httpbin.org/443</code>​ にプロキシする API インスタンスを作成します。</td></tr></tbody></table>

## [](#適用基本認証ポリシーを適用する)適用基本認証ポリシーを適用する

API インスタンスを作成したら、その API インスタンスにポリシーを適用できます。

このフェーズは ​[基本認証: 簡易ポリシー](https://docs.mulesoft.com/jp/gateway/1.10/policies-included-basic-auth-simple) as an example, but you can apply any Connected Mode policy. To find additional policies, see [Included Policies Directory](https://docs.mulesoft.com/jp/gateway/1.10/policies-included-directory)​ に適用されます。

ポリシーを適用する手順は次のとおりです。

1. 次の情報を収集します。
    
    - ポリシー GAV
        
        - `<policy-group-id>`​: Exchange のポリシーグループ ID (例: `68ef9520-24e9-4cf2-b2f5-620025690913`​)
        - `<policy-asset-id>`​:Exchange のポリシーアセット ID (例: `http-basic-authentication`​)
        - `<policy-asset-version>`​: Exchange のポリシーアセットバージョン (例: `1.3.2`​)
    - `"configurationData"`​: ポリシー設定データ
        
        設定データ項目はポリシーに依存します。基本認証: 簡易ポリシーでは、​`"username"`​ および ​`"password"`​ パラメーターが使用されます。
2. サンプルコンテンツを置き換えたら、Jenkinsfile で apply basic authentication policy ​`stage`​ を ​`stages`​ ブロックに追加します。

```Jenkinsfile
stage("Apply Basic Authentication Policy to API Instance") {
    steps {
        script {
            def apiInstanceId = getAPIInstanceID('api-response')
            sh """
                docker exec container-anypoint-cli-v4 anypoint-cli-v4 api-mgr:policy:apply ${apiInstanceId} 'http-basic-authentication' \
                --policyVersion='1.3.1' --groupId '68ef9520-24e9-4cf2-b2f5-620025690913' \
                --client_id=${params.CONNECTED_APP_CLIENT_ID} --client_secret=${params.CONNECTED_APP_CLIENT_SECRET} \
                -c '{"username": "user", "password": "test"}'
            """
        }
    }
}
```

<table><tbody><tr><td class="icon"><i class="fa icon-note" title="Note"></i></td><td class="content">たとえば、このフェーズでは、<a href="https://docs.mulesoft.com/jp/gateway/1.10/policies-included-basic-auth-simple" class="xref page">基本認証: 簡易ポリシー</a>に関連付けられたポリシー GAV および ​<code>"configurationData"</code>​ が使用されます。</td></tr></tbody></table>

## [](#api-インスタンスをデプロイする)API インスタンスをデプロイする

API インスタンスを作成したら、そのインスタンスをデプロイできます。

新しいインスタンスをデプロイするには、Jenkinsfile で deploy API ​`stage`​ を ​`stages`​ ブロックに追加します。

```Jenkinsfile
stage("Deploy API") {
    steps {
        script {
            sleep(time:15, unit:"SECONDS")
            def registration_file = parseYamlFile('registration.yaml')
            def apiInstanceId = getAPIInstanceID('api-response')

            sh """
                docker exec container-anypoint-cli-v4 anypoint-cli-v4 api-mgr:api:deploy ${apiInstanceId} \
                --client_id=${params.CONNECTED_APP_CLIENT_ID} --client_secret=${params.CONNECTED_APP_CLIENT_SECRET} \
                --target=${registration_file.spec.platformConnection.agentId[0]} --gatewayVersion=${params.FLEX_VERSION}
            """
        }
    }
}
```

## [](#api-インスタンスがデプロイされていることを検証する)API インスタンスがデプロイされていることを検証する

API インスタンスをデプロイしたら、Jenkinsfile で validate deployment ​`stage`​ を ​`stages`​ ブロックに追加して、インスタンスがデプロイされているかどうかを検証します。

```Jenkinsfile
stage("Validate Deployment") {
    steps {
        script {
            sleep(time:10, unit:"SECONDS")

            def unauthorized_status_code = sh(script: "curl -s -w \"%{http_code}\" -o /dev/null http://localhost:8082/httpbin/headers -v", returnStdout: true).trim().toInteger()
            if (unauthorized_status_code != 401) {
                error("401 status code expected but the status code obtained is ${unauthorized_status_code}")
            }

            def authorized_status_code = sh(script: "curl -s -w \"%{http_code}\" -o /dev/null http://localhost:8082/httpbin/headers -v -u user:test", returnStdout: true).trim().toInteger()
            if (authorized_status_code != 200) {
                error("200 status code expected but the status code obtained is ${unauthorized_status_code}")
            }
        }
    }
}
```

## [](#flex-gateway-を停止して登録ファイルをアーカイブする)Flex Gateway を停止して登録ファイルをアーカイブする

次のコードブロックを使用して、登録ファイルをアーカイブし、Flex Gateway を実行している Docker コンテナを削除します。​`stages`​ ブロックの後の ​`pipeline`​ ブロックに ​`post`​ ブロックを追加します。

```Jenkinsfile
post {
    success {
        script {
            // Archive the build output artifacts.
            archiveArtifacts artifacts: 'registration.yaml'
        }
    }
    always {
        script {
            sh(script: "docker rm -f container-anypoint-cli-v4 flex-gw")
        }
    }
}
```

## [](#関連情報)関連情報

- [Anypoint Platform CLI 4.x の使用開始](https://docs.mulesoft.com/jp/anypoint-cli/latest/)
- [接続モードで接続アプリケーションを使用した登録と実行](https://docs.mulesoft.com/jp/gateway/1.10/flex-conn-reg-run-app)​。
- [API Manager API を使用した Flex Gateway の管理](https://docs.mulesoft.com/jp/gateway/1.10/flex-conn-manage-public-api)